From 744bbcbed820a7ff8fe372623cfcb1ddcabecc29 Mon Sep 17 00:00:00 2001 From: Shruti Iyer <9905402+shrutiyer@users.noreply.github.com> Date: Wed, 28 Jan 2026 17:47:28 -0500 Subject: [PATCH 01/84] Propagate OAI eval and run ids to the results (#44899) * Propagate oai eval and run ids to the results * Code formatter --------- Co-authored-by: Shruti Iyer --- .../ai/evaluation/_evaluate/_evaluate.py | 4 ++ .../ai/evaluation/_model_configurations.py | 1 + .../red_team/_utils/formatting_utils.py | 2 +- .../ai/evaluation/simulator/_simulator.py | 2 +- .../samples/aoai_score_model_grader_sample.py | 2 +- .../evaluation_samples_safety_evaluation.py | 2 +- .../samples/evaluation_samples_simulate.py | 2 +- .../samples/evaluation_samples_threshold.py | 2 +- .../samples/red_team_samples.py | 2 +- .../aoai_score_model_grader_sample_audio.py | 2 +- ...ai_score_model_grader_sample_audio_file.py | 2 +- .../aoai_score_model_grader_sample_image.py | 2 +- .../tests/unittests/test_evaluate.py | 56 +++++++++++++++++++ 13 files changed, 71 insertions(+), 10 deletions(-) diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_evaluate/_evaluate.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_evaluate/_evaluate.py index bbed43df792e..9758c0ab4632 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_evaluate/_evaluate.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_evaluate/_evaluate.py @@ -1052,6 +1052,10 @@ def _evaluate( # pylint: disable=too-many-locals,too-many-statements result_df_dict = results_df.to_dict("records") result: EvaluationResult = {"rows": result_df_dict, "metrics": metrics, "studio_url": studio_url} # type: ignore + if eval_run_info_list: + result["oai_eval_run_ids"] = [ + {"eval_group_id": info["eval_group_id"], "eval_run_id": info["eval_run_id"]} for info in eval_run_info_list + ] # _add_aoai_structured_results_to_results(result, LOGGER, kwargs.get("eval_meta_data")) eval_id: Optional[str] = kwargs.get("_eval_id") diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_model_configurations.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_model_configurations.py index 1dc5615363f0..916dec2984e4 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_model_configurations.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_model_configurations.py @@ -139,6 +139,7 @@ class Conversation(TypedDict): class EvaluationResult(TypedDict): metrics: Dict + oai_eval_run_ids: NotRequired[List[Dict[str, str]]] studio_url: NotRequired[str] rows: List[Dict] _evaluation_results_list: List[Dict] diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/formatting_utils.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/formatting_utils.py index 32a75bd4057e..5e3fcfedb115 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/formatting_utils.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/formatting_utils.py @@ -52,7 +52,7 @@ def get_strategy_name(attack_strategy: Union[AttackStrategy, List[AttackStrategy def get_flattened_attack_strategies( - attack_strategies: List[Union[AttackStrategy, List[AttackStrategy]]] + attack_strategies: List[Union[AttackStrategy, List[AttackStrategy]]], ) -> List[Union[AttackStrategy, List[AttackStrategy]]]: """Flatten complex attack strategies into individual strategies. diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/simulator/_simulator.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/simulator/_simulator.py index efed102a1350..18cc2ddc89a3 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/simulator/_simulator.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/simulator/_simulator.py @@ -426,7 +426,7 @@ def _parse_prompty_response(self, *, response: str) -> Dict[str, Any]: try: if isinstance(response, str): response = response.replace("\u2019", "'").replace("\u2018", "'") - response = response.replace("\u201C", '"').replace("\u201D", '"') + response = response.replace("\u201c", '"').replace("\u201d", '"') # Replace None with null response = response.replace("None", "null") diff --git a/sdk/evaluation/azure-ai-evaluation/samples/aoai_score_model_grader_sample.py b/sdk/evaluation/azure-ai-evaluation/samples/aoai_score_model_grader_sample.py index 6590d5754580..c5cfc5ae421c 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/aoai_score_model_grader_sample.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/aoai_score_model_grader_sample.py @@ -24,7 +24,7 @@ - AZURE_AI_PROJECT_ENDPOINT 2. Hub-based project (legacy): - AZURE_SUBSCRIPTION_ID - - AZURE_RESOURCE_GROUP_NAME + - AZURE_RESOURCE_GROUP_NAME - AZURE_PROJECT_NAME """ diff --git a/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_safety_evaluation.py b/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_safety_evaluation.py index b6fb7fb55396..06ed112a504f 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_safety_evaluation.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_safety_evaluation.py @@ -9,7 +9,7 @@ """ DESCRIPTION: These samples demonstrate usage of _SafetyEvaluation class with various _SafetyEvaluator instances. - + USAGE: python evaluation_samples_safety_evaluation.py diff --git a/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_simulate.py b/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_simulate.py index df82a6bd2cd1..870019541de2 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_simulate.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_simulate.py @@ -10,7 +10,7 @@ """ DESCRIPTION: These samples demonstrate usage of various classes and methods used to perform simulation in the azure-ai-evaluation library. - + USAGE: python evaluation_samples_simulate.py diff --git a/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_threshold.py b/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_threshold.py index 80cf780fd18e..67bf31ddee9e 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_threshold.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/evaluation_samples_threshold.py @@ -10,7 +10,7 @@ """ DESCRIPTION: These samples demonstrate usage of various classes and methods used to perform evaluation with thresholds in the azure-ai-evaluation library. - + USAGE: python evaluation_samples_threshold.py diff --git a/sdk/evaluation/azure-ai-evaluation/samples/red_team_samples.py b/sdk/evaluation/azure-ai-evaluation/samples/red_team_samples.py index 3550617c0e2d..30e2eb9d5022 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/red_team_samples.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/red_team_samples.py @@ -8,7 +8,7 @@ DESCRIPTION: These samples demonstrate usage of various classes and methods used in Red Team functionality within the azure-ai-evaluation library. - + USAGE: python red_team_samples.py diff --git a/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio.py b/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio.py index 651c302b21ac..6b6139d8e3ae 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio.py @@ -24,7 +24,7 @@ - AZURE_AI_PROJECT_ENDPOINT 2. Hub-based project (legacy): - AZURE_SUBSCRIPTION_ID - - AZURE_RESOURCE_GROUP_NAME + - AZURE_RESOURCE_GROUP_NAME - AZURE_PROJECT_NAME """ diff --git a/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio_file.py b/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio_file.py index 66810052c7ac..91b45a255805 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio_file.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_audio_file.py @@ -24,7 +24,7 @@ - AZURE_AI_PROJECT_ENDPOINT 2. Hub-based project (legacy): - AZURE_SUBSCRIPTION_ID - - AZURE_RESOURCE_GROUP_NAME + - AZURE_RESOURCE_GROUP_NAME - AZURE_PROJECT_NAME """ diff --git a/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_image.py b/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_image.py index 7cc04c445545..4e370005ef9e 100644 --- a/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_image.py +++ b/sdk/evaluation/azure-ai-evaluation/samples/score_model_multimodal/aoai_score_model_grader_sample_image.py @@ -24,7 +24,7 @@ - AZURE_AI_PROJECT_ENDPOINT 2. Hub-based project (legacy): - AZURE_SUBSCRIPTION_ID - - AZURE_RESOURCE_GROUP_NAME + - AZURE_RESOURCE_GROUP_NAME - AZURE_PROJECT_NAME """ diff --git a/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_evaluate.py b/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_evaluate.py index 65c05e31509e..7a5d53449a1c 100644 --- a/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_evaluate.py +++ b/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_evaluate.py @@ -1345,6 +1345,62 @@ def run_test(): assert len(empty_converted["_evaluation_results_list"]) == 0 assert empty_converted["_evaluation_summary"]["result_counts"]["total"] == 0 + @patch( + "azure.ai.evaluation._evaluate._evaluate._map_names_to_builtins", + return_value={}, + ) + @patch("azure.ai.evaluation._evaluate._evaluate._get_evaluation_run_results") + @patch("azure.ai.evaluation._evaluate._evaluate._begin_aoai_evaluation") + @patch("azure.ai.evaluation._evaluate._evaluate._preprocess_data") + def test_evaluate_returns_oai_eval_run_ids( + self, + mock_preprocess, + mock_begin, + mock_get_results, + _, + mock_model_config, + ): + df = pd.DataFrame([{"query": "hi"}]) + grader = AzureOpenAILabelGrader( + model_config=mock_model_config, + input=[{"content": "{{item.query}}", "role": "user"}], + labels=["positive", "negative", "neutral"], + passing_labels=["neutral"], + model="gpt-4o-2024-11-20", + name="labelgrader", + ) + mock_preprocess.return_value = { + "column_mapping": {}, + "evaluators": {}, + "graders": {"g": grader}, + "input_data_df": df, + "target_run": None, + "batch_run_client": None, + "batch_run_data": None, + } + mock_begin.return_value = [ + { + "client": None, + "eval_group_id": "grp1", + "eval_run_id": "run1", + "grader_name_map": {}, + "expected_rows": len(df), + } + ] + mock_get_results.return_value = ( + pd.DataFrame([{"outputs.g.score": 1}]), + {"g.pass_rate": 1.0}, + ) + + result = evaluate( + evaluators={"g": grader}, + data="dummy_path", + azure_ai_project=None, + ) + + assert "oai_eval_run_ids" in result + assert result["oai_eval_run_ids"] == [{"eval_group_id": "grp1", "eval_run_id": "run1"}] + @pytest.mark.unittest class TestTagsInLoggingFunctions: From 75d92fd95ca9cbe86e15f0f7a222aac08d7e9005 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Wed, 28 Jan 2026 18:06:58 -0800 Subject: [PATCH 02/84] Sync .github/workflows directory with azure-sdk-tools for PR 13552 (#44907) * Few more changes * review comment resolution- 5 --------- Co-authored-by: anannya03 Co-authored-by: Anannya Patra <40665106+anannya03@users.noreply.github.com> --- .github/workflows/event-processor.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/event-processor.yml b/.github/workflows/event-processor.yml index 6cb56cf060a4..ccdd463fbdce 100644 --- a/.github/workflows/event-processor.yml +++ b/.github/workflows/event-processor.yml @@ -51,6 +51,15 @@ jobs: echo "::add-mask::$LABEL_SERVICE_API_KEY" echo "LABEL_SERVICE_API_KEY=$LABEL_SERVICE_API_KEY" >> $GITHUB_ENV + APP_CONFIG_ENDPOINT=$(az keyvault secret show \ + --vault-name issue-labeler \ + -n app-config-endpoint \ + -o tsv \ + --query value) + + echo "::add-mask::$APP_CONFIG_ENDPOINT" + echo "APP_CONFIG_ENDPOINT=$APP_CONFIG_ENDPOINT" >> $GITHUB_ENV + # To run github-event-processor built from source, for testing purposes, uncomment everything # in between the Start/End-Build From Source comments and comment everything in between the # Start/End-Install comments @@ -95,6 +104,7 @@ jobs: # https://docs.github.com/en/actions/security-guides/automatic-token-authentication#about-the-github_token-secret GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} LABEL_SERVICE_API_KEY: ${{ env.LABEL_SERVICE_API_KEY }} + APP_CONFIG_ENDPOINT: ${{ env.APP_CONFIG_ENDPOINT }} - name: Archive github event data uses: actions/upload-artifact@v6 From 1aac080191e519e4fd7484cde92585fc348eb3a4 Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Thu, 29 Jan 2026 07:47:01 -0800 Subject: [PATCH 03/84] Add missing copyright headers and ensuring consistency across files in distro (#44908) * Add missing copyright headers and ensuring consistency across files * Remove sample test app * Added CHANGELOG --- sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md | 1 + .../azure/monitor/opentelemetry/_diagnostics/__init__.py | 5 +++++ .../samples/authentication/sample_managed_credential.py | 6 +++++- .../samples/authentication/sample_secret_credential.py | 6 +++++- .../samples/logging/custom_event.py | 6 +++++- .../samples/metrics/attributes.py | 5 ++++- .../samples/metrics/instruments.py | 6 +++++- .../samples/metrics/live_metrics.py | 6 +++++- .../azure-monitor-opentelemetry/samples/metrics/views.py | 5 ++++- .../samples/tracing/azure_ai_inference.py | 6 ++++++ .../samples/tracing/azure_blob_storage.py | 6 ++++++ .../samples/tracing/db_psycopg2.py | 1 + .../samples/tracing/django/sample/example/__init__.py | 5 ++++- .../samples/tracing/django/sample/example/admin.py | 6 +++++- .../samples/tracing/django/sample/example/apps.py | 6 +++++- .../tracing/django/sample/example/migrations/__init__.py | 5 ++++- .../samples/tracing/django/sample/example/models.py | 6 +++++- .../samples/tracing/django/sample/example/tests.py | 6 +++++- .../samples/tracing/django/sample/example/urls.py | 6 +++++- .../samples/tracing/django/sample/manage.py | 6 +++++- .../samples/tracing/django/sample/sample/__init__.py | 5 ++++- .../samples/tracing/django/sample/sample/asgi.py | 6 +++++- .../samples/tracing/django/sample/sample/settings.py | 6 +++++- .../samples/tracing/django/sample/sample/urls.py | 6 +++++- .../samples/tracing/django/sample/sample/wsgi.py | 6 +++++- .../samples/tracing/http_fastapi.py | 1 + .../samples/tracing/http_flask.py | 1 + .../samples/tracing/http_requests.py | 1 + .../samples/tracing/http_urllib.py | 1 + .../samples/tracing/http_urllib3.py | 1 + .../samples/tracing/instrumentation_options.py | 1 + .../samples/tracing/manually_instrumented.py | 1 + .../samples/tracing/sampling_configurations.py | 6 ++++++ .../tests/autoinstrumentation/test_configurator.py | 6 ++++++ .../tests/autoinstrumentation/test_distro.py | 6 ++++++ sdk/monitor/azure-monitor-opentelemetry/tests/conftest.py | 1 + .../tests/instrumentation/test_psycopg2.py | 1 + 37 files changed, 141 insertions(+), 20 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md index 496476fc53e9..5479d44d416d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md @@ -9,6 +9,7 @@ ### Bugs Fixed ### Other Changes +- Add missing copyright headers and ensure consistent formatting across files. ## 1.8.5 (2026-01-28) diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/__init__.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/__init__.py index e69de29bb2d1..0bdee620366b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py index dd8d8106e216..df0574f30d1b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """ An example to show an application using Opentelemetry tracing api and sdk with a Azure Managed Identity Credential. Credentials are used for Azure Active Directory/EntraId Authentication. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py index 8e3d5aea3973..45c32d689989 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """ An example to show an application using Opentelemetry tracing api and sdk with a Azure Client Secret Credential. Credentials are used for Azure Active Directory/EntraId Authentication. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/logging/custom_event.py b/sdk/monitor/azure-monitor-opentelemetry/samples/logging/custom_event.py index 93e4777f5b4c..a15fbf62be42 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/logging/custom_event.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/logging/custom_event.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """ An example to show an application using Opentelemetry logging sdk. Logging calls to the standard Python logging library are tracked and telemetry is exported to application insights with the AzureMonitorLogExporter. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py index 5060e721220f..7e676cc2d527 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py @@ -1,5 +1,8 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import metrics diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py index e62940a0ff4f..882218981dca 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from typing import Iterable from azure.monitor.opentelemetry import configure_azure_monitor diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py index b7e6b42407c5..742633419f4e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """ This example shows how configure live metrics to be enabled. It sets up a minimal example of sending dependency, trace and exception telemetry to demonstrate the capabilities and collection set of live metrics. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py index 2260e13a6607..1affc1dcd684 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py @@ -1,5 +1,8 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import metrics diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py index 727e01e36353..90e2caec8426 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py @@ -1,3 +1,9 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from os import environ import os diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py index f4b4877dd422..5a31c6e49dfc 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py @@ -1,3 +1,9 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from os import environ from azure.monitor.opentelemetry import configure_azure_monitor diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py index d69784e8e13e..c6897b15412a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + import psycopg2 from azure.monitor.opentelemetry import configure_azure_monitor diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/__init__.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/__init__.py index 5b7f7a925cc0..0bdee620366b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/__init__.py @@ -1,2 +1,5 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py index 3f8b9caa30c7..e1ceac9b70c3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from django.contrib import admin # Register your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/apps.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/apps.py index cfad6058d247..6be675c6738f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/apps.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/apps.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from django.apps import AppConfig diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/migrations/__init__.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/migrations/__init__.py index 5b7f7a925cc0..0bdee620366b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/migrations/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/migrations/__init__.py @@ -1,2 +1,5 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py index 526ea7fddb97..95f07cd2eeed 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from django.db import models # Create your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py index 7705f147602a..81c546d8d6f1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from django.test import TestCase # Create your tests here. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/urls.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/urls.py index 27499cbfbc19..bb3eb29b488c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/urls.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/urls.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from django.urls import path from . import views diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py index 222c1993146e..cb16334e3e45 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/__init__.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/__init__.py index 5b7f7a925cc0..0bdee620366b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/__init__.py @@ -1,2 +1,5 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py index a299d1a45763..0f2410b4887c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + # cSpell:disable """ ASGI config for sample project. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/settings.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/settings.py index 28f3b356de4a..6ae8bbf93bc5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/settings.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/settings.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """ Django settings for sample project. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/urls.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/urls.py index 851a91e5ce26..e7d5ceffd855 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/urls.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/urls.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """sample URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py index 28fbcdcc2cd7..c4ad859f4931 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py @@ -1,5 +1,9 @@ +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + """ WSGI config for sample project. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py index 096e5f757fe0..2abd4c3cd86a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + import fastapi import uvicorn diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py index 33c982f77389..4729866e540e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + from azure.monitor.opentelemetry import configure_azure_monitor # Configure Azure monitor collection telemetry pipeline diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py index d9a992fb4b87..66f8b1b09eeb 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + import logging import requests # type: ignore[import-untyped] diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py index 9b2568ef59f8..7b561922bfc6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + import logging from urllib import request diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py index 82cfdeb3f4dc..f14e57c08dbb 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + import logging import urllib3 diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/instrumentation_options.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/instrumentation_options.py index 6a307727696b..149601564518 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/instrumentation_options.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/instrumentation_options.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + from azure.monitor.opentelemetry import configure_azure_monitor # Enable or disable supported instrumentations with the instrumentation_options parameter diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py index feaa15f4f5da..19c9433f24d6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor from sqlalchemy import create_engine, text diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py index bb7e151a82b0..747b34312e22 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py @@ -1,3 +1,9 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py index c43021656bbb..97416438ecf1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py @@ -1,3 +1,9 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + import warnings from unittest import TestCase from unittest.mock import patch diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py index 623e5ed37069..65babb43144a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py @@ -1,3 +1,9 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License in the project root for +# license information. +# -------------------------------------------------------------------------- + from os import environ import warnings from unittest import TestCase diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/conftest.py b/sdk/monitor/azure-monitor-opentelemetry/tests/conftest.py index 87ce6297470c..e326362a530d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/conftest.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/conftest.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- + import os from tempfile import mkstemp diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py b/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py index 8c08d8605ab2..96fada6fd49f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License in the project root for # license information. # -------------------------------------------------------------------------- + import os import pytest import sys From 027c885baf33b3bd93887c0932718f8234ede40e Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Thu, 29 Jan 2026 09:45:37 -0800 Subject: [PATCH 04/84] Feature tracking for when customer sdkstats is disabled by the user (#44888) * Feature tracking for when customer sdkstats is disabled by the user * Added CHANGELOG and fixed indentation * Add CHANGELOG * Modify CHANGELOG --- .../azure-monitor-opentelemetry-exporter/CHANGELOG.md | 8 +++++--- .../exporter/statsbeat/customer/_customer_sdkstats.py | 2 -- .../opentelemetry/exporter/statsbeat/customer/_manager.py | 2 ++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index cda596fabf99..5c557160c402 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -8,7 +8,7 @@ - Add auto detection for application ID from connection string if not set ([#44644](https://github.com/Azure/azure-sdk-for-python/pull/44644)) - Add support for user id and authId -([#44662](https://github.com/Azure/azure-sdk-for-python/pull/44662)) + ([#44662](https://github.com/Azure/azure-sdk-for-python/pull/44662)) ### Breaking Changes @@ -19,10 +19,12 @@ ([#44852](https://github.com/Azure/azure-sdk-for-python/pull/44852)) ### Other Changes +- Feature tracking for when customer sdkstats is disabled by the user + ([#44888](https://github.com/Azure/azure-sdk-for-python/pull/44888)) - Update maximum size of custom properties -([#44684](https://github.com/Azure/azure-sdk-for-python/pull/44684)) + ([#44684](https://github.com/Azure/azure-sdk-for-python/pull/44684)) - Declare support for Python 3.13 and 3.14 -([#44550](https://github.com/Azure/azure-sdk-for-python/pull/44550)) + ([#44550](https://github.com/Azure/azure-sdk-for-python/pull/44550)) ## 1.0.0b46 (2025-12-04) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_customer_sdkstats.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_customer_sdkstats.py index 36cf51865df9..dfe5a586ce96 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_customer_sdkstats.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_customer_sdkstats.py @@ -3,7 +3,6 @@ from typing import TYPE_CHECKING -from azure.monitor.opentelemetry.exporter.statsbeat._state import set_statsbeat_customer_sdkstats_feature_set from ._state import get_customer_stats_manager @@ -21,7 +20,6 @@ def collect_customer_sdkstats(exporter: "BaseExporter") -> None: # type: ignore if not customer_stats.is_initialized: # The initialize method is thread-safe and handles double-initialization customer_stats.initialize(connection_string=exporter._connection_string) # type: ignore - set_statsbeat_customer_sdkstats_feature_set() def shutdown_customer_sdkstats_metrics() -> None: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_manager.py index c5f6f1f01f30..e0ffee9e281d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_manager.py @@ -32,6 +32,7 @@ get_compute_type, ) +from azure.monitor.opentelemetry.exporter.statsbeat._state import set_statsbeat_customer_sdkstats_feature_set from ._utils import get_customer_sdkstats_export_interval, categorize_status_code, is_customer_sdkstats_enabled @@ -62,6 +63,7 @@ def __init__(self): self._status = CustomerSdkStatsStatus.UNINITIALIZED else: self._status = CustomerSdkStatsStatus.DISABLED + set_statsbeat_customer_sdkstats_feature_set() self._counters = _CustomerSdkStatsTelemetryCounters() self._language = _CUSTOMER_SDKSTATS_LANGUAGE From 3a79dcc8ac3bcf26817b0161eb9160d9bf0a2b41 Mon Sep 17 00:00:00 2001 From: M-Hietala <78813398+M-Hietala@users.noreply.github.com> Date: Thu, 29 Jan 2026 11:58:27 -0600 Subject: [PATCH 05/84] adding tool trace tests (#44905) * adding tool tracing tests * adding tool trace tests * updating test recordings * review comment related changes, code formatting --- sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + sdk/ai/azure-ai-projects/assets.json | 2 +- .../telemetry/_responses_instrumentor.py | 4 +- .../telemetry/test_responses_instrumentor.py | 162 ++- .../test_responses_instrumentor_async.py | 182 +-- ...sponses_instrumentor_browser_automation.py | 544 +++++++++ ...s_instrumentor_browser_automation_async.py | 532 ++++++++ ...responses_instrumentor_code_interpreter.py | 798 ++++++++++++ ...ses_instrumentor_code_interpreter_async.py | 798 ++++++++++++ ...test_responses_instrumentor_file_search.py | 853 +++++++++++++ ...esponses_instrumentor_file_search_async.py | 854 +++++++++++++ .../test_responses_instrumentor_mcp.py | 1075 ++++++++++++++++ .../test_responses_instrumentor_mcp_async.py | 1076 +++++++++++++++++ .../test_responses_instrumentor_workflow.py | 847 +++++++++++++ ...t_responses_instrumentor_workflow_async.py | 836 +++++++++++++ sdk/ai/azure-ai-projects/tests/test_base.py | 1 + 16 files changed, 8423 insertions(+), 142 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 08840fce6a97..034b155b7702 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -21,6 +21,7 @@ * Rename class `MicrosoftFabricAgentTool` to `MicrosoftFabricPreviewTool`. * Rename class `SharepointAgentTool` to `SharepointPreviewTool`. * Rename class `ItemParam` to `InputItem`. +* Tracing: workflow actions in conversation item listings are now emitted as "gen_ai.conversation.item" events (with role="workflow") instead of "gen_ai.workflow.action" events in the list_conversation_items span. ## 2.0.0b3 (2026-01-06) diff --git a/sdk/ai/azure-ai-projects/assets.json b/sdk/ai/azure-ai-projects/assets.json index 490af2ec735e..cf8a8fe386d2 100644 --- a/sdk/ai/azure-ai-projects/assets.json +++ b/sdk/ai/azure-ai-projects/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/ai/azure-ai-projects", - "Tag": "python/ai/azure-ai-projects_6f9985fe6d" + "Tag": "python/ai/azure-ai-projects_7cddb7d06f" } diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py index de2939f9a30f..904f714fd7ae 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py @@ -3998,9 +3998,7 @@ def _add_conversation_item_event( # pylint: disable=too-many-branches,too-many- # Wrap in parts array for semantic convention compliance parts: List[Dict[str, Any]] = [{"type": "workflow_action", "content": workflow_details}] event_body = [{"role": role, "parts": parts}] - - # Use generic event name for workflow actions - event_name = GEN_AI_WORKFLOW_ACTION_EVENT + event_name = GEN_AI_CONVERSATION_ITEM_EVENT elif item_type == "message": # Regular message - use content format for consistency diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py index 3a7fbdff92ac..66fb4fb0972a 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py @@ -3989,30 +3989,38 @@ def test_workflow_agent_non_streaming_with_content_recording(self, **kwargs): assert "content" in part assert "status" in part["content"] - # Verify conversation items listing span also has workflow actions + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items - for event in list_workflow_events: + # Verify conversation item event content structure - check for workflow items + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # With content recording ON, action_id should be present - assert "action_id" in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # With content recording ON, action_id and previous_action_id should be present + assert ( + "action_id" in part["content"] + ), "action_id should be present when content recording is enabled" + assert ( + "previous_action_id" in part["content"] + ), "previous_action_id should be present when content recording is enabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @@ -4095,31 +4103,38 @@ def test_workflow_agent_non_streaming_without_content_recording(self, **kwargs): assert "action_id" not in part["content"] assert "previous_action_id" not in part["content"] - # Verify conversation items listing span also has workflow actions + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items (content recording OFF) - for event in list_workflow_events: + # Verify conversation item event content structure (content recording OFF) + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # action_id and previous_action_id should NOT be present when content recording is off - assert "action_id" not in part["content"] - assert "previous_action_id" not in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # action_id and previous_action_id should NOT be present when content recording is off + assert ( + "action_id" not in part["content"] + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in part["content"] + ), "previous_action_id should not be present when content recording is disabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @@ -4294,30 +4309,38 @@ def test_workflow_agent_streaming_with_content_recording(self, **kwargs): assert "content" in part assert "status" in part["content"] - # Verify conversation items listing span also has workflow actions + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items - for event in list_workflow_events: + # Verify conversation item event content structure - check for workflow items + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # With content recording ON, action_id should be present - assert "action_id" in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # With content recording ON, action_id and previous_action_id should be present + assert ( + "action_id" in part["content"] + ), "action_id should be present when content recording is enabled" + assert ( + "previous_action_id" in part["content"] + ), "previous_action_id should be present when content recording is enabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @@ -4405,31 +4428,38 @@ def test_workflow_agent_streaming_without_content_recording(self, **kwargs): assert "action_id" not in part["content"] assert "previous_action_id" not in part["content"] - # Verify conversation items listing span also has workflow actions + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items (content recording OFF) - for event in list_workflow_events: + # Verify conversation item event content structure (content recording OFF) + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # action_id and previous_action_id should NOT be present when content recording is off - assert "action_id" not in part["content"] - assert "previous_action_id" not in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # action_id and previous_action_id should NOT be present when content recording is off + assert ( + "action_id" not in part["content"] + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in part["content"] + ), "previous_action_id should not be present when content recording is disabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py index 31c65c8ea902..461abae0ce90 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py @@ -2899,30 +2899,38 @@ async def test_async_workflow_agent_non_streaming_with_content_recording(self, * assert "content" in part assert "status" in part["content"] - # Verify conversation items listing span also has workflow actions + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items - for event in list_workflow_events: + # Verify conversation item event content structure - check for workflow items + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # With content recording ON, action_id should be present - assert "action_id" in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # With content recording ON, action_id and previous_action_id should be present + assert ( + "action_id" in part["content"] + ), "action_id should be present when content recording is enabled" + assert ( + "previous_action_id" in part["content"] + ), "previous_action_id should be present when content recording is enabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @@ -3007,34 +3015,45 @@ async def test_async_workflow_agent_non_streaming_without_content_recording(self assert "content" in part assert "status" in part["content"] # action_id and previous_action_id should NOT be present when content recording is off - assert "action_id" not in part["content"] - assert "previous_action_id" not in part["content"] - - # Verify conversation items listing span also has workflow actions + assert ( + "action_id" not in part["content"] + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in part["content"] + ), "previous_action_id should not be present when content recording is disabled" + + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items (content recording OFF) - for event in list_workflow_events: + # Verify conversation item event content structure (content recording OFF) + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # action_id and previous_action_id should NOT be present when content recording is off - assert "action_id" not in part["content"] - assert "previous_action_id" not in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # action_id and previous_action_id should NOT be present when content recording is off + assert ( + "action_id" not in part["content"] + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in part["content"] + ), "previous_action_id should not be present when content recording is disabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @@ -3124,30 +3143,38 @@ async def test_async_workflow_agent_streaming_with_content_recording(self, **kwa assert "content" in part assert "status" in part["content"] - # Verify conversation items listing span also has workflow actions + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items - for event in list_workflow_events: + # Verify conversation item event content structure - check for workflow items + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # With content recording ON, action_id should be present - assert "action_id" in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # With content recording ON, action_id and previous_action_id should be present + assert ( + "action_id" in part["content"] + ), "action_id should be present when content recording is enabled" + assert ( + "previous_action_id" in part["content"] + ), "previous_action_id should be present when content recording is enabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @@ -3237,34 +3264,45 @@ async def test_async_workflow_agent_streaming_without_content_recording(self, ** assert "content" in part assert "status" in part["content"] # action_id and previous_action_id should NOT be present when content recording is off - assert "action_id" not in part["content"] - assert "previous_action_id" not in part["content"] - - # Verify conversation items listing span also has workflow actions + assert ( + "action_id" not in part["content"] + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in part["content"] + ), "previous_action_id should not be present when content recording is disabled" + + # Verify conversation items listing span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) >= 1 list_span = list_spans[0] - # Check for workflow action events in list items span - list_workflow_events = [e for e in list_span.events if e.name == "gen_ai.workflow.action"] - assert len(list_workflow_events) > 0 + # Check for conversation item events in list items span + list_item_events = [e for e in list_span.events if e.name == "gen_ai.conversation.item"] + assert len(list_item_events) > 0 - # Verify workflow event content structure in list items (content recording OFF) - for event in list_workflow_events: + # Verify conversation item event content structure (content recording OFF) + found_workflow_item = False + for event in list_item_events: content_str = event.attributes.get("gen_ai.event.content", "[]") content = json.loads(content_str) assert isinstance(content, list) - assert len(content) == 1 - assert content[0]["role"] == "workflow" - assert "parts" in content[0] - assert len(content[0]["parts"]) == 1 - part = content[0]["parts"][0] - assert part["type"] == "workflow_action" - assert "content" in part - assert "status" in part["content"] - # action_id and previous_action_id should NOT be present when content recording is off - assert "action_id" not in part["content"] - assert "previous_action_id" not in part["content"] + for item in content: + if item.get("role") == "workflow": + found_workflow_item = True + assert "parts" in item + assert len(item["parts"]) >= 1 + part = item["parts"][0] + assert part["type"] == "workflow_action" + assert "content" in part + assert "status" in part["content"] + # action_id and previous_action_id should NOT be present when content recording is off + assert ( + "action_id" not in part["content"] + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in part["content"] + ), "previous_action_id should not be present when content recording is disabled" + assert found_workflow_item, "Should have found workflow items in conversation items" @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py new file mode 100644 index 000000000000..b17e6d197a0c --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py @@ -0,0 +1,544 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Tests for ResponsesInstrumentor with browser automation agents. +""" +import os +import pytest +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils import recorded_by_proxy, RecordedTransport +from azure.ai.projects.models import PromptAgentDefinition + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorBrowserAutomation(TestAiAgentsInstrumentorBase): + """Tests for ResponsesInstrumentor with browser automation agents.""" + + # ======================================== + # Sync Browser Automation Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_browser_automation_non_streaming_with_content_recording(self, **kwargs): + """Test synchronous browser automation agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id, + ) + ) + ) + + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are an Agent helping with browser automation tasks.""", + tools=[tool], + ), + ) + + try: + conversation = openai_client.conversations.create() + response = openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response.output is not None + assert len(response.output) > 0 + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + tool_call_events = [e for e in span.events if e.name == "gen_ai.output.messages"] + assert len(tool_call_events) > 0 + found_browser_tool = False + for event in tool_call_events: + if event.attributes and "gen_ai.event.content" in event.attributes: + content = event.attributes["gen_ai.event.content"] + if isinstance(content, str) and "browser_automation_preview_call" in content: + found_browser_tool = True + assert "arguments" in content or "query" in content + assert found_browser_tool + + # Comprehensive event content validation - verify content IS present + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Check that content fields ARE present with content recording ON + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + + openai_client.conversations.delete(conversation_id=conversation.id) + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_browser_automation_non_streaming_without_content_recording(self, **kwargs): + """Test synchronous browser automation agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id, + ) + ) + ) + + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are an Agent helping with browser automation tasks.""", + tools=[tool], + ), + ) + + try: + conversation = openai_client.conversations.create() + response = openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + tool_call_events = [e for e in span.events if e.name == "gen_ai.output.messages"] + for event in tool_call_events: + if event.attributes and "gen_ai.event.content" in event.attributes: + content = event.attributes["gen_ai.event.content"] + if isinstance(content, str) and "browser_automation_preview_call" in content: + assert '"id"' in content + + # Comprehensive event content validation - verify content is NOT present + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Check that content fields are NOT present with content recording OFF + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + + openai_client.conversations.delete(conversation_id=conversation.id) + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Sync Browser Automation Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_browser_automation_streaming_with_content_recording(self, **kwargs): + """Test synchronous browser automation agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + {CONTENT_TRACING_ENV_VARIABLE: "True", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} + ) + self.setup_telemetry() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id + ) + ) + ) + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, instructions="""Browser automation helper.""", tools=[tool] + ), + ) + + try: + conversation = openai_client.conversations.create() + stream = openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + for _ in stream: + pass + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + tool_call_events = [e for e in span.events if e.name == "gen_ai.output.messages"] + assert len(tool_call_events) > 0 + + openai_client.conversations.delete(conversation_id=conversation.id) + # Strict event content checks for response generation span (after span assignment) + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("user", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + # Validate content fields ARE present when content recording is enabled + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_browser_automation_streaming_without_content_recording(self, **kwargs): + """Test synchronous browser automation agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + {CONTENT_TRACING_ENV_VARIABLE: "False", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} + ) + self.setup_telemetry() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id + ) + ) + ) + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition(model=deployment_name, instructions="Browser helper.", tools=[tool]), + ) + + try: + conversation = openai_client.conversations.create() + stream = openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + for _ in stream: + pass + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Strict event content checks for response generation span (after span assignment) + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("user", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + # Validate content fields are NOT present when content recording is disabled + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + + openai_client.conversations.delete(conversation_id=conversation.id) + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py new file mode 100644 index 000000000000..ec677693213d --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py @@ -0,0 +1,532 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Async tests for ResponsesInstrumentor with browser automation agents. +""" +import os +import pytest +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import RecordedTransport +from azure.ai.projects.models import PromptAgentDefinition + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +import json + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorBrowserAutomationAsync(TestAiAgentsInstrumentorBase): + """Async tests for ResponsesInstrumentor with browser automation agents.""" + + # ======================================== + # Async Browser Automation Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_browser_automation_non_streaming_with_content_recording(self, **kwargs): + """Test asynchronous browser automation agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + async with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id, + ) + ) + ) + + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are an Agent helping with browser automation tasks.""", + tools=[tool], + ), + ) + + try: + conversation = await openai_client.conversations.create() + response = await openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response.output is not None + assert len(response.output) > 0 + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + tool_call_events = [e for e in span.events if e.name == "gen_ai.output.messages"] + assert len(tool_call_events) > 0 + found_browser_tool = False + for event in tool_call_events: + if event.attributes and "gen_ai.event.content" in event.attributes: + content = event.attributes["gen_ai.event.content"] + if isinstance(content, str) and "browser_automation_preview_call" in content: + found_browser_tool = True + assert "arguments" in content or "query" in content + assert found_browser_tool + + # Comprehensive event content validation - verify content IS present + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Check that content fields ARE present with content recording ON + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + + await openai_client.conversations.delete(conversation_id=conversation.id) + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_browser_automation_non_streaming_without_content_recording(self, **kwargs): + """Test asynchronous browser automation agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + async with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id, + ) + ) + ) + + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are an Agent helping with browser automation tasks.""", + tools=[tool], + ), + ) + + try: + conversation = await openai_client.conversations.create() + response = await openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + tool_call_events = [e for e in span.events if e.name == "gen_ai.output.messages"] + for event in tool_call_events: + if event.attributes and "gen_ai.event.content" in event.attributes: + content = event.attributes["gen_ai.event.content"] + if isinstance(content, str) and "browser_automation_preview_call" in content: + assert '"id"' in content + + # Comprehensive event content validation - verify content is NOT present + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Check that content fields are NOT present with content recording OFF + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + + await openai_client.conversations.delete(conversation_id=conversation.id) + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Async Browser Automation Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_browser_automation_streaming_with_content_recording(self, **kwargs): + """Test asynchronous browser automation agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + {CONTENT_TRACING_ENV_VARIABLE: "True", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} + ) + self.setup_telemetry() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + async with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id + ) + ) + ) + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, instructions="""Browser automation helper.""", tools=[tool] + ), + ) + + try: + conversation = await openai_client.conversations.create() + stream = await openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + async for _ in stream: + pass + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + tool_call_events = [e for e in span.events if e.name == "gen_ai.output.messages"] + assert len(tool_call_events) > 0 + + # Strict event content checks for response generation span + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("user", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + # Validate content fields ARE present when content recording is enabled + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + + await openai_client.conversations.delete(conversation_id=conversation.id) + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_browser_automation_streaming_without_content_recording(self, **kwargs): + """Test asynchronous browser automation agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + {CONTENT_TRACING_ENV_VARIABLE: "False", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} + ) + self.setup_telemetry() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + browser_automation_connection_id = kwargs.get("browser_automation_project_connection_id") + assert deployment_name is not None + if browser_automation_connection_id is None: + pytest.skip("browser_automation_project_connection_id not configured") + + async with project_client: + openai_client = project_client.get_openai_client() + + from azure.ai.projects.models import ( + BrowserAutomationPreviewTool, + BrowserAutomationToolParameters, + BrowserAutomationToolConnectionParameters, + ) + + tool = BrowserAutomationPreviewTool( + browser_automation_preview=BrowserAutomationToolParameters( + connection=BrowserAutomationToolConnectionParameters( + project_connection_id=browser_automation_connection_id + ) + ) + ) + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition(model=deployment_name, instructions="Browser helper.", tools=[tool]), + ) + + try: + conversation = await openai_client.conversations.create() + stream = await openai_client.responses.create( + conversation=conversation.id, + tool_choice="required", + input=""" + Your task is to get the latests news story from Microsoft website. + Go to the website https://news.microsoft.com and click the "What's new today" link at the top of the page to open the latest + news stories and provide a summary of the most recent one. + """, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + async for _ in stream: + pass + + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Strict event content checks for response generation span - verify content recording is OFF + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("user", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + # Validate content fields are NOT present when content recording is disabled + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + + await openai_client.conversations.delete(conversation_id=conversation.id) + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py new file mode 100644 index 000000000000..e51478a6f554 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py @@ -0,0 +1,798 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Tests for ResponsesInstrumentor with Code Interpreter tool. +""" +import os +import pytest +from io import BytesIO +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils import recorded_by_proxy, RecordedTransport +from azure.ai.projects.models import ( + PromptAgentDefinition, + CodeInterpreterTool, + CodeInterpreterContainerAuto, +) + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorCodeInterpreter(TestAiAgentsInstrumentorBase): + """ + Test suite for Code Interpreter agent telemetry instrumentation. + + This class tests OpenTelemetry trace generation when using Code Interpreter tool + with both content recording enabled and disabled, in both streaming and non-streaming modes. + """ + + # ======================================== + # Sync Code Interpreter Agent Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_code_interpreter_non_streaming_with_content_recording(self, **kwargs): + """Test synchronous Code Interpreter agent with content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + # Create vector store is not needed for code interpreter, but we need to upload file + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers code interpreter + response = openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + # With content recording, code should be present + assert ( + "code" in tool_content + ), "code should be present when content recording is enabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" in code_interpreter + ), "code should be present when content recording is enabled" + assert ( + "status" in code_interpreter + ), "status should be present in code_interpreter" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.files.delete(file.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_code_interpreter_non_streaming_without_content_recording(self, **kwargs): + """Test synchronous Code Interpreter agent with content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers code interpreter + response = openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + # Without content recording, code should NOT be present + assert ( + "code" not in tool_content + ), "code should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + # Without content recording, code should NOT be present + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" not in code_interpreter + ), "code should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.files.delete(file.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Sync Code Interpreter Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_code_interpreter_streaming_with_content_recording(self, **kwargs): + """Test synchronous Code Interpreter agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers code interpreter with streaming + stream = openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + assert ( + "code" in tool_content + ), "code should be present when content recording is enabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" in code_interpreter + ), "code should be present when content recording is enabled" + assert ( + "status" in code_interpreter + ), "status should be present in code_interpreter" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.files.delete(file.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_code_interpreter_streaming_without_content_recording(self, **kwargs): + """Test synchronous Code Interpreter agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers code interpreter with streaming + stream = openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + assert ( + "code" not in tool_content + ), "code should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" not in code_interpreter + ), "code should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.files.delete(file.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py new file mode 100644 index 000000000000..7b73aeeabec0 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py @@ -0,0 +1,798 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Tests for ResponsesInstrumentor with Code Interpreter tool (async). +""" +import os +import pytest +from io import BytesIO +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import RecordedTransport +from azure.ai.projects.models import ( + PromptAgentDefinition, + CodeInterpreterTool, + CodeInterpreterContainerAuto, +) + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorCodeInterpreterAsync(TestAiAgentsInstrumentorBase): + """ + Test suite for Code Interpreter agent telemetry instrumentation (async). + + This class tests OpenTelemetry trace generation when using Code Interpreter tool + with both content recording enabled and disabled, in both streaming and non-streaming modes. + """ + + # ======================================== + # Async Code Interpreter Agent Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_code_interpreter_non_streaming_with_content_recording(self, **kwargs): + """Test asynchronous Code Interpreter agent with content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = await openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers code interpreter + response = await openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + # With content recording, code should be present + assert ( + "code" in tool_content + ), "code should be present when content recording is enabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" in code_interpreter + ), "code should be present when content recording is enabled" + assert ( + "status" in code_interpreter + ), "status should be present in code_interpreter" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.files.delete(file.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_code_interpreter_non_streaming_without_content_recording(self, **kwargs): + """Test asynchronous Code Interpreter agent with content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = await openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers code interpreter + response = await openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + # Without content recording, code should NOT be present + assert ( + "code" not in tool_content + ), "code should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + # Without content recording, code should NOT be present + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" not in code_interpreter + ), "code should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.files.delete(file.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Async Code Interpreter Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_code_interpreter_streaming_with_content_recording(self, **kwargs): + """Test asynchronous Code Interpreter agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = await openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers code interpreter with streaming + stream = await openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + async for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + assert ( + "code" in tool_content + ), "code should be present when content recording is enabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" in code_interpreter + ), "code should be present when content recording is enabled" + assert ( + "status" in code_interpreter + ), "status should be present in code_interpreter" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.files.delete(file.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_code_interpreter_streaming_without_content_recording(self, **kwargs): + """Test asynchronous Code Interpreter agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create CSV data document + csv_data = """sector,name,operating_profit +TRANSPORTATION,Contoso shipping,850000 +TRANSPORTATION,Contoso rail,920000 +TRANSPORTATION,Contoso air,1100000 +""" + + csv_file = BytesIO(csv_data.encode("utf-8")) + csv_file.name = "transportation_data.csv" + + # Upload file for code interpreter + file = await openai_client.files.create(purpose="assistants", file=csv_file) + assert file.id is not None + + # Create agent with Code Interpreter tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can execute Python code to analyze data.", + tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers code interpreter with streaming + stream = await openai_client.responses.create( + conversation=conversation.id, + input="Calculate the average operating profit from the transportation data", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + async for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_code_interpreter_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_call = True + assert "id" in tool_content, "code_interpreter_call should have id" + assert ( + "code" not in tool_content + ), "code should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_code_interpreter_call, "Should have found code_interpreter_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_code_interpreter_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "code_interpreter_call": + found_code_interpreter_in_items = True + assert ( + "id" in tool_content + ), "code_interpreter_call should have id in conversation items" + code_interpreter = tool_content.get("code_interpreter") + if code_interpreter: + assert ( + "code" not in code_interpreter + ), "code should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_code_interpreter_in_items, "Should have found code_interpreter_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.files.delete(file.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py new file mode 100644 index 000000000000..5b01b733586c --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py @@ -0,0 +1,853 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Tests for ResponsesInstrumentor with File Search tool. +""" +import os +import pytest +from io import BytesIO +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils import recorded_by_proxy, RecordedTransport +from azure.ai.projects.models import PromptAgentDefinition, FileSearchTool + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorFileSearch(TestAiAgentsInstrumentorBase): + """Tests for ResponsesInstrumentor with File Search tool.""" + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_file_search_non_streaming_with_content_recording(self, **kwargs): + """Test synchronous File Search agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers file search + response = openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response.output_text is not None + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + # Validate input text content IS present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + assert "Contoso" in part["content"], "Should contain the user query" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + # With content recording, queries should be present + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present in file_search when content recording is enabled" + queries = file_search["queries"] + assert ( + isinstance(queries, list) and len(queries) > 0 + ), "queries should be a non-empty list" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + assert ( + isinstance(part["content"], str) and len(part["content"]) > 0 + ), "text content should be non-empty" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.vector_stores.delete(vector_store.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_file_search_non_streaming_without_content_recording(self, **kwargs): + """Test synchronous File Search agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers file search + response = openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response.output_text is not None + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + # Validate input text content is NOT present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + # Without content recording, queries should NOT be present + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.vector_stores.delete(vector_store.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Sync File Search Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_file_search_streaming_with_content_recording(self, **kwargs): + """Test synchronous File Search agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers file search with streaming + stream = openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present when content recording is enabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.vector_stores.delete(vector_store.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_file_search_streaming_without_content_recording(self, **kwargs): + """Test synchronous File Search agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # Ask question that triggers file search with streaming + stream = openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + openai_client.vector_stores.delete(vector_store.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py new file mode 100644 index 000000000000..ca5a4abd872b --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py @@ -0,0 +1,854 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Async tests for ResponsesInstrumentor with File Search tool. +""" +import os +import pytest +from io import BytesIO +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import RecordedTransport +from azure.ai.projects.models import PromptAgentDefinition, FileSearchTool + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorFileSearchAsync(TestAiAgentsInstrumentorBase): + """Async tests for ResponsesInstrumentor with File Search tool.""" + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_file_search_non_streaming_with_content_recording(self, **kwargs): + """Test asynchronous File Search agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = await openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = await openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers file search + response = await openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response.output_text is not None + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + # Validate input text content IS present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + assert "Contoso" in part["content"], "Should contain the user query" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + # With content recording, queries should be present + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present in file_search when content recording is enabled" + queries = file_search["queries"] + assert ( + isinstance(queries, list) and len(queries) > 0 + ), "queries should be a non-empty list" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + assert ( + isinstance(part["content"], str) and len(part["content"]) > 0 + ), "text content should be non-empty" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.vector_stores.delete(vector_store.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_file_search_non_streaming_without_content_recording(self, **kwargs): + """Test asynchronous File Search agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = await openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = await openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers file search + response = await openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response.output_text is not None + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + # Validate input text content is NOT present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + # Without content recording, queries should NOT be present + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.vector_stores.delete(vector_store.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Async File Search Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_file_search_streaming_with_content_recording(self, **kwargs): + """Test asynchronous File Search agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = await openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = await openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers file search with streaming + stream = await openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + async for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert "content" in part and isinstance( + part["content"], str + ), "Text content should be present when content recording is enabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present when content recording is enabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert "content" in part, "text content should be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" in file_search + ), "queries should be present when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.vector_stores.delete(vector_store.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_file_search_streaming_without_content_recording(self, **kwargs): + """Test asynchronous File Search agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create product information document + product_info = """Contoso Galaxy Innovations SmartView Glasses + +Product Category: Smart Eyewear + +Key Features: +- Augmented Reality interface +- Voice-controlled AI agent +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +Warranty: Two-year limited warranty on electronic components +Return Policy: 30-day return policy with no questions asked +""" + + # Create vector store and upload document + vector_store = await openai_client.vector_stores.create(name="ProductInfoStore") + + product_file = BytesIO(product_info.encode("utf-8")) + product_file.name = "product_info.txt" + + file = await openai_client.vector_stores.files.upload_and_poll( + vector_store_id=vector_store.id, + file=product_file, + ) + + assert file.status == "completed", f"File upload failed with status: {file.status}" + + # Create agent with File Search tool + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful assistant that can search through uploaded documents to answer questions.", + tools=[FileSearchTool(vector_store_ids=[vector_store.id])], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # Ask question that triggers file search with streaming + stream = await openai_client.responses.create( + conversation=conversation.id, + input="Tell me about Contoso products", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume the stream + async for event in stream: + pass + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 1, "Should have one response span" + + # Validate response span + span = spans[0] + assert span.attributes is not None + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None + + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + import json + + found_file_search_call = False + found_text_response = False + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_call = True + assert "id" in tool_content, "file_search_call should have id" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + elif part.get("type") == "text": + found_text_response = True + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + assert found_file_search_call, "Should have found file_search_call in output" + assert found_text_response, "Should have found text response type in output" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + found_file_search_in_items = False + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items" + elif part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "file_search_call": + found_file_search_in_items = True + assert ( + "id" in tool_content + ), "file_search_call should have id in conversation items" + file_search = tool_content.get("file_search") + if file_search: + assert ( + "queries" not in file_search + ), "queries should NOT be present when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + assert found_file_search_in_items, "Should have found file_search_call in conversation items" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + await openai_client.vector_stores.delete(vector_store.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py new file mode 100644 index 000000000000..9c47dfab727f --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py @@ -0,0 +1,1075 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Tests for ResponsesInstrumentor with MCP agents. +""" +import os +import pytest +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils import recorded_by_proxy, RecordedTransport +from azure.ai.projects.models import PromptAgentDefinition, MCPTool +from openai.types.responses.response_input_param import McpApprovalResponse + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorMCP(TestAiAgentsInstrumentorBase): + """Tests for ResponsesInstrumentor with MCP agents.""" + + # ======================================== + # Sync MCP Agent Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): + """Test synchronous MCP agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # First request - triggers MCP tool + response = openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests + input_list = [] + for item in response.output: + if item.type == "mcp_approval_request": + if item.server_label == "api-specs" and item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=item.id, + ) + ) + + # Send approval response + response2 = openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response2.output_text is not None + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span (MCP tool trigger) + span1 = spans[0] + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation for first span - verify content IS present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields ARE present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_list_tools when content recording is enabled" + elif tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" + + # Validate second response span (approval response) + span2 = spans[1] + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response2.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate MCP approval response and call in second span + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type in ("mcp_list_tools", "mcp_call", "mcp_approval_request"): + assert "id" in mcp_content + if mcp_type == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items" + assert ( + "server_label" in mcp_content + ), "server_label should be present for mcp_call in conversation items" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): + """Test synchronous MCP agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # First request - triggers MCP tool + response = openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests + input_list = [] + for item in response.output: + if item.type == "mcp_approval_request": + if item.server_label == "api-specs" and item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=item.id, + ) + ) + + # Send approval response + response2 = openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response2.output_text is not None + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span (MCP tool trigger) + span1 = spans[0] + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation for first span - verify content is NOT present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields are NOT present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content - should have type and id but not detailed fields + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + # server_label might be present but other details should not + pass + elif tool_type == "mcp_approval_request": + # Should not have name, arguments when content recording is disabled + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + + # Validate second response span (approval response) + span2 = spans[1] + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response2.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate MCP approval response and call in second span - content should be minimal + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content - should be minimal + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + # approval_request_id might not be present when content recording is disabled + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content - should be minimal + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_call when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_call when content recording is disabled" + elif part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items - should be minimal + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + # Should have id but might not have other details + assert "id" in mcp_content + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type == "mcp_call": + assert "id" in mcp_content + # Should not have name, server_label, arguments when content recording is disabled + assert ( + "name" not in mcp_content + ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Sync MCP Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_streaming_with_content_recording(self, **kwargs): + """Test synchronous MCP agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # First streaming request - triggers MCP tool + stream = openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests from stream + input_list = [] + for event in stream: + if hasattr(event, "type") and event.type == "response.output_item.done": + if hasattr(event, "item") and hasattr(event.item, "type"): + if event.item.type == "mcp_approval_request": + if hasattr(event.item, "server_label") and event.item.server_label == "api-specs": + if hasattr(event.item, "id") and event.item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=event.item.id, + ) + ) + + # Send approval response as streaming + stream2 = openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume second stream + for event in stream2: + pass + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span + span1 = spans[0] + assert span1.attributes is not None + response_id_1 = span1.attributes.get("gen_ai.response.id") + assert response_id_1 is not None + + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_1), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content: + tool_type = tool_content.get("type") + if tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" + + # Validate second response span + span2 = spans[1] + assert span2.attributes is not None + response_id_2 = span2.attributes.get("gen_ai.response.id") + assert response_id_2 is not None + + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_2), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate second span events + for event in span2.events: + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1 + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_streaming_without_content_recording(self, **kwargs): + """Test synchronous MCP agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = openai_client.conversations.create() + + # First streaming request - triggers MCP tool + stream = openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests from stream + input_list = [] + for event in stream: + if hasattr(event, "type") and event.type == "response.output_item.done": + if hasattr(event, "item") and hasattr(event.item, "type"): + if event.item.type == "mcp_approval_request": + if hasattr(event.item, "server_label") and event.item.server_label == "api-specs": + if hasattr(event.item, "id") and event.item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=event.item.id, + ) + ) + + # Send approval response as streaming + stream2 = openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume second stream + for event in stream2: + pass + + # Explicitly call and iterate through conversation items + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span + span1 = spans[0] + assert span1.attributes is not None + response_id_1 = span1.attributes.get("gen_ai.response.id") + assert response_id_1 is not None + + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_1), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content: + tool_type = tool_content.get("type") + if tool_type == "mcp_approval_request": + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + + # Validate second response span + span2 = spans[1] + assert span2.attributes is not None + response_id_2 = span2.attributes.get("gen_ai.response.id") + assert response_id_2 is not None + + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_2), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate second span events - content should be minimal + for event in span2.events: + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_call when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_call when content recording is disabled" + elif part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1 + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_call": + assert ( + "name" not in mcp_content + ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py new file mode 100644 index 000000000000..a5161456ed70 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py @@ -0,0 +1,1076 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Async tests for ResponsesInstrumentor with MCP agents. +""" +import os +import pytest +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import RecordedTransport +from azure.ai.projects.models import PromptAgentDefinition, MCPTool +from openai.types.responses.response_input_param import McpApprovalResponse + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +class TestResponsesInstrumentorMCPAsync(TestAiAgentsInstrumentorBase): + """Async tests for ResponsesInstrumentor with MCP agents.""" + + # ======================================== + # Async MCP Agent Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): + """Test asynchronous MCP agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # First request - triggers MCP tool + response = await openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests + input_list = [] + for item in response.output: + if item.type == "mcp_approval_request": + if item.server_label == "api-specs" and item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=item.id, + ) + ) + + # Send approval response + response2 = await openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response2.output_text is not None + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span (MCP tool trigger) + span1 = spans[0] + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation for first span - verify content IS present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields ARE present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_list_tools when content recording is enabled" + elif tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" + + # Validate second response span (approval response) + span2 = spans[1] + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response2.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate MCP approval response and call in second span + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type in ("mcp_list_tools", "mcp_call", "mcp_approval_request"): + assert "id" in mcp_content + if mcp_type == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items" + assert ( + "server_label" in mcp_content + ), "server_label should be present for mcp_call in conversation items" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs): + """Test asynchronous MCP agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # First request - triggers MCP tool + response = await openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests + input_list = [] + for item in response.output: + if item.type == "mcp_approval_request": + if item.server_label == "api-specs" and item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=item.id, + ) + ) + + # Send approval response + response2 = await openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=False, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + assert response2.output_text is not None + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span (MCP tool trigger) + span1 = spans[0] + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation for first span - verify content is NOT present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields are NOT present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content - should have type and id but not detailed fields + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + # server_label might be present but other details should not + pass + elif tool_type == "mcp_approval_request": + # Should not have name, arguments when content recording is disabled + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + + # Validate second response span (approval response) + span2 = spans[1] + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response2.id), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate MCP approval response and call in second span - content should be minimal + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content - should be minimal + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + # approval_request_id might not be present when content recording is disabled + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content - should be minimal + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_call when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_call when content recording is disabled" + elif part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items - should be minimal + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + # Should have id but might not have other details + assert "id" in mcp_content + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type == "mcp_call": + assert "id" in mcp_content + # Should not have name, server_label, arguments when content recording is disabled + assert ( + "name" not in mcp_content + ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + # ======================================== + # Async MCP Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_streaming_with_content_recording(self, **kwargs): + """Test asynchronous MCP agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # First streaming request - triggers MCP tool + stream = await openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests from stream + input_list = [] + async for event in stream: + if hasattr(event, "type") and event.type == "response.output_item.done": + if hasattr(event, "item") and hasattr(event.item, "type"): + if event.item.type == "mcp_approval_request": + if hasattr(event.item, "server_label") and event.item.server_label == "api-specs": + if hasattr(event.item, "id") and event.item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=event.item.id, + ) + ) + + # Send approval response as streaming + stream2 = await openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume second stream + async for event in stream2: + pass + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span + span1 = spans[0] + assert span1.attributes is not None + response_id_1 = span1.attributes.get("gen_ai.response.id") + assert response_id_1 is not None + + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_1), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation - verify content IS present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content: + tool_type = tool_content.get("type") + if tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" + + # Validate second response span + span2 = spans[1] + assert span2.attributes is not None + response_id_2 = span2.attributes.get("gen_ai.response.id") + assert response_id_2 is not None + + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_2), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate second span events + for event in span2.events: + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present when content recording is enabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1 + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_streaming_without_content_recording(self, **kwargs): + """Test asynchronous MCP agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create MCP tool + mcp_tool = MCPTool( + server_label="api-specs", + server_url="https://gitmcp.io/Azure/azure-rest-api-specs", + require_approval="always", + ) + + agent = await project_client.agents.create_version( + agent_name="MyAgent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="You are a helpful agent that can use MCP tools to assist users.", + tools=[mcp_tool], + ), + ) + + try: + conversation = await openai_client.conversations.create() + + # First streaming request - triggers MCP tool + stream = await openai_client.responses.create( + conversation=conversation.id, + input="Please summarize the Azure REST API specifications Readme", + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Collect approval requests from stream + input_list = [] + async for event in stream: + if hasattr(event, "type") and event.type == "response.output_item.done": + if hasattr(event, "item") and hasattr(event.item, "type"): + if event.item.type == "mcp_approval_request": + if hasattr(event.item, "server_label") and event.item.server_label == "api-specs": + if hasattr(event.item, "id") and event.item.id: + input_list.append( + McpApprovalResponse( + type="mcp_approval_response", + approve=True, + approval_request_id=event.item.id, + ) + ) + + # Send approval response as streaming + stream2 = await openai_client.responses.create( + conversation=conversation.id, + input=input_list, + stream=True, + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, + ) + + # Consume second stream + async for event in stream2: + pass + + # Explicitly call and iterate through conversation items + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + assert len(spans) == 2, "Should have two response spans (initial + approval)" + + # Validate first response span + span1 = spans[0] + assert span1.attributes is not None + response_id_1 = span1.attributes.get("gen_ai.response.id") + assert response_id_1 is not None + + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_1), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + + # Comprehensive event validation - verify content is NOT present + from collections.abc import Mapping + + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content: + tool_type = tool_content.get("type") + if tool_type == "mcp_approval_request": + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + + # Validate second response span + span2 = spans[1] + assert span2.attributes is not None + response_id_2 = span2.attributes.get("gen_ai.response.id") + assert response_id_2 is not None + + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", agent.name), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", response_id_2), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + + # Validate second span events - content should be minimal + for event in span2.events: + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_call when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_call when content recording is disabled" + elif part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present when content recording is disabled" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1 + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_call": + assert ( + "name" not in mcp_content + ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py new file mode 100644 index 000000000000..e4b5e0c40a94 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py @@ -0,0 +1,847 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Tests for ResponsesInstrumentor with workflow agents. +""" +import os +import pytest +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils import recorded_by_proxy, RecordedTransport +from azure.ai.projects.models import ( + AgentReference, + PromptAgentDefinition, + WorkflowAgentDefinition, +) + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +def checkWorkflowEventContents(content, content_recording_enabled): + """Validate workflow event content structure and required fields.""" + import json + + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + for entry in data: + assert entry.get("role") == "workflow" + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + found_workflow_action = False + for part in parts: + if part.get("type") == "workflow_action": + found_workflow_action = True + workflow_content = part.get("content") + assert isinstance(workflow_content, dict) + # status is always present + assert ( + "status" in workflow_content + and isinstance(workflow_content["status"], str) + and workflow_content["status"] + ) + if content_recording_enabled: + # action_id and previous_action_id should be present and non-empty + assert ( + "action_id" in workflow_content + and isinstance(workflow_content["action_id"], str) + and workflow_content["action_id"] + ) + assert ( + "previous_action_id" in workflow_content + and isinstance(workflow_content["previous_action_id"], str) + and workflow_content["previous_action_id"] + ) + else: + # action_id and previous_action_id should NOT be present when content recording is disabled + assert ( + "action_id" not in workflow_content + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in workflow_content + ), "previous_action_id should not be present when content recording is disabled" + assert found_workflow_action, "No workflow_action part found in workflow event" + + +def checkInputMessageEventContents(content, content_recording_enabled): + """Validate input message event content structure and required fields.""" + import json + + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + for entry in data: + assert entry.get("role") == "user" + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + found_text = False + for part in parts: + if part.get("type") == "text": + found_text = True + if content_recording_enabled: + assert "content" in part and isinstance(part["content"], str) and part["content"].strip() != "" + else: + # content field should NOT be present in text parts when content recording is disabled + assert ( + "content" not in part + ), "Text content should not be present when content recording is disabled" + assert found_text, "No text part found in input message event" + + +class TestResponsesInstrumentorWorkflow(TestAiAgentsInstrumentorBase): + """Tests for ResponsesInstrumentor with workflow agents.""" + + def _create_student_teacher_workflow(self, project_client, student_agent, teacher_agent): + """Create a multi-agent workflow with student and teacher agents.""" + workflow_yaml = f""" +kind: workflow +trigger: + kind: OnConversationStart + id: my_workflow + actions: + - kind: SetVariable + id: set_variable_input_task + variable: Local.LatestMessage + value: "=UserMessage(System.LastMessageText)" + + - kind: CreateConversation + id: create_student_conversation + conversationId: Local.StudentConversationId + + - kind: CreateConversation + id: create_teacher_conversation + conversationId: Local.TeacherConversationId + + - kind: InvokeAzureAgent + id: student_agent + description: The student node + conversationId: "=Local.StudentConversationId" + agent: + name: {student_agent.name} + input: + messages: "=Local.LatestMessage" + output: + messages: Local.LatestMessage + + - kind: InvokeAzureAgent + id: teacher_agent + description: The teacher node + conversationId: "=Local.TeacherConversationId" + agent: + name: {teacher_agent.name} + input: + messages: "=Local.LatestMessage" + output: + messages: Local.LatestMessage + + - kind: SetVariable + id: set_variable_turncount + variable: Local.TurnCount + value: "=Local.TurnCount + 1" + + - kind: ConditionGroup + id: completion_check + conditions: + - condition: '=!IsBlank(Find("[COMPLETE]", Upper(Last(Local.LatestMessage).Text)))' + id: check_done + actions: + - kind: EndConversation + id: end_workflow + + - condition: "=Local.TurnCount >= 4" + id: check_turn_count_exceeded + actions: + - kind: SendActivity + id: send_activity_tired + activity: "Let's try again later...I am tired." + + elseActions: + - kind: GotoAction + id: goto_student_agent + actionId: student_agent +""" + + workflow = project_client.agents.create_version( + agent_name="student-teacher-workflow", + definition=WorkflowAgentDefinition(workflow=workflow_yaml), + ) + return workflow + + # ======================================== + # Sync Workflow Agent Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_workflow_non_streaming_with_content_recording(self, **kwargs): + """Test synchronous workflow agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow + workflow = self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = openai_client.conversations.create() + + # Non-streaming request + response = openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=False, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Verify response has output + assert response.output is not None + assert len(response.output) > 0 + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans for list_conversation_items + self.exporter.force_flush() + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response.id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation and conversation item listing + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, True) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + import json + + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, True) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), True) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), True) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + project_client.agents.delete_version(agent_name=student_agent.name, agent_version=student_agent.version) + project_client.agents.delete_version(agent_name=teacher_agent.name, agent_version=teacher_agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_workflow_non_streaming_without_content_recording(self, **kwargs): + """Test synchronous workflow agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow + workflow = self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = openai_client.conversations.create() + + # Non-streaming request + response = openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=False, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Verify response has output + assert response.output is not None + assert len(response.output) > 0 + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response.id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events (should exist even without content recording) + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span - verify content recording is OFF + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, False) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + import json + + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, False) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), False) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), False) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + project_client.agents.delete_version(agent_name=student_agent.name, agent_version=student_agent.version) + project_client.agents.delete_version(agent_name=teacher_agent.name, agent_version=teacher_agent.version) + + # ======================================== + # Sync Workflow Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_workflow_streaming_with_content_recording(self, **kwargs): + """Test synchronous workflow agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow + workflow = self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = openai_client.conversations.create() + + # Streaming request + stream = openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=True, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Consume stream + for event in stream: + pass # Just consume events + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response_id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, True) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + import json + + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, True) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), True) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), True) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + project_client.agents.delete_version(agent_name=student_agent.name, agent_version=student_agent.version) + project_client.agents.delete_version(agent_name=teacher_agent.name, agent_version=teacher_agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_workflow_streaming_without_content_recording(self, **kwargs): + """Test synchronous workflow agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow + workflow = self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = openai_client.conversations.create() + + # Streaming request + stream = openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=True, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Consume stream + for event in stream: + pass # Just consume events + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = openai_client.conversations.items.list(conversation_id=conversation.id) + for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response_id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events (should exist even without content recording) + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span - verify content recording is OFF + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, False) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + import json + + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, False) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), False) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), False) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + project_client.agents.delete_version(agent_name=student_agent.name, agent_version=student_agent.version) + project_client.agents.delete_version(agent_name=teacher_agent.name, agent_version=teacher_agent.version) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py new file mode 100644 index 000000000000..22d5580bdd09 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py @@ -0,0 +1,836 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +""" +Async tests for ResponsesInstrumentor with workflow agents. +""" +import os +import pytest +from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.core.settings import settings +from gen_ai_trace_verifier import GenAiTraceVerifier +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import RecordedTransport +from azure.ai.projects.models import ( + AgentReference, + PromptAgentDefinition, + WorkflowAgentDefinition, +) + +from test_base import servicePreparer +from test_ai_instrumentor_base import ( + TestAiAgentsInstrumentorBase, + CONTENT_TRACING_ENV_VARIABLE, +) + +import json + +settings.tracing_implementation = "OpenTelemetry" +_utils._span_impl_type = settings.tracing_implementation() + + +def checkWorkflowEventContents(content, content_recording_enabled): + """Validate workflow event content structure and required fields.""" + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + for entry in data: + assert entry.get("role") == "workflow" + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + found_workflow_action = False + for part in parts: + if part.get("type") == "workflow_action": + found_workflow_action = True + workflow_content = part.get("content") + assert isinstance(workflow_content, dict) + # status is always present + assert ( + "status" in workflow_content + and isinstance(workflow_content["status"], str) + and workflow_content["status"] + ) + if content_recording_enabled: + # action_id and previous_action_id should be present and non-empty + assert ( + "action_id" in workflow_content + and isinstance(workflow_content["action_id"], str) + and workflow_content["action_id"] + ) + assert ( + "previous_action_id" in workflow_content + and isinstance(workflow_content["previous_action_id"], str) + and workflow_content["previous_action_id"] + ) + else: + # action_id and previous_action_id should NOT be present when content recording is disabled + assert ( + "action_id" not in workflow_content + ), "action_id should not be present when content recording is disabled" + assert ( + "previous_action_id" not in workflow_content + ), "previous_action_id should not be present when content recording is disabled" + assert found_workflow_action, "No workflow_action part found in workflow event" + + +def checkInputMessageEventContents(content, content_recording_enabled): + """Validate input message event content structure and required fields.""" + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + for entry in data: + assert entry.get("role") == "user" + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + found_text = False + for part in parts: + if part.get("type") == "text": + found_text = True + if content_recording_enabled: + assert "content" in part and isinstance(part["content"], str) and part["content"].strip() != "" + else: + # content field should NOT be present in text parts when content recording is disabled + assert ( + "content" not in part + ), "Text content should not be present when content recording is disabled" + assert found_text, "No text part found in input message event" + + +class TestResponsesInstrumentorWorkflowAsync(TestAiAgentsInstrumentorBase): + """Async tests for ResponsesInstrumentor with workflow agents.""" + + async def _create_student_teacher_workflow(self, project_client, student_agent, teacher_agent): + """Create a multi-agent workflow with student and teacher agents.""" + workflow_yaml = f""" +kind: workflow +trigger: + kind: OnConversationStart + id: my_workflow + actions: + - kind: SetVariable + id: set_variable_input_task + variable: Local.LatestMessage + value: "=UserMessage(System.LastMessageText)" + + - kind: CreateConversation + id: create_student_conversation + conversationId: Local.StudentConversationId + + - kind: CreateConversation + id: create_teacher_conversation + conversationId: Local.TeacherConversationId + + - kind: InvokeAzureAgent + id: student_agent + description: The student node + conversationId: "=Local.StudentConversationId" + agent: + name: {student_agent.name} + input: + messages: "=Local.LatestMessage" + output: + messages: Local.LatestMessage + + - kind: InvokeAzureAgent + id: teacher_agent + description: The teacher node + conversationId: "=Local.TeacherConversationId" + agent: + name: {teacher_agent.name} + input: + messages: "=Local.LatestMessage" + output: + messages: Local.LatestMessage + + - kind: SetVariable + id: set_variable_turncount + variable: Local.TurnCount + value: "=Local.TurnCount + 1" + + - kind: ConditionGroup + id: completion_check + conditions: + - condition: '=!IsBlank(Find("[COMPLETE]", Upper(Last(Local.LatestMessage).Text)))' + id: check_done + actions: + - kind: EndConversation + id: end_workflow + + - condition: "=Local.TurnCount >= 4" + id: check_turn_count_exceeded + actions: + - kind: SendActivity + id: send_activity_tired + activity: "Let's try again later...I am tired." + + elseActions: + - kind: GotoAction + id: goto_student_agent + actionId: student_agent +""" + + workflow = await project_client.agents.create_version( + agent_name="student-teacher-workflow", + definition=WorkflowAgentDefinition(workflow=workflow_yaml), + ) + return workflow + + # ======================================== + # Async Workflow Agent Tests - Non-Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_workflow_non_streaming_with_content_recording(self, **kwargs): + """Test asynchronous workflow agent with non-streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = await project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = await project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow using helper method + workflow = await self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = await openai_client.conversations.create() + + # Non-streaming request + response = await openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=False, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Verify response has output + assert response.output is not None + assert len(response.output) > 0 + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response.id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, True) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, True) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), True) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), True) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + await project_client.agents.delete_version( + agent_name=student_agent.name, agent_version=student_agent.version + ) + await project_client.agents.delete_version( + agent_name=teacher_agent.name, agent_version=teacher_agent.version + ) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_workflow_non_streaming_without_content_recording(self, **kwargs): + """Test asynchronous workflow agent with non-streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = await project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = await project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow using helper method + workflow = await self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = await openai_client.conversations.create() + + # Non-streaming request + response = await openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=False, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Verify response has output + assert response.output is not None + assert len(response.output) > 0 + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response.id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events (should exist even without content recording) + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span - verify content recording is OFF + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, False) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, False) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), False) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), False) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + await project_client.agents.delete_version( + agent_name=student_agent.name, agent_version=student_agent.version + ) + await project_client.agents.delete_version( + agent_name=teacher_agent.name, agent_version=teacher_agent.version + ) + + # ======================================== + # Async Workflow Agent Tests - Streaming + # ======================================== + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_workflow_streaming_with_content_recording(self, **kwargs): + """Test asynchronous workflow agent with streaming and content recording enabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "True", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = await project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = await project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow using helper method + workflow = await self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = await openai_client.conversations.create() + + # Streaming request + stream = await openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=True, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Consume stream + async for event in stream: + pass # Just consume events + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response_id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, True) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, True) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), True) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), True) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + await project_client.agents.delete_version( + agent_name=student_agent.name, agent_version=student_agent.version + ) + await project_client.agents.delete_version( + agent_name=teacher_agent.name, agent_version=teacher_agent.version + ) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_workflow_streaming_without_content_recording(self, **kwargs): + """Test asynchronous workflow agent with streaming and content recording disabled.""" + self.cleanup() + os.environ.update( + { + CONTENT_TRACING_ENV_VARIABLE: "False", + "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True", + } + ) + self.setup_telemetry() + assert not AIProjectInstrumentor().is_content_recording_enabled() + assert AIProjectInstrumentor().is_instrumented() + + project_client = self.create_async_client(operation_group="tracing", **kwargs) + deployment_name = kwargs.get("azure_ai_model_deployment_name") + assert deployment_name is not None + + async with project_client: + openai_client = project_client.get_openai_client() + + # Create Teacher Agent + teacher_agent = await project_client.agents.create_version( + agent_name="teacher-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a teacher that creates pre-school math questions for students and checks answers. + If the answer is correct, you stop the conversation by saying [COMPLETE]. + If the answer is wrong, you ask student to fix it.""", + ), + ) + + # Create Student Agent + student_agent = await project_client.agents.create_version( + agent_name="student-agent", + definition=PromptAgentDefinition( + model=deployment_name, + instructions="""You are a student who answers questions from the teacher. + When the teacher gives you a question, you answer it.""", + ), + ) + + # Create workflow using helper method + workflow = await self._create_student_teacher_workflow(project_client, student_agent, teacher_agent) + + try: + # Create conversation + conversation = await openai_client.conversations.create() + + # Streaming request + stream = await openai_client.responses.create( + conversation=conversation.id, + extra_body={"agent": AgentReference(name=workflow.name).as_dict()}, + input="1 + 1 = ?", + stream=True, + metadata={"x-ms-debug-mode-enabled": "1"}, + ) + + # Consume stream + async for event in stream: + pass # Just consume events + + # Explicitly call and iterate through conversation items to generate the list_conversation_items span + items = await openai_client.conversations.items.list(conversation_id=conversation.id) + async for item in items: + pass # Just iterate to consume items + + # Check spans + self.exporter.force_flush() + spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + assert len(spans) == 1 + span = spans[0] + + # Get response ID from span + assert span.attributes is not None, "Span should have attributes" + response_id = span.attributes.get("gen_ai.response.id") + assert response_id is not None, "Response ID should be present in span" + + # Check span attributes + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", "responses"), + ("gen_ai.provider.name", "azure.openai"), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.agent.name", workflow.name), + ("gen_ai.response.id", response_id), + ] + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match + + # Check for workflow action events (should exist even without content recording) + workflow_events = [e for e in span.events if e.name == "gen_ai.workflow.action"] + assert len(workflow_events) > 0, "Should have workflow action events" + + # Strict event content checks for response generation span - verify content recording is OFF + from collections.abc import Mapping + + for event in span.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + checkInputMessageEventContents(content, False) + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + assert isinstance(first.get("parts"), list) and len(first["parts"]) > 0 + elif event.attributes: + # Check workflow events in response generation span + event_content = event.attributes.get("gen_ai.event.content") + if not isinstance(event_content, str) or not event_content.strip(): + continue + try: + data = json.loads(event_content) + except Exception: + continue + if isinstance(data, list) and any(entry.get("role") == "workflow" for entry in data): + checkWorkflowEventContents(event_content, False) + else: + assert False, f"Unexpected event name in responses span: {event.name}" + + # Check list_conversation_items span + list_spans = self.exporter.get_spans_by_name("list_conversation_items") + assert len(list_spans) == 1, "Should have one list_conversation_items span" + list_span = list_spans[0] + + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + data = json.loads(content) + assert isinstance(data, list) + for item in data: + if item.get("role") == "workflow": + checkWorkflowEventContents(json.dumps([item]), False) + elif item.get("role") == "user": + checkInputMessageEventContents(json.dumps([item]), False) + else: + pass + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + + # Cleanup + await openai_client.conversations.delete(conversation_id=conversation.id) + + finally: + await project_client.agents.delete_version(agent_name=workflow.name, agent_version=workflow.version) + await project_client.agents.delete_version( + agent_name=student_agent.name, agent_version=student_agent.version + ) + await project_client.agents.delete_version( + agent_name=teacher_agent.name, agent_version=teacher_agent.version + ) diff --git a/sdk/ai/azure-ai-projects/tests/test_base.py b/sdk/ai/azure-ai-projects/tests/test_base.py index 45945bc99c74..15cc8f131aae 100644 --- a/sdk/ai/azure-ai-projects/tests/test_base.py +++ b/sdk/ai/azure-ai-projects/tests/test_base.py @@ -53,6 +53,7 @@ ai_search_project_connection_id="/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/sanitized-resource-group/providers/Microsoft.CognitiveServices/accounts/sanitized-account/projects/sanitized-project/connections/sanitized-ai-search-connection", ai_search_index_name="sanitized-index-name", mcp_project_connection_id="/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/sanitized-resource-group/providers/Microsoft.CognitiveServices/accounts/sanitized-account/projects/sanitized-project/connections/sanitized-mcp-connection", + browser_automation_project_connection_id="/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/sanitized-resource-group/providers/Microsoft.CognitiveServices/accounts/sanitized-account/projects/sanitized-project/connections/sanitized-browser-automation-connection", sharepoint_project_connection_id="/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/sanitized-resource-group/providers/Microsoft.CognitiveServices/accounts/sanitized-account/projects/sanitized-project/connections/sanitized-sharepoint-connection", completed_oai_model_sft_fine_tuning_job_id="sanitized-ftjob-id", completed_oai_model_rft_fine_tuning_job_id="sanitized-ftjob-id", From 00200a9e2cee6a748d5cfa4284280e256ebe2c97 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 29 Jan 2026 12:15:57 -0800 Subject: [PATCH 06/84] bump proxy version (#44909) Co-authored-by: Scott Beddall (from Dev Box) --- eng/common/testproxy/target_version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/common/testproxy/target_version.txt b/eng/common/testproxy/target_version.txt index 151749f5d2ae..3b2404bfbb0d 100644 --- a/eng/common/testproxy/target_version.txt +++ b/eng/common/testproxy/target_version.txt @@ -1 +1 @@ -1.0.0-dev.20251209.1 +1.0.0-dev.20260128.1 From 1f9cb73ba33205b7a1e3266e4ebd9c402a7c1cd2 Mon Sep 17 00:00:00 2001 From: Ryan Zhang <112638134+ryazhang-microsoft@users.noreply.github.com> Date: Thu, 29 Jan 2026 15:23:05 -0500 Subject: [PATCH 07/84] Confidential Ledger SDK update SensitiveHeaderCleanupPolicy for CCF redirection change (#44915) * update clinet and test script * remove test script * add comments * add change log * update redirection policy * Update CHANGELOG for version 2.0.0b2 release Updated release date for version 2.0.0b2 and fixed authentication issue. * add unit test * Update version to 2.0.0b2 * Trigger CI rebuild --- .../azure-confidentialledger/CHANGELOG.md | 6 ++ .../azure/confidentialledger/_client.py | 8 +- .../azure/confidentialledger/_version.py | 2 +- .../azure/confidentialledger/aio/_client.py | 4 +- .../tests/test_client_configuration.py | 98 +++++++++++++++++++ 5 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 sdk/confidentialledger/azure-confidentialledger/tests/test_client_configuration.py diff --git a/sdk/confidentialledger/azure-confidentialledger/CHANGELOG.md b/sdk/confidentialledger/azure-confidentialledger/CHANGELOG.md index 129dd85532b6..22366f06a123 100644 --- a/sdk/confidentialledger/azure-confidentialledger/CHANGELOG.md +++ b/sdk/confidentialledger/azure-confidentialledger/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 2.0.0b2 (2026-01-29) + +### Bugs Fixed + +- Fixed authentication failure on HTTP redirects by preserving sensitive headers during service-managed redirects within the Confidential Ledger endpoint. + ## 2.0.0b1 (2025-10-20) ### Features Added diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py index 5547a18f3e68..92370f080501 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py @@ -52,7 +52,13 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._config.custom_hook_policy, self._config.logging_policy, policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + # Redirect cleanup is disabled to preserve authentication and ledger-specific headers + # on service-managed redirects. Confidential Ledger redirects are expected to stay within + # the same trusted ledger endpoint, so forwarding these sensitive headers is required + # for correct authentication behavior. + policies.SensitiveHeaderCleanupPolicy( + disable_redirect_cleanup=True, **kwargs + ) if self._config.redirect_policy else None, self._config.http_logging_policy, ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_version.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_version.py index 0e00a6283246..8eb37199ee54 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_version.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0b1" +VERSION = "2.0.0b2" diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py index a3e303ca7c68..7f49efc68499 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py @@ -52,7 +52,9 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._config.custom_hook_policy, self._config.logging_policy, policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + policies.SensitiveHeaderCleanupPolicy( + disable_redirect_cleanup=True, **kwargs + ) if self._config.redirect_policy else None, self._config.http_logging_policy, ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) diff --git a/sdk/confidentialledger/azure-confidentialledger/tests/test_client_configuration.py b/sdk/confidentialledger/azure-confidentialledger/tests/test_client_configuration.py new file mode 100644 index 000000000000..47459e6733dd --- /dev/null +++ b/sdk/confidentialledger/azure-confidentialledger/tests/test_client_configuration.py @@ -0,0 +1,98 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Unit tests for ConfidentialLedgerClient configuration.""" + +import pytest +from unittest.mock import patch, MagicMock +from azure.core.pipeline import policies + +# Import the generated client directly to test its policy configuration +from azure.confidentialledger._client import ConfidentialLedgerClient as GeneratedClient + + +class TestClientConfiguration: + """Tests for client configuration settings.""" + + def test_sensitive_header_cleanup_policy_disable_redirect_cleanup_enabled(self): + """Test that SensitiveHeaderCleanupPolicy has disable_redirect_cleanup=True. + + This ensures that authentication and ledger-specific headers are preserved + on service-managed redirects, which is required for correct authentication + behavior within the trusted Confidential Ledger endpoint. + """ + # Mock the PipelineClient to capture the policies passed to it + with patch("azure.confidentialledger._client.PipelineClient") as mock_pipeline_client: + mock_pipeline_client.return_value = MagicMock() + + # Create the generated client directly - this will trigger policy creation + # The generated client only requires ledger_endpoint + client = GeneratedClient( + ledger_endpoint="https://test-ledger.confidentialledger.azure.com" + ) + + # Get the policies argument passed to PipelineClient + call_args = mock_pipeline_client.call_args + policies_arg = call_args.kwargs.get("policies") or call_args[1].get("policies") + + # Find the SensitiveHeaderCleanupPolicy in the policies list + sensitive_header_policy = None + for policy in policies_arg: + if isinstance(policy, policies.SensitiveHeaderCleanupPolicy): + sensitive_header_policy = policy + break + + # Assert the policy exists and has disable_redirect_cleanup=True + assert sensitive_header_policy is not None, ( + "SensitiveHeaderCleanupPolicy should be present in the client's policies" + ) + assert sensitive_header_policy._disable_redirect_cleanup is True, ( + "SensitiveHeaderCleanupPolicy should have disable_redirect_cleanup=True " + "to preserve authentication headers on Confidential Ledger redirects" + ) + + client.close() + + def test_sensitive_header_cleanup_policy_is_in_correct_position(self): + """Test that SensitiveHeaderCleanupPolicy is positioned after authentication_policy. + + The policy should be placed after the authentication policy so that it can + properly handle the redirect cleanup for authentication headers. + """ + with patch("azure.confidentialledger._client.PipelineClient") as mock_pipeline_client: + mock_pipeline_client.return_value = MagicMock() + + client = GeneratedClient( + ledger_endpoint="https://test-ledger.confidentialledger.azure.com" + ) + + # Get the policies argument passed to PipelineClient + call_args = mock_pipeline_client.call_args + policies_arg = call_args.kwargs.get("policies") or call_args[1].get("policies") + + # Filter out None values + non_none_policies = [p for p in policies_arg if p is not None] + + # Find positions of key policies + sensitive_header_idx = None + distributed_tracing_idx = None + + for idx, policy in enumerate(non_none_policies): + if isinstance(policy, policies.SensitiveHeaderCleanupPolicy): + sensitive_header_idx = idx + elif isinstance(policy, policies.DistributedTracingPolicy): + distributed_tracing_idx = idx + + # SensitiveHeaderCleanupPolicy should come after DistributedTracingPolicy + assert sensitive_header_idx is not None, ( + "SensitiveHeaderCleanupPolicy should be present in the policies" + ) + assert distributed_tracing_idx is not None, ( + "DistributedTracingPolicy should be present in the policies" + ) + assert sensitive_header_idx > distributed_tracing_idx, ( + "SensitiveHeaderCleanupPolicy should be positioned after DistributedTracingPolicy" + ) + + client.close() From f67586a6577ab22c8147bd49add9a34a157a9bbd Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Thu, 29 Jan 2026 16:27:19 -0500 Subject: [PATCH 08/84] update (#44921) Co-authored-by: iscai-msft --- eng/emitter-package-lock.json | 52 +++++++++++++++++------------------ eng/emitter-package.json | 2 +- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index 0add3427cd75..1226079b31c8 100644 --- a/eng/emitter-package-lock.json +++ b/eng/emitter-package-lock.json @@ -6,7 +6,7 @@ "": { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.0" + "@azure-tools/typespec-python": "0.59.1" }, "devDependencies": { "@azure-tools/openai-typespec": "1.7.3", @@ -39,17 +39,17 @@ } }, "node_modules/@azure-tools/typespec-autorest": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-autorest/-/typespec-autorest-0.64.0.tgz", - "integrity": "sha512-zC2e3px+BqGJvE9DeW00S0PZmkydorB3Hm6Fb2vlJUdmHuTTSochPiZFJF7LHNsAL8sDu7azSHzypESFdN0FmA==", + "version": "0.64.1", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-autorest/-/typespec-autorest-0.64.1.tgz", + "integrity": "sha512-WzSRiX0XS7hCL+uiivLBYMbirEUenxNzPT4giF0J+r54CVNXq/u8PLnA/06F5EHkXPa92swF4BxB1vFWB2TKow==", "license": "MIT", "engines": { "node": ">=20.0.0" }, "peerDependencies": { "@azure-tools/typespec-azure-core": "^0.64.0", - "@azure-tools/typespec-azure-resource-manager": "^0.64.0", - "@azure-tools/typespec-client-generator-core": "^0.64.0", + "@azure-tools/typespec-azure-resource-manager": "^0.64.1", + "@azure-tools/typespec-client-generator-core": "^0.64.4", "@typespec/compiler": "^1.8.0", "@typespec/http": "^1.8.0", "@typespec/openapi": "^1.8.0", @@ -78,9 +78,9 @@ } }, "node_modules/@azure-tools/typespec-azure-resource-manager": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-resource-manager/-/typespec-azure-resource-manager-0.64.0.tgz", - "integrity": "sha512-1HwGo3Nt8ksafoPp1rFOopSzgh68SFsyVNCauzjO8ftf0fEqhRXo70OaGwP6wmTZJsLnW7u1DbrBNu6b0z2sOQ==", + "version": "0.64.1", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-resource-manager/-/typespec-azure-resource-manager-0.64.1.tgz", + "integrity": "sha512-qQV/+ZVF1h8PsTNKhmKYyb+vSCgnLA8SoGeEE1oOrevGrrp9VgtOMAZ2xIxj6DpU90QU/8t2+r5P/gcQUV1iqw==", "license": "MIT", "dependencies": { "change-case": "~5.4.4", @@ -114,9 +114,9 @@ } }, "node_modules/@azure-tools/typespec-client-generator-core": { - "version": "0.64.4", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.64.4.tgz", - "integrity": "sha512-ZAYdbTe47VVff3MarJTXXiu/xg4iIilipJbjbqROIYbNkXcnIyZSC1IYDkzKHU3qgYrEyHuBjoVZc7rkxAtOLA==", + "version": "0.64.5", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.64.5.tgz", + "integrity": "sha512-RaATxsnc9ztdMPoIZ2SuyH97dIGY0BWGKcJBf0hBY+8J3de9o+QH796NA9OsiW+8J9ycCEooDbh/rkAspvA4xA==", "license": "MIT", "dependencies": { "change-case": "~5.4.4", @@ -146,13 +146,13 @@ "dev": true }, "node_modules/@azure-tools/typespec-python": { - "version": "0.59.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.0.tgz", - "integrity": "sha512-j2vywIEuCE/XIAeAAvMkuQSFlrF6IH9mIi0HP8022jPxh3fmDhOArWwt15r7Kl1+T0aiqIyaNQBGpv0zk642Dw==", + "version": "0.59.1", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.1.tgz", + "integrity": "sha512-ZE+HV8iDNf3z4uJeVUpmbtdWwh9Uq349tpNiUAovPu+JIwGzwf8lKKWyGvW+5n0VR8WmI9ibj2yyMGvmiP2jeg==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "@typespec/http-client-python": "~0.26.0", + "@typespec/http-client-python": "~0.26.1", "fs-extra": "~11.2.0", "js-yaml": "~4.1.0", "semver": "~7.6.2", @@ -166,7 +166,7 @@ "@azure-tools/typespec-azure-core": ">=0.64.0 <1.0.0", "@azure-tools/typespec-azure-resource-manager": ">=0.64.0 <1.0.0", "@azure-tools/typespec-azure-rulesets": ">=0.64.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.64.4 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.64.5 <1.0.0", "@typespec/compiler": "^1.8.0", "@typespec/events": ">=0.78.0 <1.0.0", "@typespec/http": "^1.8.0", @@ -1079,9 +1079,9 @@ } }, "node_modules/@typespec/http-client-python": { - "version": "0.26.0", - "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.0.tgz", - "integrity": "sha512-KUY1ja0yrQLiyIEtzf/oDmfwEJNi1fYNLCXVt6Rw6pinAR4mwOtkNI/1LEyYbl7/3RxSEWlpmzWfU57ltYWYQA==", + "version": "0.26.1", + "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.1.tgz", + "integrity": "sha512-QyPyYAB1qf+wxvH5FlHj8fJ3NttA1HeHUVVPLeUyyItOXAWDVczTVbDfhgS73TkrFeOb8A56NKgTVy74lt/H3g==", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -1095,11 +1095,11 @@ "node": ">=20.0.0" }, "peerDependencies": { - "@azure-tools/typespec-autorest": ">=0.64.0 <1.0.0", + "@azure-tools/typespec-autorest": ">=0.64.1 <1.0.0", "@azure-tools/typespec-azure-core": ">=0.64.0 <1.0.0", - "@azure-tools/typespec-azure-resource-manager": ">=0.64.0 <1.0.0", + "@azure-tools/typespec-azure-resource-manager": ">=0.64.1 <1.0.0", "@azure-tools/typespec-azure-rulesets": ">=0.64.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.64.4 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.64.5 <1.0.0", "@typespec/compiler": "^1.8.0", "@typespec/events": ">=0.78.0 <1.0.0", "@typespec/http": "^1.8.0", @@ -1904,9 +1904,9 @@ } }, "node_modules/tar": { - "version": "7.5.6", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.6.tgz", - "integrity": "sha512-xqUeu2JAIJpXyvskvU3uvQW8PAmHrtXp2KDuMJwQqW8Sqq0CaZBAQ+dKS3RBXVhU4wC5NjAdKrmh84241gO9cA==", + "version": "7.5.7", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.7.tgz", + "integrity": "sha512-fov56fJiRuThVFXD6o6/Q354S7pnWMJIVlDBYijsTNx6jKSE4pvrDTs6lUnmGvNyfJwFQQwWy3owKz1ucIhveQ==", "license": "BlueOak-1.0.0", "dependencies": { "@isaacs/fs-minipass": "^4.0.0", diff --git a/eng/emitter-package.json b/eng/emitter-package.json index a0884d625480..b712556e4310 100644 --- a/eng/emitter-package.json +++ b/eng/emitter-package.json @@ -1,7 +1,7 @@ { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.0" + "@azure-tools/typespec-python": "0.59.1" }, "devDependencies": { "@typespec/compiler": "^1.8.0", From 160ad135e8f201ff22d80d05dbacf9b14ab7e9b8 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 29 Jan 2026 16:43:44 -0800 Subject: [PATCH 09/84] Update version (#44927) Co-authored-by: anannya03 --- .github/workflows/event-processor.yml | 2 +- .github/workflows/scheduled-event-processor.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/event-processor.yml b/.github/workflows/event-processor.yml index ccdd463fbdce..be4f50854404 100644 --- a/.github/workflows/event-processor.yml +++ b/.github/workflows/event-processor.yml @@ -68,7 +68,7 @@ jobs: run: > dotnet tool install Azure.Sdk.Tools.GitHubEventProcessor - --version 1.0.0-dev.20250314.4 + --version 1.0.0-dev.20260129.1 --add-source https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json --global shell: bash diff --git a/.github/workflows/scheduled-event-processor.yml b/.github/workflows/scheduled-event-processor.yml index 4e89d44cf0e6..05703d88fd94 100644 --- a/.github/workflows/scheduled-event-processor.yml +++ b/.github/workflows/scheduled-event-processor.yml @@ -39,7 +39,7 @@ jobs: run: > dotnet tool install Azure.Sdk.Tools.GitHubEventProcessor - --version 1.0.0-dev.20250425.1 + --version 1.0.0-dev.20260129.1 --add-source https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json --global shell: bash From 48235853a3b7b4df7a64b23ec184d53e7ac10d95 Mon Sep 17 00:00:00 2001 From: Darren Cohen <39422044+dargilco@users.noreply.github.com> Date: Thu, 29 Jan 2026 18:03:27 -0800 Subject: [PATCH 10/84] Update sample_redteam_evaluations.py to use OS temp folder for output files (#44928) --- .../evaluations/sample_redteam_evaluations.py | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py b/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py index dee0bfd3b88e..4773ae76102c 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py +++ b/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py @@ -19,12 +19,11 @@ Set these environment variables with your own values: 1) AZURE_AI_PROJECT_ENDPOINT - Required. The Azure AI Project endpoint, as found in the overview page of your Microsoft Foundry project. It has the form: https://.services.ai.azure.com/api/projects/. - 2) DATA_FOLDER - Optional. The folder path where the data files for upload are located. - 3) AZURE_AI_AGENT_NAME - Required. The name of the Agent to perform red teaming evaluation on. + 2) AZURE_AI_AGENT_NAME - Required. The name of the Agent to perform red teaming evaluation on. """ import os - +import tempfile from dotenv import load_dotenv from pprint import pprint from azure.ai.projects.models._models import PromptAgentDefinition @@ -49,10 +48,6 @@ def main() -> None: endpoint = os.environ.get("AZURE_AI_PROJECT_ENDPOINT", "") agent_name = os.environ.get("AZURE_AI_AGENT_NAME", "") - # Construct the paths to the data folder and data file used in this sample - script_dir = os.path.dirname(os.path.abspath(__file__)) - data_folder = os.environ.get("DATA_FOLDER", os.path.join(script_dir, "data_folder")) - with ( DefaultAzureCredential() as credential, AIProjectClient(endpoint=endpoint, credential=credential) as project_client, @@ -99,9 +94,7 @@ def main() -> None: ) taxonomy = project_client.evaluation_taxonomies.create(name=agent_name, body=eval_taxonomy_input) - taxonomy_path = os.path.join(data_folder, f"taxonomy_{agent_name}.json") - # Create the data folder if it doesn't exist - os.makedirs(data_folder, exist_ok=True) + taxonomy_path = os.path.join(tempfile.gettempdir(), f"taxonomy_{agent_name}.json") with open(taxonomy_path, "w") as f: f.write(json.dumps(_to_json_primitive(taxonomy), indent=2)) print(f"Red teaming Taxonomy created for agent: {agent_name}. Taxonomy written to {taxonomy_path}") @@ -134,9 +127,7 @@ def main() -> None: run = client.evals.runs.retrieve(run_id=eval_run_response.id, eval_id=eval_object.id) if run.status == "completed" or run.status == "failed": output_items = list(client.evals.runs.output_items.list(run_id=run.id, eval_id=eval_object.id)) - output_items_path = os.path.join(data_folder, f"redteam_eval_output_items_{agent_name}.json") - # Create the data folder if it doesn't exist - os.makedirs(data_folder, exist_ok=True) + output_items_path = os.path.join(tempfile.gettempdir(), f"redteam_eval_output_items_{agent_name}.json") with open(output_items_path, "w") as f: f.write(json.dumps(_to_json_primitive(output_items), indent=2)) print( From 916e8a726e43391598b87c42451aafa2f9ad517e Mon Sep 17 00:00:00 2001 From: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> Date: Fri, 30 Jan 2026 15:34:31 +0800 Subject: [PATCH 11/84] bump typespec-python 0.59.2 (#44934) --- eng/emitter-package-lock.json | 26 +++++++++++++------------- eng/emitter-package.json | 8 ++++---- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index 1226079b31c8..1a534f600857 100644 --- a/eng/emitter-package-lock.json +++ b/eng/emitter-package-lock.json @@ -6,15 +6,15 @@ "": { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.1" + "@azure-tools/typespec-python": "0.59.2" }, "devDependencies": { "@azure-tools/openai-typespec": "1.7.3", - "@azure-tools/typespec-autorest": "~0.64.0", + "@azure-tools/typespec-autorest": "~0.64.1", "@azure-tools/typespec-azure-core": "~0.64.0", - "@azure-tools/typespec-azure-resource-manager": "~0.64.0", + "@azure-tools/typespec-azure-resource-manager": "~0.64.1", "@azure-tools/typespec-azure-rulesets": "~0.64.0", - "@azure-tools/typespec-client-generator-core": "~0.64.4", + "@azure-tools/typespec-client-generator-core": "~0.64.5", "@azure-tools/typespec-liftr-base": "0.11.0", "@typespec/compiler": "^1.8.0", "@typespec/events": "~0.78.0", @@ -146,13 +146,13 @@ "dev": true }, "node_modules/@azure-tools/typespec-python": { - "version": "0.59.1", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.1.tgz", - "integrity": "sha512-ZE+HV8iDNf3z4uJeVUpmbtdWwh9Uq349tpNiUAovPu+JIwGzwf8lKKWyGvW+5n0VR8WmI9ibj2yyMGvmiP2jeg==", + "version": "0.59.2", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.2.tgz", + "integrity": "sha512-rt6/YipPeZqTHoJZtE5mzG+FLzAuY+hHSHpudTMaKi8GPlsWlfZcPvb75BfLztvKrrGwEy682i7R1fAmwY7Pqw==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "@typespec/http-client-python": "~0.26.1", + "@typespec/http-client-python": "~0.26.2", "fs-extra": "~11.2.0", "js-yaml": "~4.1.0", "semver": "~7.6.2", @@ -162,9 +162,9 @@ "node": ">=20.0.0" }, "peerDependencies": { - "@azure-tools/typespec-autorest": ">=0.64.0 <1.0.0", + "@azure-tools/typespec-autorest": ">=0.64.1 <1.0.0", "@azure-tools/typespec-azure-core": ">=0.64.0 <1.0.0", - "@azure-tools/typespec-azure-resource-manager": ">=0.64.0 <1.0.0", + "@azure-tools/typespec-azure-resource-manager": ">=0.64.1 <1.0.0", "@azure-tools/typespec-azure-rulesets": ">=0.64.0 <1.0.0", "@azure-tools/typespec-client-generator-core": ">=0.64.5 <1.0.0", "@typespec/compiler": "^1.8.0", @@ -1079,9 +1079,9 @@ } }, "node_modules/@typespec/http-client-python": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.1.tgz", - "integrity": "sha512-QyPyYAB1qf+wxvH5FlHj8fJ3NttA1HeHUVVPLeUyyItOXAWDVczTVbDfhgS73TkrFeOb8A56NKgTVy74lt/H3g==", + "version": "0.26.2", + "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.2.tgz", + "integrity": "sha512-bNpjViWsaZER3Z0O/QYgo4OALTDubPuCwuq0iExb8U5AIig/CB4Qsi9zVRtyRfH0ZZ2KJqjlTYaHazrtX4bqLA==", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/eng/emitter-package.json b/eng/emitter-package.json index b712556e4310..e16ca6495676 100644 --- a/eng/emitter-package.json +++ b/eng/emitter-package.json @@ -1,7 +1,7 @@ { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.1" + "@azure-tools/typespec-python": "0.59.2" }, "devDependencies": { "@typespec/compiler": "^1.8.0", @@ -14,11 +14,11 @@ "@typespec/streams": "~0.78.0", "@typespec/xml": "~0.78.0", "@azure-tools/openai-typespec": "1.7.3", - "@azure-tools/typespec-autorest": "~0.64.0", + "@azure-tools/typespec-autorest": "~0.64.1", "@azure-tools/typespec-azure-core": "~0.64.0", - "@azure-tools/typespec-azure-resource-manager": "~0.64.0", + "@azure-tools/typespec-azure-resource-manager": "~0.64.1", "@azure-tools/typespec-azure-rulesets": "~0.64.0", - "@azure-tools/typespec-client-generator-core": "~0.64.4", + "@azure-tools/typespec-client-generator-core": "~0.64.5", "@azure-tools/typespec-liftr-base": "0.11.0" } } \ No newline at end of file From 519173c9ada67669d2fca63aefab317a6aead1e3 Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Fri, 30 Jan 2026 09:31:28 -0800 Subject: [PATCH 12/84] Enable live metrics be default (#44902) * Enable live metrics by default * Add CHANGELOG * Update tests * Remove testing fixtures * Modify CHANGELOG * Retrigger CI/CD pipeline * Retrigger CI/CD pipeline --- .../azure-monitor-opentelemetry/CHANGELOG.md | 3 +++ sdk/monitor/azure-monitor-opentelemetry/README.md | 2 +- .../azure/monitor/opentelemetry/_configure.py | 2 +- .../monitor/opentelemetry/_utils/configurations.py | 2 +- .../samples/metrics/live_metrics.py | 6 +++--- .../tests/test_configure.py | 14 +++++++------- .../tests/utils/test_configurations.py | 6 +++--- 7 files changed, 19 insertions(+), 16 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md index 5479d44d416d..c323344495e6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md @@ -4,6 +4,9 @@ ### Features Added +- Enable live metrics by default + ([#44902](https://github.com/Azure/azure-sdk-for-python/pull/44902)) + ### Breaking Changes ### Bugs Fixed diff --git a/sdk/monitor/azure-monitor-opentelemetry/README.md b/sdk/monitor/azure-monitor-opentelemetry/README.md index 03bf5325ab24..2373227a08cf 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/README.md +++ b/sdk/monitor/azure-monitor-opentelemetry/README.md @@ -60,7 +60,7 @@ You can use `configure_azure_monitor` to set up instrumentation for your app to | Parameter | Description | Environment Variable | |-------------------|----------------------------------------------------|----------------------| | `connection_string` | The [connection string][connection_string_doc] for your Application Insights resource. The connection string will be automatically populated from the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable if not explicitly passed in. | `APPLICATIONINSIGHTS_CONNECTION_STRING` | -| `enable_live_metrics` | Enable [live metrics][application_insights_live_metrics] feature. Defaults to `False`. | `N/A` | +| `enable_live_metrics` | Enable [live metrics][application_insights_live_metrics] feature. Defaults to `True`. | `N/A` | | `enable_performance_counters` | Enable [performance counters][application_insights_performance_counters]. Defaults to `True`. | `N/A` | | `logging_formatter` | A Python logging [formatter][python_logging_formatter] that will be used to format collected logs. | `PYTHON_APPLICATIONINSIGHTS_LOGGING_FORMAT` - accepts a STRING field used for formatting, not a [formatter][python_logging_formatter] | | `logger_name` | The name of the [Python logger][python_logger] under which telemetry is collected. Setting this value is imperative so logs created from the SDK itself are not tracked. | `PYTHON_APPLICATIONINSIGHTS_LOGGER_NAME` | diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py index 0ccf13c40bb6..af8988a6b891 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py @@ -112,7 +112,7 @@ def configure_azure_monitor(**kwargs) -> None: # pylint: disable=C4758 :keyword list[~opentelemetry.sdk.metrics.MetricReader] metric_readers: List of MetricReader objects to read and export metrics. Each reader can have its own exporter and collection interval. :keyword bool enable_live_metrics: Boolean value to determine whether to enable live metrics feature. - Defaults to `False`. + Defaults to `True`. :keyword bool enable_performance_counters: Boolean value to determine whether to enable performance counters. Defaults to `True`. :keyword str storage_directory: Storage directory in which to store retry files. Defaults to diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py index de694de31e57..183017cd5d91 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py @@ -314,7 +314,7 @@ def _default_metric_readers(configurations): def _default_enable_live_metrics(configurations): - configurations.setdefault(ENABLE_LIVE_METRICS_ARG, False) + configurations.setdefault(ENABLE_LIVE_METRICS_ARG, True) def _default_enable_performance_counters(configurations): diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py index 742633419f4e..2b6b4e24d1da 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py @@ -5,8 +5,9 @@ # -------------------------------------------------------------------------- """ -This example shows how configure live metrics to be enabled. It sets up a minimal example of sending dependency, +This example sets up a minimal example of sending dependency through live metrics, trace and exception telemetry to demonstrate the capabilities and collection set of live metrics. +Live metrics is enabled by default, it can be disabled by setting `enable_live_metrics` to `False` """ import logging import requests # type: ignore[import-untyped] @@ -14,7 +15,6 @@ from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace - from opentelemetry.sdk.resources import Resource configure_azure_monitor( @@ -25,7 +25,7 @@ } ), logger_name=__name__, - enable_live_metrics=True, # Enable live metrics configuration + # enable_live_metrics=False, # To disable live metrics configuration ) tracer = trace.get_tracer(__name__) diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py b/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py index a5dd375f0516..1db4b9adc5bd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py @@ -68,7 +68,7 @@ def test_configure_azure_monitor( tracing_mock.assert_called_once() logging_mock.assert_called_once() metrics_mock.assert_called_once() - live_metrics_mock.assert_not_called() + live_metrics_mock.assert_called_once() instrumentation_mock.assert_called_once() detect_attach_mock.assert_called_once() @@ -109,7 +109,7 @@ def test_configure_azure_monitor_disable_tracing( "django": {"enabled": False}, "requests": {"enabled": False}, }, - "enable_live_metrics": False, + "enable_live_metrics": True, "enable_performance_counters": True, "resource": TEST_RESOURCE, } @@ -123,7 +123,7 @@ def test_configure_azure_monitor_disable_tracing( tracing_mock.assert_not_called() logging_mock.assert_called_once_with(configurations) metrics_mock.assert_called_once_with(configurations) - live_metrics_mock.assert_not_called() + live_metrics_mock.assert_called_once_with(configurations) instrumentation_mock.assert_called_once_with(configurations) # Assert setup_metrics is called before setup_logging self.assertLess(call_order.index("metrics"), call_order.index("logging")) @@ -160,7 +160,7 @@ def test_configure_azure_monitor_disable_logging( "disable_tracing": False, "disable_logging": True, "disable_metrics": False, - "enable_live_metrics": False, + "enable_live_metrics": True, "enable_performance_counters": True, "resource": TEST_RESOURCE, } @@ -174,7 +174,7 @@ def test_configure_azure_monitor_disable_logging( tracing_mock.assert_called_once_with(configurations) logging_mock.assert_not_called() metrics_mock.assert_called_once_with(configurations) - live_metrics_mock.assert_not_called() + live_metrics_mock.assert_called_once_with(configurations) instrumentation_mock.assert_called_once_with(configurations) # Assert setup_metrics is called before setup_tracing self.assertLess(call_order.index("metrics"), call_order.index("tracing")) @@ -211,7 +211,7 @@ def test_configure_azure_monitor_disable_metrics( "disable_tracing": False, "disable_logging": False, "disable_metrics": True, - "enable_live_metrics": False, + "enable_live_metrics": True, "enable_performance_counters": True, "resource": TEST_RESOURCE, } @@ -220,7 +220,7 @@ def test_configure_azure_monitor_disable_metrics( tracing_mock.assert_called_once_with(configurations) logging_mock.assert_called_once_with(configurations) metrics_mock.assert_not_called() - live_metrics_mock.assert_not_called() + live_metrics_mock.assert_called_once_with(configurations) instrumentation_mock.assert_called_once_with(configurations) @patch( diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py index 7d2d22f22ff5..7684db635893 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py @@ -81,7 +81,7 @@ def test_get_configurations(self, resource_create_mock): "enabled": False, } }, - enable_live_metrics=True, + enable_live_metrics=False, enable_performance_counters=False, views=["test_view"], logger_name="test_logger", @@ -117,7 +117,7 @@ def test_get_configurations(self, resource_create_mock): }, ) self.assertEqual(configurations["storage_directory"], "test_directory") - self.assertEqual(configurations["enable_live_metrics"], True) + self.assertEqual(configurations["enable_live_metrics"], False) self.assertEqual(configurations["enable_performance_counters"], False) self.assertEqual(configurations["views"], ["test_view"]) self.assertEqual(configurations["logger_name"], "test_logger") @@ -154,7 +154,7 @@ def test_get_configurations_defaults(self, resource_create_mock): self.assertEqual(configurations["sampling_ratio"], 1.0) self.assertTrue("credential" not in configurations) self.assertTrue("storage_directory" not in configurations) - self.assertEqual(configurations["enable_live_metrics"], False) + self.assertEqual(configurations["enable_live_metrics"], True) self.assertEqual(configurations["enable_performance_counters"], True) self.assertEqual(configurations["logger_name"], "") self.assertEqual(configurations["span_processors"], []) From 7f9beed6e230e530331ccdffc8bd424f2a59693e Mon Sep 17 00:00:00 2001 From: xitzhang Date: Fri, 30 Jan 2026 11:11:19 -0800 Subject: [PATCH 13/84] [VoiceLive]Add Foundry agent integration, filler response configuration, and reasoning effort control (#44773) * [VoiceLive]Add Foundry agent integration, filler response configuration, and reasoning effort control * Update sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * add defualt value for endpoint * update models * update cspell * Add Scene model, ServerEventWarning, and AvatarConfig enhancements * update change log * update sample * remove warning * update cspell * remove blank --------- Co-authored-by: Xiting Zhang Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-voicelive/CHANGELOG.md | 22 +- .../apiview-properties.json | 17 +- .../azure/ai/voicelive/_types.py | 1 + .../azure/ai/voicelive/_utils/model_base.py | 110 ++- .../ai/voicelive/_utils/serialization.py | 17 +- .../azure/ai/voicelive/models/__init__.py | 30 + .../azure/ai/voicelive/models/_enums.py | 59 +- .../azure/ai/voicelive/models/_models.py | 851 ++++++++++++++++-- sdk/ai/azure-ai-voicelive/pyproject.toml | 2 +- .../samples/async_function_calling_sample.py | 2 +- .../samples/async_mcp_sample.py | 24 +- .../samples/supervisor_agent_sample.py | 637 +++++++++++++ .../tests/test_live_realtime_service.py | 1 + .../tests/test_unit_enums.py | 4 +- .../tests/test_unit_models_filler_foundry.py | 669 ++++++++++++++ .../tests/test_unit_serialization.py | 59 ++ 16 files changed, 2407 insertions(+), 98 deletions(-) create mode 100644 sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py create mode 100644 sdk/ai/azure-ai-voicelive/tests/test_unit_models_filler_foundry.py diff --git a/sdk/ai/azure-ai-voicelive/CHANGELOG.md b/sdk/ai/azure-ai-voicelive/CHANGELOG.md index 483d70489edb..b44c4fffc9dc 100644 --- a/sdk/ai/azure-ai-voicelive/CHANGELOG.md +++ b/sdk/ai/azure-ai-voicelive/CHANGELOG.md @@ -5,13 +5,33 @@ ### Features Added - **Support for Explicit Null Values**: Enhanced `RequestSession` to properly serialize explicitly set `None` values (e.g., `turn_detection=None` now correctly sends `"turn_detection": null` in the WebSocket message) +- **Filler Response Configuration**: Added support for filler response generation during latency or tool calls: + - `BasicFillerResponseConfig` for static filler texts that are randomly selected + - `LlmFillerResponseConfig` for LLM-generated context-aware filler responses + - `FillerTrigger` enum with `latency` and `tool` triggers + - `filler_response` field in `RequestSession` and `ResponseSession` +- **Foundry Agent Integration**: Added support for Azure AI Foundry agents: + - `FoundryAgentTool` for defining Foundry agent configurations + - `ResponseFoundryAgentCallItem` for Foundry agent call responses + - `FoundryAgentContextType` enum for context management (`no_context`, `agent_context`) + - Server events for Foundry agent call lifecycle: `ServerEventResponseFoundryAgentCallArgumentsDelta`, `ServerEventResponseFoundryAgentCallArgumentsDone`, `ServerEventResponseFoundryAgentCallInProgress`, `ServerEventResponseFoundryAgentCallCompleted`, `ServerEventResponseFoundryAgentCallFailed` +- **Reasoning Effort Control**: Added `reasoning_effort` field to `RequestSession`, `ResponseSession`, and `ResponseCreateParams` for controlling reasoning models effort levels with `ReasoningEffort` enum (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`) +- **Response Metadata**: Added `metadata` field to `Response` and `ResponseCreateParams` for attaching up to 16 key-value pairs (max 64 chars for keys, 512 chars for values) +- **Array Encoding Support**: Enhanced serialization to support pipe, space, comma, and newline-delimited array encoding formats +- **Custom Text Normalization**: Added `custom_text_normalization_url` field to `AzureStandardVoice`, `AzureCustomVoice`, and `AzurePersonalVoice` for custom text normalization configurations +- **Avatar Scene Configuration**: Added `Scene` model for controlling avatar's zoom level, position (x/y), rotation (x/y/z pitch/yaw/roll), and movement amplitude in the video frame +- **Enhanced Avatar Configuration**: Added `scene` and `output_audit_audio` fields to `AvatarConfig` for scene control and audit audio forwarding via WebSocket ### Other Changes -- **Dependency Update**: Updated minimum `azure-core` version from 1.35.0 to 1.36.0 +- **Dependency Update**: Updated minimum `azure-core` version from 1.36.0 to 1.37.0 +- **Security Enhancement**: Removed `eval()` usage in serialization utilities, replaced with explicit type checking for improved security +- **Serialization Improvements**: Enhanced model_base deserialization for mutable types and array-encoded strings ### Bug Fixes +- **Audio Format Values**: Fixed `OutputAudioFormat` enum values to use underscore format (`pcm16_8000hz`, `pcm16_16000hz`) instead of hyphenated format for consistency with wire protocol and backward compatibility + ## 1.2.0b2 (2025-11-20) ### Features Added diff --git a/sdk/ai/azure-ai-voicelive/apiview-properties.json b/sdk/ai/azure-ai-voicelive/apiview-properties.json index 11a239dd8cfa..1bde12b720f5 100644 --- a/sdk/ai/azure-ai-voicelive/apiview-properties.json +++ b/sdk/ai/azure-ai-voicelive/apiview-properties.json @@ -23,6 +23,8 @@ "azure.ai.voicelive.models.AzureSemanticVadMultilingual": "VoiceLive.AzureSemanticVadMultilingual", "azure.ai.voicelive.models.AzureStandardVoice": "VoiceLive.AzureStandardVoice", "azure.ai.voicelive.models.Background": "VoiceLive.Background", + "azure.ai.voicelive.models.FillerResponseConfigBase": "VoiceLive.FillerResponseConfigBase", + "azure.ai.voicelive.models.BasicFillerResponseConfig": "VoiceLive.BasicFillerResponseConfig", "azure.ai.voicelive.models.CachedTokenDetails": "VoiceLive.CachedTokenDetails", "azure.ai.voicelive.models.ClientEvent": "VoiceLive.ClientEvent", "azure.ai.voicelive.models.ClientEventConversationItemCreate": "VoiceLive.ClientEventConversationItemCreate", @@ -44,15 +46,17 @@ "azure.ai.voicelive.models.ContentPart": "VoiceLive.ContentPart", "azure.ai.voicelive.models.ConversationItemBase": "VoiceLive.ConversationItemBase", "azure.ai.voicelive.models.ErrorResponse": "VoiceLive.ErrorResponse", + "azure.ai.voicelive.models.Tool": "VoiceLive.Tool", + "azure.ai.voicelive.models.FoundryAgentTool": "VoiceLive.FoundryAgentTool", "azure.ai.voicelive.models.FunctionCallItem": "VoiceLive.FunctionCallItem", "azure.ai.voicelive.models.FunctionCallOutputItem": "VoiceLive.FunctionCallOutputItem", - "azure.ai.voicelive.models.Tool": "VoiceLive.Tool", "azure.ai.voicelive.models.FunctionTool": "VoiceLive.FunctionTool", "azure.ai.voicelive.models.IceServer": "VoiceLive.IceServer", "azure.ai.voicelive.models.MessageContentPart": "VoiceLive.MessageContentPart", "azure.ai.voicelive.models.InputAudioContentPart": "VoiceLive.InputAudioContentPart", "azure.ai.voicelive.models.InputTextContentPart": "VoiceLive.InputTextContentPart", "azure.ai.voicelive.models.InputTokenDetails": "VoiceLive.InputTokenDetails", + "azure.ai.voicelive.models.LlmFillerResponseConfig": "VoiceLive.LlmFillerResponseConfig", "azure.ai.voicelive.models.LogProbProperties": "VoiceLive.LogProbProperties", "azure.ai.voicelive.models.MCPApprovalResponseRequestItem": "VoiceLive.MCPApprovalResponseRequestItem", "azure.ai.voicelive.models.MCPServer": "VoiceLive.MCPServer", @@ -71,6 +75,7 @@ "azure.ai.voicelive.models.ResponseCreateParams": "VoiceLive.ResponseCreateParams", "azure.ai.voicelive.models.ResponseFailedDetails": "VoiceLive.ResponseFailedDetails", "azure.ai.voicelive.models.ResponseItem": "VoiceLive.ResponseItem", + "azure.ai.voicelive.models.ResponseFoundryAgentCallItem": "VoiceLive.ResponseFoundryAgentCallItem", "azure.ai.voicelive.models.ResponseFunctionCallItem": "VoiceLive.ResponseFunctionCallItem", "azure.ai.voicelive.models.ResponseFunctionCallOutputItem": "VoiceLive.ResponseFunctionCallOutputItem", "azure.ai.voicelive.models.ResponseIncompleteDetails": "VoiceLive.ResponseIncompleteDetails", @@ -81,6 +86,7 @@ "azure.ai.voicelive.models.ResponseMessageItem": "VoiceLive.ResponseMessageItem", "azure.ai.voicelive.models.ResponseSession": "VoiceLive.ResponseSession", "azure.ai.voicelive.models.ResponseTextContentPart": "VoiceLive.ResponseTextContentPart", + "azure.ai.voicelive.models.Scene": "VoiceLive.Scene", "azure.ai.voicelive.models.ServerEvent": "VoiceLive.ServerEvent", "azure.ai.voicelive.models.ServerEventConversationItemCreated": "VoiceLive.ServerEventConversationItemCreated", "azure.ai.voicelive.models.ServerEventConversationItemDeleted": "VoiceLive.ServerEventConversationItemDeleted", @@ -112,6 +118,11 @@ "azure.ai.voicelive.models.ServerEventResponseContentPartDone": "VoiceLive.ServerEventResponseContentPartDone", "azure.ai.voicelive.models.ServerEventResponseCreated": "VoiceLive.ServerEventResponseCreated", "azure.ai.voicelive.models.ServerEventResponseDone": "VoiceLive.ServerEventResponseDone", + "azure.ai.voicelive.models.ServerEventResponseFoundryAgentCallArgumentsDelta": "VoiceLive.ServerEventResponseFoundryAgentCallArgumentsDelta", + "azure.ai.voicelive.models.ServerEventResponseFoundryAgentCallArgumentsDone": "VoiceLive.ServerEventResponseFoundryAgentCallArgumentsDone", + "azure.ai.voicelive.models.ServerEventResponseFoundryAgentCallCompleted": "VoiceLive.ServerEventResponseFoundryAgentCallCompleted", + "azure.ai.voicelive.models.ServerEventResponseFoundryAgentCallFailed": "VoiceLive.ServerEventResponseFoundryAgentCallFailed", + "azure.ai.voicelive.models.ServerEventResponseFoundryAgentCallInProgress": "VoiceLive.ServerEventResponseFoundryAgentCallInProgress", "azure.ai.voicelive.models.ServerEventResponseFunctionCallArgumentsDelta": "VoiceLive.ServerEventResponseFunctionCallArgumentsDelta", "azure.ai.voicelive.models.ServerEventResponseFunctionCallArgumentsDone": "VoiceLive.ServerEventResponseFunctionCallArgumentsDone", "azure.ai.voicelive.models.ServerEventResponseMcpCallArgumentsDelta": "VoiceLive.ServerEventResponseMcpCallArgumentsDelta", @@ -148,7 +159,9 @@ "azure.ai.voicelive.models.PersonalVoiceModels": "VoiceLive.PersonalVoiceModels", "azure.ai.voicelive.models.OutputAudioFormat": "VoiceLive.OutputAudioFormat", "azure.ai.voicelive.models.ToolType": "VoiceLive.ToolType", + "azure.ai.voicelive.models.FoundryAgentContextType": "VoiceLive.FoundryAgentContextType", "azure.ai.voicelive.models.MCPApprovalType": "VoiceLive.MCPApprovalType", + "azure.ai.voicelive.models.ReasoningEffort": "VoiceLive.ReasoningEffort", "azure.ai.voicelive.models.AnimationOutputType": "VoiceLive.AnimationOutputType", "azure.ai.voicelive.models.InputAudioFormat": "VoiceLive.InputAudioFormat", "azure.ai.voicelive.models.TurnDetectionType": "VoiceLive.TurnDetectionType", @@ -158,6 +171,8 @@ "azure.ai.voicelive.models.AvatarOutputProtocol": "VoiceLive.AvatarOutputProtocol", "azure.ai.voicelive.models.AudioTimestampType": "VoiceLive.AudioTimestampType", "azure.ai.voicelive.models.ToolChoiceLiteral": "VoiceLive.ToolChoiceLiteral", + "azure.ai.voicelive.models.FillerResponseConfigType": "VoiceLive.FillerResponseConfigType", + "azure.ai.voicelive.models.FillerTrigger": "VoiceLive.FillerTrigger", "azure.ai.voicelive.models.ResponseStatus": "VoiceLive.ResponseStatus", "azure.ai.voicelive.models.ResponseItemStatus": "VoiceLive.ResponseItemStatus", "azure.ai.voicelive.models.RequestImageContentPartDetail": "VoiceLive.RequestImageContentPartDetail", diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_types.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_types.py index af1ff22f45b7..86801624e71f 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_types.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_types.py @@ -12,3 +12,4 @@ from . import models as _models Voice = Union[str, "_models.OpenAIVoiceName", "_models.OpenAIVoice", "_models.AzureVoice"] ToolChoice = Union[str, "_models.ToolChoiceLiteral", "_models.ToolChoiceSelection"] +FillerResponseConfig = Union["_models.BasicFillerResponseConfig", "_models.LlmFillerResponseConfig"] diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/model_base.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/model_base.py index 12926fa98dcf..d962e0e8fceb 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/model_base.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/model_base.py @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -767,6 +817,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +878,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -998,7 +1059,11 @@ def __init__( @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1074,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1184,7 +1272,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1285,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/serialization.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/serialization.py index 45a3e44e45cb..81ec1de5922b 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/serialization.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_utils/serialization.py @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/__init__.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/__init__.py index 0b0327e00d38..b38881c5313c 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/__init__.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/__init__.py @@ -32,6 +32,7 @@ AzureStandardVoice, AzureVoice, Background, + BasicFillerResponseConfig, CachedTokenDetails, ClientEvent, ClientEventConversationItemCreate, @@ -55,6 +56,8 @@ ConversationRequestItem, EouDetection, ErrorResponse, + FillerResponseConfigBase, + FoundryAgentTool, FunctionCallItem, FunctionCallOutputItem, FunctionTool, @@ -62,6 +65,7 @@ InputAudioContentPart, InputTextContentPart, InputTokenDetails, + LlmFillerResponseConfig, LogProbProperties, MCPApprovalResponseRequestItem, MCPServer, @@ -80,6 +84,7 @@ ResponseCancelledDetails, ResponseCreateParams, ResponseFailedDetails, + ResponseFoundryAgentCallItem, ResponseFunctionCallItem, ResponseFunctionCallOutputItem, ResponseIncompleteDetails, @@ -92,6 +97,7 @@ ResponseSession, ResponseStatusDetails, ResponseTextContentPart, + Scene, ServerEvent, ServerEventConversationItemCreated, ServerEventConversationItemDeleted, @@ -123,6 +129,11 @@ ServerEventResponseContentPartDone, ServerEventResponseCreated, ServerEventResponseDone, + ServerEventResponseFoundryAgentCallArgumentsDelta, + ServerEventResponseFoundryAgentCallArgumentsDone, + ServerEventResponseFoundryAgentCallCompleted, + ServerEventResponseFoundryAgentCallFailed, + ServerEventResponseFoundryAgentCallInProgress, ServerEventResponseFunctionCallArgumentsDelta, ServerEventResponseFunctionCallArgumentsDone, ServerEventResponseMcpCallArgumentsDelta, @@ -161,6 +172,9 @@ ClientEventType, ContentPartType, EouThresholdLevel, + FillerResponseConfigType, + FillerTrigger, + FoundryAgentContextType, InputAudioFormat, ItemParamStatus, ItemType, @@ -171,6 +185,7 @@ OutputAudioFormat, PersonalVoiceModels, PhotoAvatarBaseModes, + ReasoningEffort, RequestImageContentPartDetail, ResponseItemStatus, ResponseStatus, @@ -202,6 +217,7 @@ "AzureStandardVoice", "AzureVoice", "Background", + "BasicFillerResponseConfig", "CachedTokenDetails", "ClientEvent", "ClientEventConversationItemCreate", @@ -225,6 +241,8 @@ "ConversationRequestItem", "EouDetection", "ErrorResponse", + "FillerResponseConfigBase", + "FoundryAgentTool", "FunctionCallItem", "FunctionCallOutputItem", "FunctionTool", @@ -232,6 +250,7 @@ "InputAudioContentPart", "InputTextContentPart", "InputTokenDetails", + "LlmFillerResponseConfig", "LogProbProperties", "MCPApprovalResponseRequestItem", "MCPServer", @@ -250,6 +269,7 @@ "ResponseCancelledDetails", "ResponseCreateParams", "ResponseFailedDetails", + "ResponseFoundryAgentCallItem", "ResponseFunctionCallItem", "ResponseFunctionCallOutputItem", "ResponseIncompleteDetails", @@ -262,6 +282,7 @@ "ResponseSession", "ResponseStatusDetails", "ResponseTextContentPart", + "Scene", "ServerEvent", "ServerEventConversationItemCreated", "ServerEventConversationItemDeleted", @@ -293,6 +314,11 @@ "ServerEventResponseContentPartDone", "ServerEventResponseCreated", "ServerEventResponseDone", + "ServerEventResponseFoundryAgentCallArgumentsDelta", + "ServerEventResponseFoundryAgentCallArgumentsDone", + "ServerEventResponseFoundryAgentCallCompleted", + "ServerEventResponseFoundryAgentCallFailed", + "ServerEventResponseFoundryAgentCallInProgress", "ServerEventResponseFunctionCallArgumentsDelta", "ServerEventResponseFunctionCallArgumentsDone", "ServerEventResponseMcpCallArgumentsDelta", @@ -328,6 +354,9 @@ "ClientEventType", "ContentPartType", "EouThresholdLevel", + "FillerResponseConfigType", + "FillerTrigger", + "FoundryAgentContextType", "InputAudioFormat", "ItemParamStatus", "ItemType", @@ -338,6 +367,7 @@ "OutputAudioFormat", "PersonalVoiceModels", "PhotoAvatarBaseModes", + "ReasoningEffort", "RequestImageContentPartDetail", "ResponseItemStatus", "ResponseStatus", diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_enums.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_enums.py index 7b700bbdf126..24d291e8c06b 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_enums.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_enums.py @@ -100,6 +100,33 @@ class EouThresholdLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Default sensitivity threshold level.""" +class FillerResponseConfigType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Filler response configuration types.""" + + STATIC_FILLER = "static_filler" + """Static filler configuration type.""" + LLM_FILLER = "llm_filler" + """LLM-based filler configuration type.""" + + +class FillerTrigger(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Triggers that can activate filler response generation.""" + + LATENCY = "latency" + """Trigger filler when response latency exceeds threshold.""" + TOOL = "tool" + """Trigger filler when a tool call is being executed.""" + + +class FoundryAgentContextType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The available set of Foundry agent context types.""" + + NO_CONTEXT = "no_context" + """Only the current user input is sent, no context maintained.""" + AGENT_CONTEXT = "agent_context" + """Agent maintains its own context (thread), only current input sent per call.""" + + class InputAudioFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Input audio format types supported.""" @@ -130,6 +157,7 @@ class ItemType(str, Enum, metaclass=CaseInsensitiveEnumMeta): MCP_CALL = "mcp_call" MCP_APPROVAL_REQUEST = "mcp_approval_request" MCP_APPROVAL_RESPONSE = "mcp_approval_response" + FOUNDRY_AGENT_CALL = "foundry_agent_call" class MCPApprovalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -192,9 +220,9 @@ class OutputAudioFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): PCM16 = "pcm16" """16-bit PCM audio format at default sampling rate (24kHz)""" - PCM16_8000_HZ = "pcm16-8000hz" + PCM16_8000_HZ = "pcm16_8000hz" """16-bit PCM audio format at 8kHz sampling rate""" - PCM16_16000_HZ = "pcm16-16000hz" + PCM16_16000_HZ = "pcm16_16000hz" """16-bit PCM audio format at 16kHz sampling rate""" G711_ULAW = "g711_ulaw" """G.711 μ-law (mu-law) audio format at 8kHz sampling rate""" @@ -220,6 +248,27 @@ class PhotoAvatarBaseModes(str, Enum, metaclass=CaseInsensitiveEnumMeta): """VASA-1 model""" +class ReasoningEffort(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Constrains effort on reasoning for reasoning models. Check model documentation for supported + values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. + """ + + NONE = "none" + """No reasoning effort.""" + MINIMAL = "minimal" + """Minimal reasoning effort.""" + LOW = "low" + """Low reasoning effort - faster responses with less reasoning.""" + MEDIUM = "medium" + """Medium reasoning effort - balanced between speed and reasoning depth.""" + HIGH = "high" + """High reasoning effort - more thorough reasoning, may take longer.""" + XHIGH = "xhigh" + """Extra high reasoning effort - maximum reasoning depth.""" + + class RequestImageContentPartDetail(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies an image's detail level. Can be 'auto', 'low', 'high', or an unknown future value.""" @@ -300,6 +349,11 @@ class ServerEventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): RESPONSE_MCP_CALL_IN_PROGRESS = "response.mcp_call.in_progress" RESPONSE_MCP_CALL_COMPLETED = "response.mcp_call.completed" RESPONSE_MCP_CALL_FAILED = "response.mcp_call.failed" + RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA = "response.foundry_agent_call_arguments.delta" + RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE = "response.foundry_agent_call_arguments.done" + RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS = "response.foundry_agent_call.in_progress" + RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED = "response.foundry_agent_call.completed" + RESPONSE_FOUNDRY_AGENT_CALL_FAILED = "response.foundry_agent_call.failed" class ToolChoiceLiteral(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -320,6 +374,7 @@ class ToolType(str, Enum, metaclass=CaseInsensitiveEnumMeta): FUNCTION = "function" MCP = "mcp" + FOUNDRY_AGENT = "foundry_agent" class TurnDetectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py index 87ddc5547a8a..bef8a9eb7fa8 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/models/_models.py @@ -15,6 +15,7 @@ AzureVoiceType, ClientEventType, ContentPartType, + FillerResponseConfigType, ItemType, MessageRole, ResponseStatus, @@ -117,7 +118,8 @@ class ConversationRequestItem(_Model): FunctionCallItem, FunctionCallOutputItem, MCPApprovalResponseRequestItem, MessageItem :ivar type: Required. Known values are: "message", "function_call", "function_call_output", - "mcp_list_tools", "mcp_call", "mcp_approval_request", and "mcp_approval_response". + "mcp_list_tools", "mcp_call", "mcp_approval_request", "mcp_approval_response", and + "foundry_agent_call". :vartype type: str or ~azure.ai.voicelive.models.ItemType :ivar id: :vartype id: str @@ -126,7 +128,8 @@ class ConversationRequestItem(_Model): __mapping__: dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) """Required. Known values are: \"message\", \"function_call\", \"function_call_output\", - \"mcp_list_tools\", \"mcp_call\", \"mcp_approval_request\", and \"mcp_approval_response\".""" + \"mcp_list_tools\", \"mcp_call\", \"mcp_approval_request\", \"mcp_approval_response\", and + \"foundry_agent_call\".""" id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @overload @@ -374,9 +377,15 @@ class AvatarConfig(_Model): :vartype customized: bool :ivar video: Optional video configuration including resolution, bitrate, and codec. :vartype video: ~azure.ai.voicelive.models.VideoParams + :ivar scene: Configuration for the avatar's zoom level, position, rotation and movement + amplitude in the video frame. + :vartype scene: ~azure.ai.voicelive.models.Scene :ivar output_protocol: Output protocol for avatar streaming. Default is 'webrtc'. Known values are: "webrtc" and "websocket". :vartype output_protocol: str or ~azure.ai.voicelive.models.AvatarOutputProtocol + :ivar output_audit_audio: When enabled, forwards audit audio via WebSocket for review/debugging + purposes, even when avatar output is delivered via WebRTC. + :vartype output_audit_audio: bool """ type: Optional[Union[str, "_models.AvatarConfigTypes"]] = rest_field( @@ -399,11 +408,17 @@ class AvatarConfig(_Model): """Indicates whether the avatar is customized or not. Required.""" video: Optional["_models.VideoParams"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional video configuration including resolution, bitrate, and codec.""" + scene: Optional["_models.Scene"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Configuration for the avatar's zoom level, position, rotation and movement amplitude in the + video frame.""" output_protocol: Optional[Union[str, "_models.AvatarOutputProtocol"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """Output protocol for avatar streaming. Default is 'webrtc'. Known values are: \"webrtc\" and \"websocket\".""" + output_audit_audio: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """When enabled, forwards audit audio via WebSocket for review/debugging purposes, even when + avatar output is delivered via WebRTC.""" @overload def __init__( @@ -416,7 +431,9 @@ def __init__( style: Optional[str] = None, model: Optional[Union[str, "_models.PhotoAvatarBaseModes"]] = None, video: Optional["_models.VideoParams"] = None, + scene: Optional["_models.Scene"] = None, output_protocol: Optional[Union[str, "_models.AvatarOutputProtocol"]] = None, + output_audit_audio: Optional[bool] = None, ) -> None: ... @overload @@ -477,6 +494,8 @@ class AzureCustomVoice(AzureVoice, discriminator="azure-custom"): :vartype temperature: float :ivar custom_lexicon_url: :vartype custom_lexicon_url: str + :ivar custom_text_normalization_url: + :vartype custom_text_normalization_url: str :ivar prefer_locales: :vartype prefer_locales: list[str] :ivar locale: @@ -500,6 +519,9 @@ class AzureCustomVoice(AzureVoice, discriminator="azure-custom"): temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Temperature must be between 0.0 and 1.0.""" custom_lexicon_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + custom_text_normalization_url: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) prefer_locales: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) locale: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) style: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -515,6 +537,7 @@ def __init__( endpoint_id: str, temperature: Optional[float] = None, custom_lexicon_url: Optional[str] = None, + custom_text_normalization_url: Optional[str] = None, prefer_locales: Optional[list[str]] = None, locale: Optional[str] = None, style: Optional[str] = None, @@ -549,6 +572,8 @@ class AzurePersonalVoice(AzureVoice, discriminator="azure-personal"): :vartype model: str or ~azure.ai.voicelive.models.PersonalVoiceModels :ivar custom_lexicon_url: :vartype custom_lexicon_url: str + :ivar custom_text_normalization_url: + :vartype custom_text_normalization_url: str :ivar prefer_locales: :vartype prefer_locales: list[str] :ivar locale: @@ -575,6 +600,9 @@ class AzurePersonalVoice(AzureVoice, discriminator="azure-personal"): """Underlying neural model to use for personal voice. Required. Known values are: \"DragonLatestNeural\", \"PhoenixLatestNeural\", and \"PhoenixV2Neural\".""" custom_lexicon_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + custom_text_normalization_url: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) prefer_locales: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) locale: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) style: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -590,6 +618,7 @@ def __init__( model: Union[str, "_models.PersonalVoiceModels"], temperature: Optional[float] = None, custom_lexicon_url: Optional[str] = None, + custom_text_normalization_url: Optional[str] = None, prefer_locales: Optional[list[str]] = None, locale: Optional[str] = None, style: Optional[str] = None, @@ -618,7 +647,7 @@ class EouDetection(_Model): :ivar model: Required. Is one of the following types: Literal["semantic_detection_v1"], Literal["semantic_detection_v1_en"], Literal["semantic_detection_v1_multilingual"], str - :vartype model: str or str or str or str + :vartype model: str """ __mapping__: dict[str, _Model] = {} @@ -1024,6 +1053,8 @@ class AzureStandardVoice(AzureVoice, discriminator="azure-standard"): :vartype temperature: float :ivar custom_lexicon_url: :vartype custom_lexicon_url: str + :ivar custom_text_normalization_url: + :vartype custom_text_normalization_url: str :ivar prefer_locales: :vartype prefer_locales: list[str] :ivar locale: @@ -1045,6 +1076,9 @@ class AzureStandardVoice(AzureVoice, discriminator="azure-standard"): temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Temperature must be between 0.0 and 1.0.""" custom_lexicon_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + custom_text_normalization_url: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) prefer_locales: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) locale: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) style: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -1059,6 +1093,7 @@ def __init__( name: str, temperature: Optional[float] = None, custom_lexicon_url: Optional[str] = None, + custom_text_normalization_url: Optional[str] = None, prefer_locales: Optional[list[str]] = None, locale: Optional[str] = None, style: Optional[str] = None, @@ -1114,6 +1149,99 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class FillerResponseConfigBase(_Model): + """Base model for filler response configuration. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LlmFillerResponseConfig, BasicFillerResponseConfig + + :ivar type: The type of filler response configuration. Required. Known values are: + "static_filler" and "llm_filler". + :vartype type: str or ~azure.ai.voicelive.models.FillerResponseConfigType + :ivar triggers: List of triggers that can fire the filler. Any trigger can activate the filler + (OR logic). + Supported: 'latency', 'tool'. + :vartype triggers: list[str or ~azure.ai.voicelive.models.FillerTrigger] + :ivar latency_threshold_ms: Latency threshold in milliseconds before triggering filler + response. Default is 2000ms. + :vartype latency_threshold_ms: int + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of filler response configuration. Required. Known values are: \"static_filler\" and + \"llm_filler\".""" + triggers: Optional[list[Union[str, "_models.FillerTrigger"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """List of triggers that can fire the filler. Any trigger can activate the filler (OR logic). + Supported: 'latency', 'tool'.""" + latency_threshold_ms: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Latency threshold in milliseconds before triggering filler response. Default is 2000ms.""" + + @overload + def __init__( + self, + *, + type: str, + triggers: Optional[list[Union[str, "_models.FillerTrigger"]]] = None, + latency_threshold_ms: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BasicFillerResponseConfig(FillerResponseConfigBase, discriminator="static_filler"): + """Configuration for basic/static filler response generation. + Randomly selects from configured texts when any trigger condition is met. + + :ivar triggers: List of triggers that can fire the filler. Any trigger can activate the filler + (OR logic). + Supported: 'latency', 'tool'. + :vartype triggers: list[str or ~azure.ai.voicelive.models.FillerTrigger] + :ivar latency_threshold_ms: Latency threshold in milliseconds before triggering filler + response. Default is 2000ms. + :vartype latency_threshold_ms: int + :ivar type: Required. Static filler configuration type. + :vartype type: str or ~azure.ai.voicelive.models.STATIC_FILLER + :ivar texts: List of filler text options to randomly select from. + :vartype texts: list[str] + """ + + type: Literal[FillerResponseConfigType.STATIC_FILLER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. Static filler configuration type.""" + texts: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """List of filler text options to randomly select from.""" + + @overload + def __init__( + self, + *, + triggers: Optional[list[Union[str, "_models.FillerTrigger"]]] = None, + latency_threshold_ms: Optional[int] = None, + texts: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = FillerResponseConfigType.STATIC_FILLER # type: ignore + + class CachedTokenDetails(_Model): """Details of output token usage. @@ -1942,6 +2070,117 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class Tool(_Model): + """The base representation of a voicelive tool definition. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + FoundryAgentTool, FunctionTool, MCPServer + + :ivar type: Required. Known values are: "function", "mcp", and "foundry_agent". + :vartype type: str or ~azure.ai.voicelive.models.ToolType + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """Required. Known values are: \"function\", \"mcp\", and \"foundry_agent\".""" + + @overload + def __init__( + self, + *, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FoundryAgentTool(Tool, discriminator="foundry_agent"): + """The definition of a Foundry agent tool as used by the voicelive endpoint. + + :ivar type: Required. + :vartype type: str or ~azure.ai.voicelive.models.FOUNDRY_AGENT + :ivar agent_name: The name of the Foundry agent to call. Required. + :vartype agent_name: str + :ivar agent_version: The version of the Foundry agent to call. + :vartype agent_version: str + :ivar project_name: The name of the Foundry project containing the agent. Required. + :vartype project_name: str + :ivar client_id: The client ID associated with the Foundry agent. + :vartype client_id: str + :ivar description: An optional description for the Foundry agent tool. If this is provided, it + will be used instead of the agent's description in foundry portal. + :vartype description: str + :ivar foundry_resource_override: An optional override for the Foundry resource used to execute + the agent. + :vartype foundry_resource_override: str + :ivar agent_context_type: The context type to use when invoking the Foundry agent. Defaults to + 'agent_context'. Known values are: "no_context" and "agent_context". + :vartype agent_context_type: str or ~azure.ai.voicelive.models.FoundryAgentContextType + :ivar return_agent_response_directly: Whether to return the agent's response directly in the + VoiceLive response. Set to false means to ask the voice live to rewrite the response. + :vartype return_agent_response_directly: bool + """ + + type: Literal[ToolType.FOUNDRY_AGENT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required.""" + agent_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the Foundry agent to call. Required.""" + agent_version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The version of the Foundry agent to call.""" + project_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the Foundry project containing the agent. Required.""" + client_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The client ID associated with the Foundry agent.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An optional description for the Foundry agent tool. If this is provided, it will be used + instead of the agent's description in foundry portal.""" + foundry_resource_override: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An optional override for the Foundry resource used to execute the agent.""" + agent_context_type: Optional[Union[str, "_models.FoundryAgentContextType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The context type to use when invoking the Foundry agent. Defaults to 'agent_context'. Known + values are: \"no_context\" and \"agent_context\".""" + return_agent_response_directly: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Whether to return the agent's response directly in the VoiceLive response. Set to false means + to ask the voice live to rewrite the response.""" + + @overload + def __init__( + self, + *, + agent_name: str, + project_name: str, + agent_version: Optional[str] = None, + client_id: Optional[str] = None, + description: Optional[str] = None, + foundry_resource_override: Optional[str] = None, + agent_context_type: Optional[Union[str, "_models.FoundryAgentContextType"]] = None, + return_agent_response_directly: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ToolType.FOUNDRY_AGENT # type: ignore + + class FunctionCallItem(ConversationRequestItem, discriminator="function_call"): """A function call item within a conversation. @@ -2043,38 +2282,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = ItemType.FUNCTION_CALL_OUTPUT # type: ignore -class Tool(_Model): - """The base representation of a voicelive tool definition. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - FunctionTool, MCPServer - - :ivar type: Required. Known values are: "function" and "mcp". - :vartype type: str or ~azure.ai.voicelive.models.ToolType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"function\" and \"mcp\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class FunctionTool(Tool, discriminator="function"): """The definition of a function tool as used by the voicelive endpoint. @@ -2308,6 +2515,60 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class LlmFillerResponseConfig(FillerResponseConfigBase, discriminator="llm_filler"): + """Configuration for LLM-based filler response generation. + Uses LLM to generate context-aware filler responses when any trigger condition is met. + + :ivar triggers: List of triggers that can fire the filler. Any trigger can activate the filler + (OR logic). + Supported: 'latency', 'tool'. + :vartype triggers: list[str or ~azure.ai.voicelive.models.FillerTrigger] + :ivar latency_threshold_ms: Latency threshold in milliseconds before triggering filler + response. Default is 2000ms. + :vartype latency_threshold_ms: int + :ivar type: Required. LLM-based filler configuration type. + :vartype type: str or ~azure.ai.voicelive.models.LLM_FILLER + :ivar model: The model to use for LLM-based filler generation. Default is gpt-4.1-mini. + :vartype model: str + :ivar instructions: Custom instructions for generating filler responses. If not provided, a + default prompt is used. + :vartype instructions: str + :ivar max_completion_tokens: Maximum number of tokens to generate for the filler response. + :vartype max_completion_tokens: int + """ + + type: Literal[FillerResponseConfigType.LLM_FILLER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. LLM-based filler configuration type.""" + model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The model to use for LLM-based filler generation. Default is gpt-4.1-mini.""" + instructions: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Custom instructions for generating filler responses. If not provided, a default prompt is used.""" + max_completion_tokens: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Maximum number of tokens to generate for the filler response.""" + + @overload + def __init__( + self, + *, + triggers: Optional[list[Union[str, "_models.FillerTrigger"]]] = None, + latency_threshold_ms: Optional[int] = None, + model: Optional[str] = None, + instructions: Optional[str] = None, + max_completion_tokens: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = FillerResponseConfigType.LLM_FILLER # type: ignore + + class LogProbProperties(_Model): """A single log probability entry for a token. @@ -2681,8 +2942,6 @@ class RequestSession(_Model): :vartype instructions: str :ivar input_audio_sampling_rate: Input audio sampling rate in Hz. Available values: - - * For pcm16: 8000, 16000, 24000 * For g711_alaw/g711_ulaw: 8000. @@ -2691,7 +2950,7 @@ class RequestSession(_Model): "g711_ulaw", and "g711_alaw". :vartype input_audio_format: str or ~azure.ai.voicelive.models.InputAudioFormat :ivar output_audio_format: Output audio format. Default is 'pcm16'. Known values are: "pcm16", - "pcm16-8000hz", "pcm16-16000hz", "g711_ulaw", and "g711_alaw". + "pcm16_8000hz", "pcm16_16000hz", "g711_ulaw", and "g711_alaw". :vartype output_audio_format: str or ~azure.ai.voicelive.models.OutputAudioFormat :ivar turn_detection: Type of turn detection to use. :vartype turn_detection: ~azure.ai.voicelive.models.TurnDetection @@ -2719,6 +2978,15 @@ class RequestSession(_Model): :ivar max_response_output_tokens: Maximum number of tokens to generate in the response. Default is unlimited. Is either a int type or a Literal["inf"] type. :vartype max_response_output_tokens: int or str + :ivar reasoning_effort: Constrains effort on reasoning for reasoning models. Check model + documentation for supported values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. Known values are: "none", "minimal", "low", "medium", "high", and "xhigh". + :vartype reasoning_effort: str or ~azure.ai.voicelive.models.ReasoningEffort + :ivar filler_response: Configuration for filler response generation during latency or tool + calls. Is either a BasicFillerResponseConfig type or a LlmFillerResponseConfig type. + :vartype filler_response: ~azure.ai.voicelive.models.BasicFillerResponseConfig or + ~azure.ai.voicelive.models.LlmFillerResponseConfig """ model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -2737,8 +3005,6 @@ class RequestSession(_Model): input_audio_sampling_rate: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Input audio sampling rate in Hz. Available values: - - * For pcm16: 8000, 16000, 24000 * For g711_alaw/g711_ulaw: 8000.""" @@ -2750,8 +3016,8 @@ class RequestSession(_Model): output_audio_format: Optional[Union[str, "_models.OutputAudioFormat"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """Output audio format. Default is 'pcm16'. Known values are: \"pcm16\", \"pcm16-8000hz\", - \"pcm16-16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" + """Output audio format. Default is 'pcm16'. Known values are: \"pcm16\", \"pcm16_8000hz\", + \"pcm16_16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" turn_detection: Optional["_models.TurnDetection"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -2786,6 +3052,19 @@ class RequestSession(_Model): ) """Maximum number of tokens to generate in the response. Default is unlimited. Is either a int type or a Literal[\"inf\"] type.""" + reasoning_effort: Optional[Union[str, "_models.ReasoningEffort"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Constrains effort on reasoning for reasoning models. Check model documentation for supported + values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. Known values are: \"none\", \"minimal\", \"low\", \"medium\", \"high\", and + \"xhigh\".""" + filler_response: Optional["_types.FillerResponseConfig"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Configuration for filler response generation during latency or tool calls. Is either a + BasicFillerResponseConfig type or a LlmFillerResponseConfig type.""" @overload def __init__( @@ -2809,6 +3088,8 @@ def __init__( tool_choice: Optional["_types.ToolChoice"] = None, temperature: Optional[float] = None, max_response_output_tokens: Optional[Union[int, Literal["inf"]]] = None, + reasoning_effort: Optional[Union[str, "_models.ReasoningEffort"]] = None, + filler_response: Optional["_types.FillerResponseConfig"] = None, ) -> None: ... @overload @@ -2895,7 +3176,7 @@ class Response(_Model): could be responding in either text or audio. :vartype modalities: list[str or ~azure.ai.voicelive.models.Modality] :ivar output_audio_format: The format of output audio. Options are ``pcm16``, ``g711_ulaw``, or - ``g711_alaw``. Known values are: "pcm16", "pcm16-8000hz", "pcm16-16000hz", "g711_ulaw", and + ``g711_alaw``. Known values are: "pcm16", "pcm16_8000hz", "pcm16_16000hz", "g711_ulaw", and "g711_alaw". :vartype output_audio_format: str or ~azure.ai.voicelive.models.OutputAudioFormat :ivar temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. @@ -2904,6 +3185,10 @@ class Response(_Model): inclusive of tool calls, that was used in this response. Is either a int type or a Literal["inf"] type. :vartype max_output_tokens: int or str + :ivar metadata: Set of up to 16 key-value pairs that can be attached to an object. + This can be useful for storing additional information about the object in a structured format. + Keys can be a maximum of 64 characters long and values can be a maximum of 512 characters long. + :vartype metadata: dict[str, str] """ id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -2953,7 +3238,7 @@ class Response(_Model): visibility=["read", "create", "update", "delete", "query"] ) """The format of output audio. Options are ``pcm16``, ``g711_ulaw``, or ``g711_alaw``. Known - values are: \"pcm16\", \"pcm16-8000hz\", \"pcm16-16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" + values are: \"pcm16\", \"pcm16_8000hz\", \"pcm16_16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" max_output_tokens: Optional[Union[int, Literal["inf"]]] = rest_field( @@ -2962,6 +3247,10 @@ class Response(_Model): """Maximum number of output tokens for a single assistant response, inclusive of tool calls, that was used in this response. Is either a int type or a Literal[\"inf\"] type.""" + metadata: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Set of up to 16 key-value pairs that can be attached to an object. + This can be useful for storing additional information about the object in a structured format. + Keys can be a maximum of 64 characters long and values can be a maximum of 512 characters long.""" @overload def __init__( @@ -2979,6 +3268,7 @@ def __init__( output_audio_format: Optional[Union[str, "_models.OutputAudioFormat"]] = None, temperature: Optional[float] = None, max_output_tokens: Optional[Union[int, Literal["inf"]]] = None, + metadata: Optional[dict[str, str]] = None, ) -> None: ... @overload @@ -3130,7 +3420,7 @@ class ResponseCreateParams(_Model): :vartype voice: str or ~azure.ai.voicelive.models.OpenAIVoiceName or ~azure.ai.voicelive.models.OpenAIVoice or ~azure.ai.voicelive.models.AzureVoice :ivar output_audio_format: The format of output audio. Options are ``pcm16``, ``g711_ulaw``, or - ``g711_alaw``. Known values are: "pcm16", "pcm16-8000hz", "pcm16-16000hz", "g711_ulaw", and + ``g711_alaw``. Known values are: "pcm16", "pcm16_8000hz", "pcm16_16000hz", "g711_ulaw", and "g711_alaw". :vartype output_audio_format: str or ~azure.ai.voicelive.models.OutputAudioFormat :ivar tools: Tools (functions) available to the model. @@ -3151,6 +3441,15 @@ class ResponseCreateParams(_Model): added into the conversation history and returned with synthesized audio output in the created response. :vartype pre_generated_assistant_message: ~azure.ai.voicelive.models.AssistantMessageItem + :ivar reasoning_effort: Constrains effort on reasoning for reasoning models. Check model + documentation for supported values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. Known values are: "none", "minimal", "low", "medium", "high", and "xhigh". + :vartype reasoning_effort: str or ~azure.ai.voicelive.models.ReasoningEffort + :ivar metadata: Set of up to 16 key-value pairs that can be attached to an object. + This can be useful for storing additional information about the object in a structured format. + Keys can be a maximum of 64 characters long and values can be a maximum of 512 characters long. + :vartype metadata: dict[str, str] """ commit: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -3191,7 +3490,7 @@ class ResponseCreateParams(_Model): visibility=["read", "create", "update", "delete", "query"] ) """The format of output audio. Options are ``pcm16``, ``g711_ulaw``, or ``g711_alaw``. Known - values are: \"pcm16\", \"pcm16-8000hz\", \"pcm16-16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" + values are: \"pcm16\", \"pcm16_8000hz\", \"pcm16_16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" tools: Optional[list["_models.Tool"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Tools (functions) available to the model.""" tool_choice: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -3213,6 +3512,18 @@ class ResponseCreateParams(_Model): """Create the response with pre-generated assistant message. The message item would be added into the conversation history and returned with synthesized audio output in the created response.""" + reasoning_effort: Optional[Union[str, "_models.ReasoningEffort"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Constrains effort on reasoning for reasoning models. Check model documentation for supported + values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. Known values are: \"none\", \"minimal\", \"low\", \"medium\", \"high\", and + \"xhigh\".""" + metadata: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Set of up to 16 key-value pairs that can be attached to an object. + This can be useful for storing additional information about the object in a structured format. + Keys can be a maximum of 64 characters long and values can be a maximum of 512 characters long.""" @overload def __init__( @@ -3231,6 +3542,8 @@ def __init__( temperature: Optional[float] = None, max_output_tokens: Optional[Union[int, Literal["inf"]]] = None, pre_generated_assistant_message: Optional["_models.AssistantMessageItem"] = None, + reasoning_effort: Optional[Union[str, "_models.ReasoningEffort"]] = None, + metadata: Optional[dict[str, str]] = None, ) -> None: ... @overload @@ -3281,12 +3594,13 @@ class ResponseItem(_Model): """Base for any response item; discriminated by ``type``. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ResponseFunctionCallItem, ResponseFunctionCallOutputItem, ResponseMCPApprovalRequestItem, - ResponseMCPApprovalResponseItem, ResponseMCPCallItem, ResponseMCPListToolItem, - ResponseMessageItem + ResponseFoundryAgentCallItem, ResponseFunctionCallItem, ResponseFunctionCallOutputItem, + ResponseMCPApprovalRequestItem, ResponseMCPApprovalResponseItem, ResponseMCPCallItem, + ResponseMCPListToolItem, ResponseMessageItem :ivar type: Required. Known values are: "message", "function_call", "function_call_output", - "mcp_list_tools", "mcp_call", "mcp_approval_request", and "mcp_approval_response". + "mcp_list_tools", "mcp_call", "mcp_approval_request", "mcp_approval_response", and + "foundry_agent_call". :vartype type: str or ~azure.ai.voicelive.models.ItemType :ivar id: :vartype id: str @@ -3297,7 +3611,8 @@ class ResponseItem(_Model): __mapping__: dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) """Required. Known values are: \"message\", \"function_call\", \"function_call_output\", - \"mcp_list_tools\", \"mcp_call\", \"mcp_approval_request\", and \"mcp_approval_response\".""" + \"mcp_list_tools\", \"mcp_call\", \"mcp_approval_request\", \"mcp_approval_response\", and + \"foundry_agent_call\".""" id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) object: Optional[Literal["realtime.item"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Default value is \"realtime.item\".""" @@ -3322,6 +3637,70 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class ResponseFoundryAgentCallItem(ResponseItem, discriminator="foundry_agent_call"): + """A response item that represents a call to a Foundry agent. + + :ivar id: + :vartype id: str + :ivar object: Default value is "realtime.item". + :vartype object: str + :ivar type: The type of the item. Required. + :vartype type: str or ~azure.ai.voicelive.models.FOUNDRY_AGENT_CALL + :ivar name: The name of the Foundry agent. Required. + :vartype name: str + :ivar call_id: The ID of the call. Required. + :vartype call_id: str + :ivar arguments: The arguments for the agent call. Required. + :vartype arguments: str + :ivar agent_response_id: The ID of the agent response, if any. + :vartype agent_response_id: str + :ivar output: The output of the agent call. + :vartype output: str + :ivar error: The error, if any, from the agent call. + :vartype error: any + """ + + type: Literal[ItemType.FOUNDRY_AGENT_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of the item. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the Foundry agent. Required.""" + call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the call. Required.""" + arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The arguments for the agent call. Required.""" + agent_response_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the agent response, if any.""" + output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The output of the agent call.""" + error: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error, if any, from the agent call.""" + + @overload + def __init__( + self, + *, + name: str, + call_id: str, + arguments: str, + id: Optional[str] = None, # pylint: disable=redefined-builtin + object: Optional[Literal["realtime.item"]] = None, + agent_response_id: Optional[str] = None, + output: Optional[str] = None, + error: Optional[Any] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ItemType.FOUNDRY_AGENT_CALL # type: ignore + + class ResponseFunctionCallItem(ResponseItem, discriminator="function_call"): """A function call item within a conversation. @@ -3733,8 +4112,6 @@ class ResponseSession(_Model): :vartype instructions: str :ivar input_audio_sampling_rate: Input audio sampling rate in Hz. Available values: - - * For pcm16: 8000, 16000, 24000 * For g711_alaw/g711_ulaw: 8000. @@ -3743,7 +4120,7 @@ class ResponseSession(_Model): "g711_ulaw", and "g711_alaw". :vartype input_audio_format: str or ~azure.ai.voicelive.models.InputAudioFormat :ivar output_audio_format: Output audio format. Default is 'pcm16'. Known values are: "pcm16", - "pcm16-8000hz", "pcm16-16000hz", "g711_ulaw", and "g711_alaw". + "pcm16_8000hz", "pcm16_16000hz", "g711_ulaw", and "g711_alaw". :vartype output_audio_format: str or ~azure.ai.voicelive.models.OutputAudioFormat :ivar turn_detection: Type of turn detection to use. :vartype turn_detection: ~azure.ai.voicelive.models.TurnDetection @@ -3771,6 +4148,15 @@ class ResponseSession(_Model): :ivar max_response_output_tokens: Maximum number of tokens to generate in the response. Default is unlimited. Is either a int type or a Literal["inf"] type. :vartype max_response_output_tokens: int or str + :ivar reasoning_effort: Constrains effort on reasoning for reasoning models. Check model + documentation for supported values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. Known values are: "none", "minimal", "low", "medium", "high", and "xhigh". + :vartype reasoning_effort: str or ~azure.ai.voicelive.models.ReasoningEffort + :ivar filler_response: Configuration for filler response generation during latency or tool + calls. Is either a BasicFillerResponseConfig type or a LlmFillerResponseConfig type. + :vartype filler_response: ~azure.ai.voicelive.models.BasicFillerResponseConfig or + ~azure.ai.voicelive.models.LlmFillerResponseConfig :ivar agent: The agent configuration for the session, if applicable. :vartype agent: ~azure.ai.voicelive.models.AgentConfig :ivar id: The unique identifier for the session. @@ -3793,8 +4179,6 @@ class ResponseSession(_Model): input_audio_sampling_rate: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Input audio sampling rate in Hz. Available values: - - * For pcm16: 8000, 16000, 24000 * For g711_alaw/g711_ulaw: 8000.""" @@ -3806,8 +4190,8 @@ class ResponseSession(_Model): output_audio_format: Optional[Union[str, "_models.OutputAudioFormat"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """Output audio format. Default is 'pcm16'. Known values are: \"pcm16\", \"pcm16-8000hz\", - \"pcm16-16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" + """Output audio format. Default is 'pcm16'. Known values are: \"pcm16\", \"pcm16_8000hz\", + \"pcm16_16000hz\", \"g711_ulaw\", and \"g711_alaw\".""" turn_detection: Optional["_models.TurnDetection"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -3842,6 +4226,19 @@ class ResponseSession(_Model): ) """Maximum number of tokens to generate in the response. Default is unlimited. Is either a int type or a Literal[\"inf\"] type.""" + reasoning_effort: Optional[Union[str, "_models.ReasoningEffort"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Constrains effort on reasoning for reasoning models. Check model documentation for supported + values for each model. + Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in + a response. Known values are: \"none\", \"minimal\", \"low\", \"medium\", \"high\", and + \"xhigh\".""" + filler_response: Optional["_types.FillerResponseConfig"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Configuration for filler response generation during latency or tool calls. Is either a + BasicFillerResponseConfig type or a LlmFillerResponseConfig type.""" agent: Optional["_models.AgentConfig"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The agent configuration for the session, if applicable.""" id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -3869,6 +4266,8 @@ def __init__( tool_choice: Optional["_types.ToolChoice"] = None, temperature: Optional[float] = None, max_response_output_tokens: Optional[Union[int, Literal["inf"]]] = None, + reasoning_effort: Optional[Union[str, "_models.ReasoningEffort"]] = None, + filler_response: Optional["_types.FillerResponseConfig"] = None, agent: Optional["_models.AgentConfig"] = None, id: Optional[str] = None, # pylint: disable=redefined-builtin ) -> None: ... @@ -3916,6 +4315,79 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = ContentPartType.TEXT # type: ignore +class Scene(_Model): + """Configuration for avatar's zoom level, position, rotation and movement amplitude in the video + frame. + + :ivar zoom: Zoom level of the avatar. Range is (0, +∞). Values less than 1 zoom out, values + greater than 1 zoom in. + :vartype zoom: float + :ivar position_x: Horizontal position of the avatar. Range is [-1, 1], as a proportion of frame + width. Negative values move left, positive values move right. + :vartype position_x: float + :ivar position_y: Vertical position of the avatar. Range is [-1, 1], as a proportion of frame + height. Negative values move up, positive values move down. + :vartype position_y: float + :ivar rotation_x: Rotation around the X-axis (pitch). Range is [-π, π] in radians. Negative + values rotate up, positive values rotate down. + :vartype rotation_x: float + :ivar rotation_y: Rotation around the Y-axis (yaw). Range is [-π, π] in radians. Negative + values rotate left, positive values rotate right. + :vartype rotation_y: float + :ivar rotation_z: Rotation around the Z-axis (roll). Range is [-π, π] in radians. Negative + values rotate anticlockwise, positive values rotate clockwise. + :vartype rotation_z: float + :ivar amplitude: Amplitude of the avatar movement. Range is (0, 1]. Values in (0, 1) mean + reduced amplitude, 1 means full amplitude. + :vartype amplitude: float + """ + + zoom: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Zoom level of the avatar. Range is (0, +∞). Values less than 1 zoom out, values greater than 1 + zoom in.""" + position_x: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Horizontal position of the avatar. Range is [-1, 1], as a proportion of frame width. Negative + values move left, positive values move right.""" + position_y: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Vertical position of the avatar. Range is [-1, 1], as a proportion of frame height. Negative + values move up, positive values move down.""" + rotation_x: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rotation around the X-axis (pitch). Range is [-π, π] in radians. Negative values rotate up, + positive values rotate down.""" + rotation_y: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rotation around the Y-axis (yaw). Range is [-π, π] in radians. Negative values rotate left, + positive values rotate right.""" + rotation_z: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rotation around the Z-axis (roll). Range is [-π, π] in radians. Negative values rotate + anticlockwise, positive values rotate clockwise.""" + amplitude: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Amplitude of the avatar movement. Range is (0, 1]. Values in (0, 1) mean reduced amplitude, 1 + means full amplitude.""" + + @overload + def __init__( + self, + *, + zoom: Optional[float] = None, + position_x: Optional[float] = None, + position_y: Optional[float] = None, + rotation_x: Optional[float] = None, + rotation_y: Optional[float] = None, + rotation_z: Optional[float] = None, + amplitude: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class ServerEvent(_Model): """A voicelive server event. @@ -3935,6 +4407,10 @@ class ServerEvent(_Model): ServerEventResponseAudioTranscriptDelta, ServerEventResponseAudioTranscriptDone, ServerEventResponseContentPartAdded, ServerEventResponseContentPartDone, ServerEventResponseCreated, ServerEventResponseDone, + ServerEventResponseFoundryAgentCallCompleted, ServerEventResponseFoundryAgentCallFailed, + ServerEventResponseFoundryAgentCallInProgress, + ServerEventResponseFoundryAgentCallArgumentsDelta, + ServerEventResponseFoundryAgentCallArgumentsDone, ServerEventResponseFunctionCallArgumentsDelta, ServerEventResponseFunctionCallArgumentsDone, ServerEventResponseMcpCallCompleted, ServerEventResponseMcpCallFailed, ServerEventResponseMcpCallInProgress, ServerEventResponseMcpCallArgumentsDelta, @@ -3960,7 +4436,10 @@ class ServerEvent(_Model): "response.function_call_arguments.done", "mcp_list_tools.in_progress", "mcp_list_tools.completed", "mcp_list_tools.failed", "response.mcp_call_arguments.delta", "response.mcp_call_arguments.done", "mcp_approval_request", "mcp_approval_response", - "response.mcp_call.in_progress", "response.mcp_call.completed", and "response.mcp_call.failed". + "response.mcp_call.in_progress", "response.mcp_call.completed", "response.mcp_call.failed", + "response.foundry_agent_call_arguments.delta", "response.foundry_agent_call_arguments.done", + "response.foundry_agent_call.in_progress", "response.foundry_agent_call.completed", and + "response.foundry_agent_call.failed". :vartype type: str or ~azure.ai.voicelive.models.ServerEventType :ivar event_id: :vartype event_id: str @@ -3968,8 +4447,8 @@ class ServerEvent(_Model): __mapping__: dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of event. Required. Known values are: \"error\", \"session.avatar.connecting\", - \"session.created\", \"session.updated\", + """The type of event. Required. Known values are: \"error\", + \"session.avatar.connecting\", \"session.created\", \"session.updated\", \"conversation.item.input_audio_transcription.completed\", \"conversation.item.input_audio_transcription.delta\", \"conversation.item.input_audio_transcription.failed\", \"conversation.item.created\", @@ -3987,8 +4466,10 @@ class ServerEvent(_Model): \"response.function_call_arguments.done\", \"mcp_list_tools.in_progress\", \"mcp_list_tools.completed\", \"mcp_list_tools.failed\", \"response.mcp_call_arguments.delta\", \"response.mcp_call_arguments.done\", \"mcp_approval_request\", \"mcp_approval_response\", - \"response.mcp_call.in_progress\", \"response.mcp_call.completed\", and - \"response.mcp_call.failed\".""" + \"response.mcp_call.in_progress\", \"response.mcp_call.completed\", + \"response.mcp_call.failed\", \"response.foundry_agent_call_arguments.delta\", + \"response.foundry_agent_call_arguments.done\", \"response.foundry_agent_call.in_progress\", + \"response.foundry_agent_call.completed\", and \"response.foundry_agent_call.failed\".""" event_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @overload @@ -5491,6 +5972,246 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = ServerEventType.RESPONSE_DONE # type: ignore +class ServerEventResponseFoundryAgentCallArgumentsDelta( + ServerEvent, discriminator="response.foundry_agent_call_arguments.delta" +): # pylint: disable=name-too-long + """Represents a delta update of the arguments for a Foundry agent call. + + :ivar event_id: + :vartype event_id: str + :ivar type: Required. + :vartype type: str or ~azure.ai.voicelive.models.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA + :ivar delta: The delta of the arguments. Required. + :vartype delta: str + :ivar item_id: The ID of the item associated with the event. Required. + :vartype item_id: str + :ivar response_id: The ID of the response associated with the event. Required. + :vartype response_id: str + :ivar output_index: The index of the output associated with the event. Required. + :vartype output_index: int + """ + + type: Literal[ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required.""" + delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The delta of the arguments. Required.""" + item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the item associated with the event. Required.""" + response_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the response associated with the event. Required.""" + output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The index of the output associated with the event. Required.""" + + @overload + def __init__( + self, + *, + delta: str, + item_id: str, + response_id: str, + output_index: int, + event_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA # type: ignore + + +class ServerEventResponseFoundryAgentCallArgumentsDone( + ServerEvent, discriminator="response.foundry_agent_call_arguments.done" +): # pylint: disable=name-too-long + """Indicates the completion of the arguments for a Foundry agent call. + + :ivar event_id: + :vartype event_id: str + :ivar type: Required. + :vartype type: str or ~azure.ai.voicelive.models.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE + :ivar item_id: The ID of the item associated with the event. Required. + :vartype item_id: str + :ivar response_id: The ID of the response associated with the event. Required. + :vartype response_id: str + :ivar output_index: The index of the output associated with the event. Required. + :vartype output_index: int + :ivar arguments: The full arguments for the agent call. + :vartype arguments: str + """ + + type: Literal[ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required.""" + item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the item associated with the event. Required.""" + response_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the response associated with the event. Required.""" + output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The index of the output associated with the event. Required.""" + arguments: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The full arguments for the agent call.""" + + @overload + def __init__( + self, + *, + item_id: str, + response_id: str, + output_index: int, + event_id: Optional[str] = None, + arguments: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE # type: ignore + + +class ServerEventResponseFoundryAgentCallCompleted( + ServerEvent, discriminator="response.foundry_agent_call.completed" +): # pylint: disable=name-too-long + """Indicates the Foundry agent call has completed. + + :ivar event_id: + :vartype event_id: str + :ivar type: Required. + :vartype type: str or ~azure.ai.voicelive.models.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED + :ivar item_id: The ID of the item associated with the event. Required. + :vartype item_id: str + :ivar output_index: The index of the output associated with the event. Required. + :vartype output_index: int + """ + + type: Literal[ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required.""" + item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the item associated with the event. Required.""" + output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The index of the output associated with the event. Required.""" + + @overload + def __init__( + self, + *, + item_id: str, + output_index: int, + event_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED # type: ignore + + +class ServerEventResponseFoundryAgentCallFailed( + ServerEvent, discriminator="response.foundry_agent_call.failed" +): # pylint: disable=name-too-long + """Indicates the Foundry agent call has failed. + + :ivar event_id: + :vartype event_id: str + :ivar type: Required. + :vartype type: str or ~azure.ai.voicelive.models.RESPONSE_FOUNDRY_AGENT_CALL_FAILED + :ivar item_id: The ID of the item associated with the event. Required. + :vartype item_id: str + :ivar output_index: The index of the output associated with the event. Required. + :vartype output_index: int + """ + + type: Literal[ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_FAILED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required.""" + item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the item associated with the event. Required.""" + output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The index of the output associated with the event. Required.""" + + @overload + def __init__( + self, + *, + item_id: str, + output_index: int, + event_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_FAILED # type: ignore + + +class ServerEventResponseFoundryAgentCallInProgress( + ServerEvent, discriminator="response.foundry_agent_call.in_progress" +): # pylint: disable=name-too-long + """Indicates the Foundry agent call is in progress. + + :ivar event_id: + :vartype event_id: str + :ivar type: Required. + :vartype type: str or ~azure.ai.voicelive.models.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS + :ivar item_id: The ID of the item associated with the event. Required. + :vartype item_id: str + :ivar output_index: The index of the output associated with the event. Required. + :vartype output_index: int + :ivar agent_response_id: The ID of the agent response, if any. + :vartype agent_response_id: str + """ + + type: Literal[ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required.""" + item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the item associated with the event. Required.""" + output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The index of the output associated with the event. Required.""" + agent_response_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the agent response, if any.""" + + @overload + def __init__( + self, + *, + item_id: str, + output_index: int, + event_id: Optional[str] = None, + agent_response_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS # type: ignore + + class ServerEventResponseFunctionCallArgumentsDelta( ServerEvent, discriminator="response.function_call_arguments.delta" ): # pylint: disable=name-too-long @@ -6320,13 +7041,13 @@ class ToolChoiceSelection(_Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: ToolChoiceFunctionSelection - :ivar type: Required. Known values are: "function" and "mcp". + :ivar type: Required. Known values are: "function", "mcp", and "foundry_agent". :vartype type: str or ~azure.ai.voicelive.models.ToolType """ __mapping__: dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"function\" and \"mcp\".""" + """Required. Known values are: \"function\", \"mcp\", and \"foundry_agent\".""" @overload def __init__( diff --git a/sdk/ai/azure-ai-voicelive/pyproject.toml b/sdk/ai/azure-ai-voicelive/pyproject.toml index a9e8a901bc41..5fdee2a8b6d1 100644 --- a/sdk/ai/azure-ai-voicelive/pyproject.toml +++ b/sdk/ai/azure-ai-voicelive/pyproject.toml @@ -32,7 +32,7 @@ keywords = ["azure", "azure sdk"] dependencies = [ "isodate>=0.6.1", - "azure-core>=1.36.0", + "azure-core>=1.37.0", "typing-extensions>=4.6.0", ] dynamic = [ diff --git a/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py b/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py index 4faf55a22a3b..4b804ef4e447 100644 --- a/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py +++ b/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py @@ -702,7 +702,7 @@ async def main(): """Main async function.""" # Get credentials from environment variables api_key = os.environ.get("AZURE_VOICELIVE_API_KEY") - endpoint = os.environ.get("AZURE_VOICELIVE_ENDPOINT", "wss://api.voicelive.com/v1") + endpoint = os.environ.get("AZURE_VOICELIVE_ENDPOINT", "https://test.voicelive.com/") if not api_key: print("❌ Error: No API key provided") diff --git a/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py b/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py index 775bc41e62d9..a9f120caf6d6 100644 --- a/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py +++ b/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py @@ -363,17 +363,18 @@ def __init__( self.audio_processor: Optional[AudioProcessor] = None self.session_ready: bool = False - async def run(self): """Run the async MCP call client with audio input.""" try: logger.info(f"Connecting to VoiceLive API with model {self.model}") # Connect to VoiceLive WebSocket API asynchronously + # Using 2026-01-01-preview API version for MCP support async with connect( endpoint=self.endpoint, credential=self.credential, model=self.model, + api_version="2026-01-01-preview", ) as connection: # Initialize audio processor self.audio_processor = AudioProcessor(connection) @@ -422,17 +423,14 @@ async def _setup_session(self, connection): MCPServer( server_label="deepwiki", server_url="https://mcp.deepwiki.com/mcp", - allowed_tools= [ - "read_wiki_structure", - "ask_question" - ], + allowed_tools=["read_wiki_structure", "ask_question"], require_approval="never", ), MCPServer( server_label="azure_doc", server_url="https://learn.microsoft.com/api/mcp", require_approval="always", - ) + ), ] # Create session configuration with MCP tools @@ -557,7 +555,9 @@ async def _handle_mcp_approval_request(self, conversation_created_event, connect logger.error("MCP approval item missing ID") return - logger.info(f"MCP Approval Request received: id={approval_id}, server_label={server_label}, function_name={function_name}, arguments={arguments}") + logger.info( + f"MCP Approval Request received: id={approval_id}, server_label={server_label}, function_name={function_name}, arguments={arguments}" + ) # wait for user input to approve or deny approval_response = False @@ -574,8 +574,7 @@ async def _handle_mcp_approval_request(self, conversation_created_event, connect # Send approval response approval_response_item = MCPApprovalResponseRequestItem( - approval_request_id=approval_id, - approve=approval_response + approval_request_id=approval_id, approve=approval_response ) await connection.conversation.item.create(item=approval_response_item) @@ -642,12 +641,13 @@ async def _handle_mcp_call_arguments(self, conversation_created_event, connectio logger.error(f"Error waiting for MCP call arguments done: {e}") return + async def main(): """Main async function.""" # Get credentials from environment variables api_key = os.environ.get("AZURE_VOICELIVE_API_KEY") - # important, PLEASE SET the features=mcp_preview:true in query params to enable mcp features - endpoint = os.environ.get("AZURE_VOICELIVE_ENDPOINT", "wss://api.voicelive.com/v1?features=mcp_preview:true") + # Note: Use api_version="2026-01-01-preview" to enable MCP features + endpoint = os.environ.get("AZURE_VOICELIVE_ENDPOINT", "https://test.voicelive.com/") if not api_key: print("❌ Error: No API key provided") @@ -668,7 +668,7 @@ async def main(): credential=credential, model="gpt-4o-realtime-preview", voice="en-US-AvaNeural", - instructions="You are a helpful AI assistant with access to some mcp server. " + instructions="You are a helpful AI assistant with access to some mcp server. ", ) # Setup signal handlers for graceful shutdown diff --git a/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py b/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py new file mode 100644 index 000000000000..9514cf835e63 --- /dev/null +++ b/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py @@ -0,0 +1,637 @@ +# pylint: disable=line-too-long,useless-suppression +#!/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. +# -------------------------------------------------------------------------- + +""" +FILE: supervisor_agent_sample.py + +DESCRIPTION: + This sample demonstrates how to use a supervisor agent powered by azure foundry in a voice live. + The Supervisor pattern is a common multi-agent architecture where a central AI agent acts as a coordinator, managing and delegating tasks to specialized supervisor agents. +""" + +import os +import sys +import asyncio +import logging +import base64 +import signal +import threading +import queue +from typing import Union, Optional, cast +from concurrent.futures import ThreadPoolExecutor + +# Audio processing imports +try: + import pyaudio +except ImportError: + print("This sample requires pyaudio. Install with: pip install pyaudio") + sys.exit(1) + +# Environment variable loading +try: + from dotenv import load_dotenv + + load_dotenv() +except ImportError: + print("Note: python-dotenv not installed. Using existing environment variables.") + +# Azure VoiceLive SDK imports +from azure.core.credentials import AzureKeyCredential +from azure.core.credentials_async import AsyncTokenCredential +from azure.ai.voicelive.aio import connect +from azure.ai.voicelive.models import ( + RequestSession, + ServerEventType, + ServerVad, + AudioEchoCancellation, + AzureStandardVoice, + Modality, + InputAudioFormat, + OutputAudioFormat, + FoundryAgentTool, + ToolChoiceLiteral, + AudioInputTranscriptionOptions, + ResponseFoundryAgentCallItem, +) + +# Set up logging +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") +logger = logging.getLogger(__name__) + +def _get_required_env(name: str) -> str: + """Get a required environment variable or exit with error.""" + value = os.environ.get(name) + if not value: + print(f"❌ Error: No {name} provided") + print(f"Please set the {name} environment variable.") + sys.exit(1) + return value + + +supervisor_agent_name = _get_required_env("SUPERVISOR_AGENT_NAME") +supervisor_agent_version = _get_required_env("SUPERVISOR_AGENT_VERSION") +supervisor_agent_project_name = _get_required_env("SUPERVISOR_AGENT_PROJECT_NAME") + +supervisor_agent_description = "You are a supervisor agent that determines the next response whenever the agent faces a non-trivial decision" + +chat_agent_instructions = f""" +You are a helpful agent. Your task is to maintain a natural conversation flow with the user. +By default, you must always use the {supervisor_agent_name} tool to get your next response, except when handling greetings (e.g., "hello", "hi there") or engaging in basic chitchat (e.g., "how are you?", "thank you"). +Before calling {supervisor_agent_name}, you MUST ALWAYS say something to the user (e.g., "Let me look into that.", "Just a second."). Never call {supervisor_agent_name} without first saying something to the user. +""" + +chat_agent_model = os.environ.get("CHAT_AGENT_MODEL", "gpt-realtime") + +chat_agent_voice = os.environ.get("CHAT_AGENT_VOICE", "en-US-AvaMultilingualNeural") + +class AudioProcessor: + """ + Handles real-time audio capture and playback for the voice assistant. + + This class manages bidirectional audio streaming: + - Captures audio input from the microphone using PyAudio + - Plays back audio output through speakers using PyAudio + - Uses separate threads for capture, sending, and playback to avoid blocking + - Uses queues to buffer audio data between threads for thread-safe communication + + Audio format: PCM16, 24kHz, mono + """ + + def __init__(self, connection): + self.connection = connection + self.audio = pyaudio.PyAudio() + + # Audio configuration - PCM16, 24kHz, mono as specified + self.format = pyaudio.paInt16 + self.channels = 1 + self.rate = 24000 + self.chunk_size = 1024 + + # Capture and playback state + self.is_capturing = False + self.is_playing = False + self.input_stream = None + self.output_stream = None + + # Audio queues and threading + self.audio_queue: "queue.Queue[bytes]" = queue.Queue() + self.audio_send_queue: "queue.Queue[str]" = queue.Queue() # base64 audio to send + self.executor = ThreadPoolExecutor(max_workers=3) + self.capture_thread: Optional[threading.Thread] = None + self.playback_thread: Optional[threading.Thread] = None + self.send_thread: Optional[threading.Thread] = None + self.loop: Optional[asyncio.AbstractEventLoop] = None # Store the event loop + + logger.info("AudioProcessor initialized with 24kHz PCM16 mono audio") + + async def start_capture(self): + """Start capturing audio from microphone.""" + if self.is_capturing: + return + + # Store the current event loop for use in threads + self.loop = asyncio.get_event_loop() + + self.is_capturing = True + + try: + self.input_stream = self.audio.open( + format=self.format, + channels=self.channels, + rate=self.rate, + input=True, + frames_per_buffer=self.chunk_size, + stream_callback=None, + ) + + self.input_stream.start_stream() + + # Start capture thread + self.capture_thread = threading.Thread(target=self._capture_audio_thread) + self.capture_thread.daemon = True + self.capture_thread.start() + + # Start audio send thread + self.send_thread = threading.Thread(target=self._send_audio_thread) + self.send_thread.daemon = True + self.send_thread.start() + + logger.info("Started audio capture") + + except Exception as e: + logger.error(f"Failed to start audio capture: {e}") + self.is_capturing = False + raise + + def _capture_audio_thread(self): + """Audio capture thread - runs in background.""" + while self.is_capturing and self.input_stream: + try: + # Read audio data + audio_data = self.input_stream.read(self.chunk_size, exception_on_overflow=False) + + if audio_data and self.is_capturing: + # Convert to base64 and queue for sending + audio_base64 = base64.b64encode(audio_data).decode("utf-8") + self.audio_send_queue.put(audio_base64) + + except Exception as e: + if self.is_capturing: + logger.error(f"Error in audio capture: {e}") + break + + def _send_audio_thread(self): + """Audio send thread - handles async operations from sync thread.""" + while self.is_capturing: + try: + # Get audio data from queue (blocking with timeout) + audio_base64 = self.audio_send_queue.get(timeout=0.1) + + if audio_base64 and self.is_capturing and self.loop: + # Schedule the async send operation in the main event loop + try: + future = asyncio.run_coroutine_threadsafe( + self.connection.input_audio_buffer.append(audio=audio_base64), self.loop + ) + # Wait briefly to catch any immediate errors + try: + future.result(timeout=0.05) + except TimeoutError: + pass # Expected - operation still running + except Exception as e: + if self.is_capturing: + logger.error(f"Error scheduling audio send: {e}") + + except queue.Empty: + continue + except Exception as e: + if self.is_capturing: + logger.error(f"Error in send audio thread: {e}") + break + logger.debug("Send audio thread exiting") + + async def stop_capture(self): + """Stop capturing audio.""" + if not self.is_capturing: + return + + self.is_capturing = False + + if self.input_stream: + self.input_stream.stop_stream() + self.input_stream.close() + self.input_stream = None + + if self.capture_thread: + self.capture_thread.join(timeout=1.0) + + if self.send_thread: + self.send_thread.join(timeout=1.0) + + # Clear the send queue + while not self.audio_send_queue.empty(): + try: + self.audio_send_queue.get_nowait() + except queue.Empty: + break + + logger.info("Stopped audio capture") + + async def start_playback(self): + """Initialize audio playback system.""" + if self.is_playing: + return + + self.is_playing = True + + try: + self.output_stream = self.audio.open( + format=self.format, + channels=self.channels, + rate=self.rate, + output=True, + frames_per_buffer=self.chunk_size, + ) + + # Start playback thread + self.playback_thread = threading.Thread(target=self._playback_audio_thread) + self.playback_thread.daemon = True + self.playback_thread.start() + + logger.info("Audio playback system ready") + + except Exception as e: + logger.error(f"Failed to initialize audio playback: {e}") + self.is_playing = False + raise + + def _playback_audio_thread(self): + """Audio playback thread - runs in background.""" + while self.is_playing: + try: + # Get audio data from queue (blocking with timeout) + audio_data = self.audio_queue.get(timeout=0.1) + + # Double-check state before writing to prevent race condition + if audio_data and self.is_playing: + stream = self.output_stream + if stream: + try: + stream.write(audio_data) + except OSError as e: + # Stream was closed, exit gracefully + if self.is_playing: + logger.debug(f"Stream write interrupted: {e}") + break + + except queue.Empty: + continue + except Exception as e: + if self.is_playing: + logger.error(f"Error in audio playback: {e}") + break + logger.debug("Playback thread exiting") + + async def queue_audio(self, audio_data: bytes): + """Queue audio data for playback.""" + if self.is_playing: + self.audio_queue.put(audio_data) + + async def stop_playback(self): + """Stop audio playback and clear queue.""" + if not self.is_playing: + return + + self.is_playing = False + + # Clear the queue to help thread exit faster + while not self.audio_queue.empty(): + try: + self.audio_queue.get_nowait() + except queue.Empty: + break + + # IMPORTANT: Join thread BEFORE closing stream to prevent race condition + # where thread tries to write after stream is closed + if self.playback_thread: + self.playback_thread.join(timeout=2.0) + self.playback_thread = None + + if self.output_stream: + try: + self.output_stream.stop_stream() + self.output_stream.close() + except Exception as e: + logger.warning(f"Error closing output stream: {e}") + finally: + self.output_stream = None + + logger.info("Stopped audio playback") + + async def cleanup(self): + """Clean up audio resources.""" + await self.stop_capture() + await self.stop_playback() + + if self.audio: + self.audio.terminate() + + self.executor.shutdown(wait=True) + logger.info("Audio processor cleaned up") + + +class AsyncSupervisorAgentClient: + """Async client for Azure Voice Live API with supervisor agent capabilities and audio input.""" + + def __init__( + self, + endpoint: str, + credential: Union[AzureKeyCredential, AsyncTokenCredential], + model: str, + voice: str, + instructions: str, + ): + self.endpoint = endpoint + self.credential = credential + self.model = model + self.voice = voice + self.instructions = instructions + self.session_id: Optional[str] = None + self.audio_processor: Optional[AudioProcessor] = None + self.session_ready: bool = False + + + async def run(self) -> None: + """Run the voice assistant with supervisor agent capabilities. + + Establishes WebSocket connection, configures the session, + and processes events until interrupted. + """ + try: + logger.info(f"Connecting to VoiceLive API with model {self.model}") + + # Connect to VoiceLive WebSocket API asynchronously + async with connect( + endpoint=self.endpoint, + credential=self.credential, + model=self.model, + api_version="2026-01-01-preview", + ) as connection: + # Initialize audio processor + self.audio_processor = AudioProcessor(connection) + + # Configure session with function tools + await self._setup_session(connection) + + # Start audio playback system + await self.audio_processor.start_playback() + + logger.info("Voice assistant with agent tools ready! Start speaking...") + print("\n" + "=" * 70) + print("🎤 VOICE ASSISTANT WITH SUPERVISOR AGENT READY") + print("Try saying:") + print(" • 'What production do you have?'") + print(" • 'What color do you have?'") + print("Press Ctrl+C to exit") + print("=" * 70 + "\n") + + # Process events asynchronously + await self._process_events(connection) + + except KeyboardInterrupt: + logger.info("Received interrupt signal, shutting down...") + except Exception as e: + logger.error(f"Connection error: {e}") + raise + finally: + # Cleanup audio processor + if self.audio_processor: + await self.audio_processor.cleanup() + + async def _setup_session(self, connection) -> None: + """Configure the VoiceLive session with supervisor agent capabilities.""" + logger.info("Setting up voice conversation session...") + + # Create voice configuration + voice_config = AzureStandardVoice(name=self.voice) + + # Create turn detection configuration + turn_detection_config = ServerVad(threshold=0.5, prefix_padding_ms=300, silence_duration_ms=500) + + # Define available foundry agent tools + foundry_agent_tools: list[FoundryAgentTool] = [ + FoundryAgentTool( + agent_name=supervisor_agent_name, + agent_version=supervisor_agent_version, + project_name=supervisor_agent_project_name, + description=supervisor_agent_description, + ) + ] + + # Create session configuration with foundry agent tools + session_config = RequestSession( + modalities=[Modality.TEXT, Modality.AUDIO], + instructions=self.instructions, + voice=voice_config, + input_audio_format=InputAudioFormat.PCM16, + output_audio_format=OutputAudioFormat.PCM16, + input_audio_echo_cancellation=AudioEchoCancellation(), + turn_detection=turn_detection_config, + tools=foundry_agent_tools, + tool_choice=ToolChoiceLiteral.AUTO, # Let the model decide when to call functions + input_audio_transcription=AudioInputTranscriptionOptions(model="whisper-1"), + ) + + # Send session configuration asynchronously + await connection.session.update(session=session_config) + logger.info("Session configuration with agent tools sent") + + async def _process_events(self, connection) -> None: + """Process events from the VoiceLive connection.""" + try: + async for event in connection: + await self._handle_event(event, connection) + except KeyboardInterrupt: + logger.info("Event processing interrupted") + except Exception as e: + logger.error(f"Error processing events: {e}") + raise + + async def _handle_event(self, event, connection) -> None: + """Handle different types of server events from VoiceLive.""" + ap = self.audio_processor + assert ap is not None, "AudioProcessor must be initialized" + + if event.type == ServerEventType.SESSION_UPDATED: + self.session_id = event.session.id + logger.info(f"Session ready: {self.session_id}") + self.session_ready = True + + # Start audio capture once session is ready + await ap.start_capture() + print("🎤 Ready for voice input! Try asking about zava productions...") + + elif event.type == ServerEventType.INPUT_AUDIO_BUFFER_SPEECH_STARTED: + logger.info("🎤 User started speaking - stopping playback") + print("🎤 Listening...") + + # Stop current assistant audio playback (interruption handling) + try: + await ap.stop_playback() + except Exception as e: + logger.error(f"Error stopping playback: {e}") + + elif event.type == ServerEventType.INPUT_AUDIO_BUFFER_SPEECH_STOPPED: + logger.info("🎤 User stopped speaking") + print("🤔 Processing...") + + # Restart playback system for response + try: + await ap.start_playback() + except Exception as e: + logger.error(f"Error starting playback: {e}") + + elif event.type == ServerEventType.RESPONSE_CREATED: + logger.info("🤖 Assistant response created") + + elif event.type == ServerEventType.RESPONSE_TEXT_DELTA: + logger.info(f"Text response: {event.delta}") + + elif event.type == ServerEventType.RESPONSE_AUDIO_DELTA: + # Stream audio response to speakers + logger.debug("Received audio delta") + await ap.queue_audio(event.delta) + + elif event.type == ServerEventType.RESPONSE_AUDIO_DONE: + logger.info("🤖 Assistant finished speaking") + print("🎤 Ready for next input...") + + elif event.type == ServerEventType.RESPONSE_DONE: + logger.info("✅ Response complete") + + elif event.type == ServerEventType.CONVERSATION_ITEM_CREATED: + if isinstance(event.item, ResponseFoundryAgentCallItem): + logger.info(f"🛠️ Foundry Agent Call initiated with tool: {event.item.name}") + + elif event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE: + logger.info(f"🛠️ Foundry Agent Call arguments: {event.arguments}") + + elif event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS: + if event.agent_response_id: + logger.info(f"🛠️ Foundry Agent Call in progress with response ID: {event.agent_response_id}") + + elif event.type == ServerEventType.RESPONSE_OUTPUT_ITEM_DONE: + if isinstance(event.item, ResponseFoundryAgentCallItem): + logger.info(f"🛠️ Foundry Agent Call completed with output: {event.item.output}") + + elif event.type == ServerEventType.ERROR: + logger.error(f"❌ VoiceLive error: {event.error.message}") + print(f"Error: {event.error.message}") + + +async def main() -> None: + """Main entry point for the supervisor agent sample.""" + # Get credentials from environment variables + api_key = os.environ.get("AZURE_VOICELIVE_API_KEY") + endpoint = os.environ.get("AZURE_VOICELIVE_ENDPOINT", "wss://api.voicelive.com/v1") + + if not api_key: + print("❌ Error: No AZURE_VOICELIVE_API_KEY provided") + print("Please set the AZURE_VOICELIVE_API_KEY environment variable.") + sys.exit(1) + + # Option 1: API key authentication (simple, recommended for quick start) + credential: Union[AzureKeyCredential, AsyncTokenCredential] = AzureKeyCredential(api_key) + + # Option 2: Async AAD authentication (requires azure-identity) + # Uncomment the lines below to use AAD authentication instead: + # from azure.identity.aio import AzureCliCredential, DefaultAzureCredential + # credential = AzureCliCredential() + + # Create and run the supervisor agent client + client = AsyncSupervisorAgentClient( + endpoint=endpoint, + credential=credential, + model=chat_agent_model, + voice=chat_agent_voice, + instructions=chat_agent_instructions, + ) + + # Setup signal handlers for graceful shutdown + def signal_handler(sig, frame): + logger.info("Received shutdown signal") + raise KeyboardInterrupt() + + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) + + try: + await client.run() + except KeyboardInterrupt: + print("\n👋 Supervisor Agent shut down.") + except Exception as e: + logger.error(f"Error: {e}") + sys.exit(1) + + +if __name__ == "__main__": + # Check for required dependencies + dependencies = { + "pyaudio": "Audio processing", + "azure.ai.voicelive": "Azure VoiceLive SDK", + "azure.core": "Azure Core libraries", + } + + missing_deps = [] + for dep, description in dependencies.items(): + try: + __import__(dep.replace("-", "_")) + except ImportError: + missing_deps.append(f"{dep} ({description})") + + if missing_deps: + print("❌ Missing required dependencies:") + for dep in missing_deps: + print(f" - {dep}") + print("\nInstall with: pip install azure-ai-voicelive pyaudio python-dotenv") + sys.exit(1) + + # Check audio system + try: + p = pyaudio.PyAudio() + # Check for input devices + input_devices = [ + i + for i in range(p.get_device_count()) + if cast(Union[int, float], p.get_device_info_by_index(i).get("maxInputChannels", 0) or 0) > 0 + ] + # Check for output devices + output_devices = [ + i + for i in range(p.get_device_count()) + if cast(Union[int, float], p.get_device_info_by_index(i).get("maxOutputChannels", 0) or 0) > 0 + ] + p.terminate() + + if not input_devices: + print("❌ No audio input devices found. Please check your microphone.") + sys.exit(1) + if not output_devices: + print("❌ No audio output devices found. Please check your speakers.") + sys.exit(1) + + except Exception as e: + print(f"❌ Audio system check failed: {e}") + sys.exit(1) + + print("🎙️ Voice Assistant with Supervisor Agent - Azure VoiceLive SDK") + print("=" * 65) + + # Run the async main function + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-voicelive/tests/test_live_realtime_service.py b/sdk/ai/azure-ai-voicelive/tests/test_live_realtime_service.py index e768a53e10a8..ff9ee1e40031 100644 --- a/sdk/ai/azure-ai-voicelive/tests/test_live_realtime_service.py +++ b/sdk/ai/azure-ai-voicelive/tests/test_live_realtime_service.py @@ -410,6 +410,7 @@ async def test_realtime_service_tool_call(self, test_data_dir: Path, model: str, await conn.session.update(session=session) await conn.input_audio_buffer.append(audio=_load_audio_b64(audio_file)) + await conn.response.create() timeout_s = 10 conversation_created_events = [] function_call_results = [] diff --git a/sdk/ai/azure-ai-voicelive/tests/test_unit_enums.py b/sdk/ai/azure-ai-voicelive/tests/test_unit_enums.py index a3f71871d674..d3341a18a3e7 100644 --- a/sdk/ai/azure-ai-voicelive/tests/test_unit_enums.py +++ b/sdk/ai/azure-ai-voicelive/tests/test_unit_enums.py @@ -199,8 +199,8 @@ class TestOutputAudioFormat: def test_pcm_formats(self): """Test PCM format values.""" assert OutputAudioFormat.PCM16 == "pcm16" - assert OutputAudioFormat.PCM16_8000_HZ == "pcm16-8000hz" - assert OutputAudioFormat.PCM16_16000_HZ == "pcm16-16000hz" + assert OutputAudioFormat.PCM16_8000_HZ == "pcm16_8000hz" + assert OutputAudioFormat.PCM16_16000_HZ == "pcm16_16000hz" def test_g711_formats(self): """Test G.711 format values.""" diff --git a/sdk/ai/azure-ai-voicelive/tests/test_unit_models_filler_foundry.py b/sdk/ai/azure-ai-voicelive/tests/test_unit_models_filler_foundry.py new file mode 100644 index 000000000000..7667ef28fd20 --- /dev/null +++ b/sdk/ai/azure-ai-voicelive/tests/test_unit_models_filler_foundry.py @@ -0,0 +1,669 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +""" +Unit tests for FillerResponseConfig and FoundryAgentTool models. +Tests the filler response feature and Foundry agent integration. +""" + +import pytest +from azure.ai.voicelive.models import ( + BasicFillerResponseConfig, + FillerResponseConfigType, + FillerTrigger, + FoundryAgentContextType, + FoundryAgentTool, + ItemType, + LlmFillerResponseConfig, + ReasoningEffort, + RequestSession, + Response, + ResponseCreateParams, + ResponseFoundryAgentCallItem, + ResponseSession, + ServerEventResponseFoundryAgentCallArgumentsDelta, + ServerEventResponseFoundryAgentCallArgumentsDone, + ServerEventResponseFoundryAgentCallCompleted, + ServerEventResponseFoundryAgentCallFailed, + ServerEventResponseFoundryAgentCallInProgress, + ServerEventType, + ToolType, +) + + +class TestBasicFillerResponseConfig: + """Test BasicFillerResponseConfig model.""" + + def test_basic_filler_minimal(self): + """Test BasicFillerResponseConfig with minimal parameters.""" + config = BasicFillerResponseConfig() + + assert config.type == FillerResponseConfigType.STATIC_FILLER + assert config.triggers is None + assert config.latency_threshold_ms is None + assert config.texts is None + + def test_basic_filler_with_texts(self): + """Test BasicFillerResponseConfig with filler texts.""" + texts = ["Hmm...", "Let me think...", "One moment..."] + config = BasicFillerResponseConfig(texts=texts) + + assert config.type == FillerResponseConfigType.STATIC_FILLER + assert config.texts == texts + assert len(config.texts) == 3 + + def test_basic_filler_with_triggers(self): + """Test BasicFillerResponseConfig with triggers.""" + config = BasicFillerResponseConfig( + triggers=[FillerTrigger.LATENCY, FillerTrigger.TOOL], latency_threshold_ms=2000, texts=["Please wait..."] + ) + + assert config.type == FillerResponseConfigType.STATIC_FILLER + assert FillerTrigger.LATENCY in config.triggers + assert FillerTrigger.TOOL in config.triggers + assert config.latency_threshold_ms == 2000 + + def test_basic_filler_string_triggers(self): + """Test BasicFillerResponseConfig with string triggers.""" + config = BasicFillerResponseConfig(triggers=["latency", "tool"]) + + assert config.triggers == ["latency", "tool"] + + +class TestLlmFillerResponseConfig: + """Test LlmFillerResponseConfig model.""" + + def test_llm_filler_minimal(self): + """Test LlmFillerResponseConfig with minimal parameters.""" + config = LlmFillerResponseConfig() + + assert config.type == FillerResponseConfigType.LLM_FILLER + assert config.model is None + assert config.instructions is None + assert config.max_completion_tokens is None + + def test_llm_filler_full(self): + """Test LlmFillerResponseConfig with all parameters.""" + config = LlmFillerResponseConfig( + triggers=[FillerTrigger.LATENCY], + latency_threshold_ms=1500, + model="gpt-4o-mini", + instructions="Generate brief filler responses.", + max_completion_tokens=50, + ) + + assert config.type == FillerResponseConfigType.LLM_FILLER + assert FillerTrigger.LATENCY in config.triggers + assert config.latency_threshold_ms == 1500 + assert config.model == "gpt-4o-mini" + assert config.max_completion_tokens == 50 + + def test_filler_config_type_discrimination(self): + """Test that filler config types are properly discriminated.""" + basic = BasicFillerResponseConfig(texts=["Wait..."]) + llm = LlmFillerResponseConfig(model="gpt-4o") + + assert basic.type != llm.type + assert basic.type == FillerResponseConfigType.STATIC_FILLER + assert llm.type == FillerResponseConfigType.LLM_FILLER + + +class TestFoundryAgentTool: + """Test FoundryAgentTool model.""" + + def test_foundry_agent_minimal(self): + """Test FoundryAgentTool with required parameters only.""" + tool = FoundryAgentTool(agent_name="my-agent", project_name="my-project") + + assert tool.type == ToolType.FOUNDRY_AGENT + assert tool.agent_name == "my-agent" + assert tool.project_name == "my-project" + assert tool.agent_version is None + + def test_foundry_agent_full(self): + """Test FoundryAgentTool with all parameters.""" + tool = FoundryAgentTool( + agent_name="my-agent", + project_name="my-project", + agent_version="v1.0", + client_id="client-123", + description="A helpful agent", + foundry_resource_override="https://custom.azure.com", + agent_context_type=FoundryAgentContextType.AGENT_CONTEXT, + return_agent_response_directly=True, + ) + + assert tool.agent_name == "my-agent" + assert tool.agent_version == "v1.0" + assert tool.client_id == "client-123" + assert tool.description == "A helpful agent" + assert tool.agent_context_type == FoundryAgentContextType.AGENT_CONTEXT + assert tool.return_agent_response_directly is True + + def test_foundry_agent_context_types(self): + """Test FoundryAgentTool with different context types.""" + no_context = FoundryAgentTool( + agent_name="a", project_name="p", agent_context_type=FoundryAgentContextType.NO_CONTEXT + ) + agent_context = FoundryAgentTool( + agent_name="a", project_name="p", agent_context_type=FoundryAgentContextType.AGENT_CONTEXT + ) + + assert no_context.agent_context_type == FoundryAgentContextType.NO_CONTEXT + assert agent_context.agent_context_type == FoundryAgentContextType.AGENT_CONTEXT + + +class TestResponseFoundryAgentCallItem: + """Test ResponseFoundryAgentCallItem model.""" + + def test_foundry_call_item_minimal(self): + """Test ResponseFoundryAgentCallItem with required fields.""" + item = ResponseFoundryAgentCallItem(name="my-agent", call_id="call-123", arguments='{"param": "value"}') + + assert item.type == ItemType.FOUNDRY_AGENT_CALL + assert item.name == "my-agent" + assert item.call_id == "call-123" + assert item.arguments == '{"param": "value"}' + + def test_foundry_call_item_with_output(self): + """Test ResponseFoundryAgentCallItem with output.""" + item = ResponseFoundryAgentCallItem( + name="my-agent", + call_id="call-123", + arguments="{}", + agent_response_id="resp-456", + output='{"result": "success"}', + ) + + assert item.agent_response_id == "resp-456" + assert item.output == '{"result": "success"}' + + def test_foundry_call_item_with_error(self): + """Test ResponseFoundryAgentCallItem with error.""" + error = {"code": "error", "message": "Failed"} + item = ResponseFoundryAgentCallItem(name="agent", call_id="call-1", arguments="{}", error=error) + + assert item.error == error + + +class TestFoundryAgentServerEvents: + """Test server events for Foundry agent calls.""" + + def test_arguments_delta_event(self): + """Test ServerEventResponseFoundryAgentCallArgumentsDelta.""" + event = ServerEventResponseFoundryAgentCallArgumentsDelta( + delta='{"p":', item_id="item-1", response_id="resp-1", output_index=0 + ) + + assert event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA + assert event.delta == '{"p":' + assert event.item_id == "item-1" + + def test_arguments_done_event(self): + """Test ServerEventResponseFoundryAgentCallArgumentsDone.""" + event = ServerEventResponseFoundryAgentCallArgumentsDone( + item_id="item-1", response_id="resp-1", output_index=0, arguments='{"param": "value"}' + ) + + assert event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE + assert event.arguments == '{"param": "value"}' + + def test_in_progress_event(self): + """Test ServerEventResponseFoundryAgentCallInProgress.""" + event = ServerEventResponseFoundryAgentCallInProgress( + item_id="item-1", output_index=0, agent_response_id="agent-resp-1" + ) + + assert event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS + assert event.agent_response_id == "agent-resp-1" + + def test_completed_event(self): + """Test ServerEventResponseFoundryAgentCallCompleted.""" + event = ServerEventResponseFoundryAgentCallCompleted(item_id="item-1", output_index=0) + + assert event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED + + def test_failed_event(self): + """Test ServerEventResponseFoundryAgentCallFailed.""" + event = ServerEventResponseFoundryAgentCallFailed(item_id="item-1", output_index=0) + + assert event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_FAILED + + +class TestReasoningEffort: + """Test ReasoningEffort enum and usage.""" + + def test_reasoning_effort_values(self): + """Test all ReasoningEffort enum values.""" + assert ReasoningEffort.NONE == "none" + assert ReasoningEffort.MINIMAL == "minimal" + assert ReasoningEffort.LOW == "low" + assert ReasoningEffort.MEDIUM == "medium" + assert ReasoningEffort.HIGH == "high" + assert ReasoningEffort.XHIGH == "xhigh" + + def test_reasoning_effort_in_request_session(self): + """Test using reasoning_effort in RequestSession.""" + session = RequestSession(model="o1-preview", reasoning_effort=ReasoningEffort.MEDIUM) + + assert session.reasoning_effort == ReasoningEffort.MEDIUM + + def test_reasoning_effort_in_response_params(self): + """Test using reasoning_effort in ResponseCreateParams.""" + params = ResponseCreateParams(reasoning_effort=ReasoningEffort.LOW) + + assert params.reasoning_effort == ReasoningEffort.LOW + + +class TestResponseMetadata: + """Test metadata field in Response models.""" + + def test_response_with_metadata(self): + """Test Response with metadata.""" + metadata = {"session": "abc", "user": "123"} + response = Response(id="resp-1", metadata=metadata) + + assert response.metadata == metadata + assert response.metadata["session"] == "abc" + + def test_response_create_params_with_metadata(self): + """Test ResponseCreateParams with metadata.""" + metadata = {"test": "value"} + params = ResponseCreateParams(metadata=metadata) + + assert params.metadata == metadata + + +class TestSessionWithFillerResponse: + """Test session models with filler_response field.""" + + def test_request_session_with_basic_filler(self): + """Test RequestSession with BasicFillerResponseConfig.""" + filler = BasicFillerResponseConfig(texts=["Hmm..."]) + session = RequestSession(model="gpt-4o-realtime-preview", filler_response=filler) + + assert session.filler_response is not None + assert session.filler_response.type == FillerResponseConfigType.STATIC_FILLER + + def test_request_session_with_llm_filler(self): + """Test RequestSession with LlmFillerResponseConfig.""" + filler = LlmFillerResponseConfig(model="gpt-4o-mini") + session = RequestSession(model="gpt-4o-realtime-preview", filler_response=filler) + + assert session.filler_response is not None + assert session.filler_response.type == FillerResponseConfigType.LLM_FILLER + + def test_response_session_with_filler(self): + """Test ResponseSession with filler_response.""" + filler = BasicFillerResponseConfig(texts=["Wait..."]) + session = ResponseSession(model="gpt-4o-realtime-preview", filler_response=filler) + + assert session.filler_response is not None + + +class TestNewEnums: + """Test new enum types.""" + + def test_filler_trigger_enum(self): + """Test FillerTrigger enum.""" + assert FillerTrigger.LATENCY == "latency" + assert FillerTrigger.TOOL == "tool" + + def test_filler_config_type_enum(self): + """Test FillerResponseConfigType enum.""" + assert FillerResponseConfigType.STATIC_FILLER == "static_filler" + assert FillerResponseConfigType.LLM_FILLER == "llm_filler" + + def test_foundry_context_type_enum(self): + """Test FoundryAgentContextType enum.""" + assert FoundryAgentContextType.NO_CONTEXT == "no_context" + assert FoundryAgentContextType.AGENT_CONTEXT == "agent_context" + + def test_tool_type_includes_foundry(self): + """Test ToolType includes FOUNDRY_AGENT.""" + assert ToolType.FOUNDRY_AGENT == "foundry_agent" + + def test_item_type_includes_foundry_call(self): + """Test ItemType includes FOUNDRY_AGENT_CALL.""" + assert ItemType.FOUNDRY_AGENT_CALL == "foundry_agent_call" + + +class TestIntegrationScenarios: + """Test integration scenarios with new features.""" + + def test_session_with_foundry_and_filler(self): + """Test complete session with Foundry agent and filler.""" + agent = FoundryAgentTool( + agent_name="support-agent", + project_name="support", + agent_context_type=FoundryAgentContextType.AGENT_CONTEXT, + ) + filler = LlmFillerResponseConfig(triggers=[FillerTrigger.LATENCY, FillerTrigger.TOOL], model="gpt-4o-mini") + session = RequestSession( + model="gpt-4o-realtime-preview", + tools=[agent], + reasoning_effort=ReasoningEffort.MEDIUM, + filler_response=filler, + ) + + assert len(session.tools) == 1 + assert session.tools[0].type == ToolType.FOUNDRY_AGENT + assert session.reasoning_effort == ReasoningEffort.MEDIUM + assert session.filler_response.type == FillerResponseConfigType.LLM_FILLER + + def test_mixed_tool_types(self): + """Test session with mixed tool types.""" + from azure.ai.voicelive.models import FunctionTool + + func = FunctionTool(name="func", description="test", parameters={}) + foundry = FoundryAgentTool(agent_name="agent", project_name="project") + session = RequestSession(model="gpt-4o-realtime-preview", tools=[func, foundry]) + + assert len(session.tools) == 2 + assert session.tools[0].type == ToolType.FUNCTION + assert session.tools[1].type == ToolType.FOUNDRY_AGENT + + +class TestSerialization: + """Test serialization and deserialization of new models.""" + + def test_basic_filler_serialization(self): + """Test BasicFillerResponseConfig serialization.""" + config = BasicFillerResponseConfig( + triggers=[FillerTrigger.LATENCY], latency_threshold_ms=2000, texts=["Wait...", "One moment..."] + ) + + # Serialize to dict + data = dict(config) + + assert data["type"] == "static_filler" + assert data["triggers"] == ["latency"] + assert data["latency_threshold_ms"] == 2000 + assert data["texts"] == ["Wait...", "One moment..."] + + def test_llm_filler_serialization(self): + """Test LlmFillerResponseConfig serialization.""" + config = LlmFillerResponseConfig( + triggers=[FillerTrigger.TOOL], model="gpt-4o-mini", instructions="Be brief", max_completion_tokens=50 + ) + + data = dict(config) + + assert data["type"] == "llm_filler" + assert data["model"] == "gpt-4o-mini" + assert data["instructions"] == "Be brief" + assert data["max_completion_tokens"] == 50 + + def test_foundry_tool_serialization(self): + """Test FoundryAgentTool serialization.""" + tool = FoundryAgentTool( + agent_name="my-agent", + project_name="my-project", + agent_version="v1.0", + client_id="client-123", + description="Test agent", + agent_context_type=FoundryAgentContextType.AGENT_CONTEXT, + return_agent_response_directly=True, + ) + + data = dict(tool) + + assert data["type"] == "foundry_agent" + assert data["agent_name"] == "my-agent" + assert data["project_name"] == "my-project" + assert data["agent_version"] == "v1.0" + assert data["agent_context_type"] == "agent_context" + assert data["return_agent_response_directly"] is True + + def test_foundry_call_item_serialization(self): + """Test ResponseFoundryAgentCallItem serialization.""" + item = ResponseFoundryAgentCallItem( + name="agent-1", + call_id="call-123", + arguments='{"param": "value"}', + output='{"result": "success"}', + agent_response_id="resp-456", + ) + + data = dict(item) + + assert data["type"] == "foundry_agent_call" + assert data["name"] == "agent-1" + assert data["call_id"] == "call-123" + assert data["arguments"] == '{"param": "value"}' + assert data["output"] == '{"result": "success"}' + + def test_foundry_event_serialization(self): + """Test Foundry server event serialization.""" + event = ServerEventResponseFoundryAgentCallArgumentsDelta( + delta='{"p":', item_id="item-1", response_id="resp-1", output_index=0, event_id="evt-123" + ) + + data = dict(event) + + assert data["type"] == "response.foundry_agent_call_arguments.delta" + assert data["delta"] == '{"p":' + assert data["item_id"] == "item-1" + + +class TestEdgeCases: + """Test edge cases and boundary conditions.""" + + def test_basic_filler_empty_texts(self): + """Test BasicFillerResponseConfig with empty texts list.""" + config = BasicFillerResponseConfig(texts=[]) + assert config.texts == [] + + def test_basic_filler_single_text(self): + """Test BasicFillerResponseConfig with single text.""" + config = BasicFillerResponseConfig(texts=["Only one"]) + assert len(config.texts) == 1 + + def test_llm_filler_zero_tokens(self): + """Test LlmFillerResponseConfig with zero max tokens.""" + config = LlmFillerResponseConfig(max_completion_tokens=0) + assert config.max_completion_tokens == 0 + + def test_foundry_tool_minimal_required_only(self): + """Test FoundryAgentTool with only required fields.""" + tool = FoundryAgentTool(agent_name="a", project_name="p") + + assert tool.agent_name == "a" + assert tool.project_name == "p" + assert tool.agent_version is None + assert tool.client_id is None + assert tool.description is None + + def test_foundry_call_item_empty_arguments(self): + """Test ResponseFoundryAgentCallItem with empty arguments.""" + item = ResponseFoundryAgentCallItem(name="agent", call_id="call-1", arguments="{}") + assert item.arguments == "{}" + + def test_multiple_filler_triggers(self): + """Test filler config with all trigger types.""" + config = BasicFillerResponseConfig(triggers=[FillerTrigger.LATENCY, FillerTrigger.TOOL]) + assert len(config.triggers) == 2 + assert FillerTrigger.LATENCY in config.triggers + assert FillerTrigger.TOOL in config.triggers + + +class TestValidation: + """Test model validation and constraints.""" + + def test_reasoning_effort_all_values(self): + """Test all ReasoningEffort enum values work in models.""" + efforts = [ + ReasoningEffort.NONE, + ReasoningEffort.MINIMAL, + ReasoningEffort.LOW, + ReasoningEffort.MEDIUM, + ReasoningEffort.HIGH, + ReasoningEffort.XHIGH, + ] + + for effort in efforts: + session = RequestSession(reasoning_effort=effort) + assert session.reasoning_effort == effort + + def test_metadata_max_keys(self): + """Test Response metadata with multiple keys.""" + metadata = {f"key{i}": f"value{i}" for i in range(16)} + response = Response(metadata=metadata) + + assert len(response.metadata) == 16 + + def test_metadata_long_values(self): + """Test Response metadata with long values.""" + long_value = "x" * 512 + metadata = {"key": long_value} + response = Response(metadata=metadata) + + assert response.metadata["key"] == long_value + + def test_foundry_context_type_string_values(self): + """Test FoundryAgentContextType with string values.""" + tool1 = FoundryAgentTool(agent_name="a", project_name="p", agent_context_type="no_context") + tool2 = FoundryAgentTool(agent_name="a", project_name="p", agent_context_type="agent_context") + + assert tool1.agent_context_type == "no_context" + assert tool2.agent_context_type == "agent_context" + + +class TestTypeUnions: + """Test union type handling for filler configs.""" + + def test_session_accepts_basic_filler(self): + """Test RequestSession accepts BasicFillerResponseConfig.""" + filler = BasicFillerResponseConfig(texts=["Wait"]) + session = RequestSession(filler_response=filler) + + assert isinstance(session.filler_response, BasicFillerResponseConfig) + + def test_session_accepts_llm_filler(self): + """Test RequestSession accepts LlmFillerResponseConfig.""" + filler = LlmFillerResponseConfig(model="gpt-4o") + session = RequestSession(filler_response=filler) + + assert isinstance(session.filler_response, LlmFillerResponseConfig) + + def test_response_session_filler_types(self): + """Test ResponseSession with different filler types.""" + basic = BasicFillerResponseConfig(texts=["Hmm"]) + llm = LlmFillerResponseConfig() + + session1 = ResponseSession(filler_response=basic) + session2 = ResponseSession(filler_response=llm) + + assert session1.filler_response.type == FillerResponseConfigType.STATIC_FILLER + assert session2.filler_response.type == FillerResponseConfigType.LLM_FILLER + + +class TestServerEventTypes: + """Test all Foundry agent server event types.""" + + def test_all_foundry_event_types_exist(self): + """Test that all Foundry agent event types are defined.""" + expected_types = [ + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA, + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE, + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS, + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED, + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_FAILED, + ] + + for event_type in expected_types: + assert event_type is not None + assert isinstance(event_type, str) + + def test_event_type_string_values(self): + """Test Foundry agent event type string values.""" + assert ( + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA == "response.foundry_agent_call_arguments.delta" + ) + assert ( + ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE == "response.foundry_agent_call_arguments.done" + ) + assert ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_IN_PROGRESS == "response.foundry_agent_call.in_progress" + assert ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED == "response.foundry_agent_call.completed" + assert ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_FAILED == "response.foundry_agent_call.failed" + + +class TestComplexScenarios: + """Test complex real-world scenarios.""" + + def test_complete_foundry_workflow(self): + """Test complete Foundry agent workflow with all components.""" + # Create tool + tool = FoundryAgentTool( + agent_name="support-bot", + project_name="customer-support", + agent_version="v2.0", + description="Customer support agent", + agent_context_type=FoundryAgentContextType.AGENT_CONTEXT, + return_agent_response_directly=False, + ) + + # Create session with tool + session = RequestSession(model="gpt-4o-realtime-preview", tools=[tool], reasoning_effort=ReasoningEffort.MEDIUM) + + # Create call item + call_item = ResponseFoundryAgentCallItem( + name="support-bot", + call_id="call-abc123", + arguments='{"query": "help with billing"}', + agent_response_id="resp-def456", + output='{"answer": "Here is billing help..."}', + ) + + # Create events + delta_event = ServerEventResponseFoundryAgentCallArgumentsDelta( + delta='{"query":', item_id="item-1", response_id="resp-1", output_index=0 + ) + + done_event = ServerEventResponseFoundryAgentCallArgumentsDone( + item_id="item-1", response_id="resp-1", output_index=0, arguments='{"query": "help with billing"}' + ) + + completed_event = ServerEventResponseFoundryAgentCallCompleted(item_id="item-1", output_index=0) + + # Verify all components + assert tool.type == ToolType.FOUNDRY_AGENT + assert session.tools[0].agent_name == "support-bot" + assert call_item.type == ItemType.FOUNDRY_AGENT_CALL + assert delta_event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DELTA + assert done_event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_ARGUMENTS_DONE + assert completed_event.type == ServerEventType.RESPONSE_FOUNDRY_AGENT_CALL_COMPLETED + + def test_session_with_all_new_features(self): + """Test session combining all new features.""" + # Foundry agent + agent = FoundryAgentTool(agent_name="multi-agent", project_name="enterprise") + + # Filler config + filler = LlmFillerResponseConfig( + triggers=[FillerTrigger.LATENCY, FillerTrigger.TOOL], + latency_threshold_ms=1500, + model="gpt-4o-mini", + max_completion_tokens=30, + ) + + # Create session with everything + session = RequestSession( + model="gpt-4o-realtime-preview", + tools=[agent], + reasoning_effort=ReasoningEffort.HIGH, + filler_response=filler, + ) + + # Verify all features present + assert session.tools[0].type == ToolType.FOUNDRY_AGENT + assert session.reasoning_effort == ReasoningEffort.HIGH + assert session.filler_response.type == FillerResponseConfigType.LLM_FILLER + assert session.filler_response.model == "gpt-4o-mini" + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/sdk/ai/azure-ai-voicelive/tests/test_unit_serialization.py b/sdk/ai/azure-ai-voicelive/tests/test_unit_serialization.py index 7ca27ecf45bf..cca0e0fdd415 100644 --- a/sdk/ai/azure-ai-voicelive/tests/test_unit_serialization.py +++ b/sdk/ai/azure-ai-voicelive/tests/test_unit_serialization.py @@ -335,3 +335,62 @@ def test_serializer_with_real_world_data(self): assert modalities_result == ["text", "audio"] assert formats_result == ["pcm16", "g711_ulaw"] + + +class TestSerializationSecurity: + """Test security improvements in serialization (removed eval usage).""" + + def test_serialize_basic_no_eval(self): + """Test that basic type serialization doesn't use eval().""" + from azure.ai.voicelive._utils.serialization import Serializer + + serializer = Serializer() + + # These should work without eval + assert serializer.serialize_basic("test", "str") == "test" + assert serializer.serialize_basic(42, "int") == 42 + assert serializer.serialize_basic(3.14, "float") == 3.14 + assert serializer.serialize_basic(True, "bool") is True + + def test_serialize_basic_invalid_type_raises_error(self): + """Test that invalid data types raise TypeError instead of eval error.""" + from azure.ai.voicelive._utils.serialization import Serializer + + serializer = Serializer() + + # Should raise TypeError for unsupported types, not execute arbitrary code + with pytest.raises(TypeError, match="Unknown basic data type"): + serializer.serialize_basic("test", "malicious_code") + + def test_deserialize_basic_no_eval(self): + """Test that basic type deserialization doesn't use eval().""" + from azure.ai.voicelive._utils.serialization import Deserializer + + deserializer = Deserializer() + + # These should work without eval + assert deserializer.deserialize_basic("test", "str") == "test" + assert deserializer.deserialize_basic("42", "int") == 42 + assert deserializer.deserialize_basic("3.14", "float") == 3.14 + + def test_deserialize_basic_invalid_type_raises_error(self): + """Test that invalid data types raise TypeError in deserialization.""" + from azure.ai.voicelive._utils.serialization import Deserializer + + deserializer = Deserializer() + + # Should raise TypeError for unsupported types + with pytest.raises(TypeError, match="Unknown basic data type"): + deserializer.deserialize_basic("test", "unknown_type") + + def test_security_bool_serialization(self): + """Test that bool serialization works correctly without eval.""" + from azure.ai.voicelive._utils.serialization import Serializer + + serializer = Serializer() + + # Test bool specifically as it was changed from eval(data_type)(data) + assert serializer.serialize_basic(True, "bool") is True + assert serializer.serialize_basic(False, "bool") is False + assert serializer.serialize_basic(1, "bool") is True # Truthy value + assert serializer.serialize_basic(0, "bool") is False # Falsy value From e7b5fa81aa188011fb4323382d1a32b32f54d55b Mon Sep 17 00:00:00 2001 From: M-Hietala <78813398+M-Hietala@users.noreply.github.com> Date: Fri, 30 Jan 2026 13:17:26 -0600 Subject: [PATCH 14/84] updating response generation span names (#44926) * updating response generation span names * change to rerun ci --- sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + .../telemetry/_responses_instrumentor.py | 12 +-- .../azure/ai/projects/telemetry/_utils.py | 4 + .../telemetry/test_responses_instrumentor.py | 77 ++++++++++--------- .../test_responses_instrumentor_async.py | 69 +++++++++-------- ...sponses_instrumentor_browser_automation.py | 9 ++- ...s_instrumentor_browser_automation_async.py | 9 ++- ...responses_instrumentor_code_interpreter.py | 9 ++- ...ses_instrumentor_code_interpreter_async.py | 9 ++- ...test_responses_instrumentor_file_search.py | 9 ++- ...esponses_instrumentor_file_search_async.py | 9 ++- .../test_responses_instrumentor_mcp.py | 11 +-- .../test_responses_instrumentor_mcp_async.py | 9 ++- .../test_responses_instrumentor_workflow.py | 9 ++- ...t_responses_instrumentor_workflow_async.py | 9 ++- 15 files changed, 137 insertions(+), 118 deletions(-) diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 034b155b7702..0cac8cb15095 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -22,6 +22,7 @@ * Rename class `SharepointAgentTool` to `SharepointPreviewTool`. * Rename class `ItemParam` to `InputItem`. * Tracing: workflow actions in conversation item listings are now emitted as "gen_ai.conversation.item" events (with role="workflow") instead of "gen_ai.workflow.action" events in the list_conversation_items span. +* Tracing: response generation span names changed from "responses {model_name}" to "chat {model_name}" for model calls and from "responses {agent_name}" to "invoke_agent {agent_name}" for agent calls. ## 2.0.0b3 (2026-01-06) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py index 904f714fd7ae..37a14d1f682b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py @@ -51,6 +51,8 @@ OperationName, SERVER_ADDRESS, SERVER_PORT, + SPAN_NAME_CHAT, + SPAN_NAME_INVOKE_AGENT, start_span, ) @@ -1481,11 +1483,11 @@ def start_responses_span( tools: Optional[List[Dict[str, Any]]] = None, ) -> "Optional[AbstractSpan]": """Start a span for responses API call.""" - # Build span name: prefer model, then assistant name, then just operation - if model: - span_name = f"{OperationName.RESPONSES.value} {model}" - elif assistant_name: - span_name = f"{OperationName.RESPONSES.value} {assistant_name}" + # Build span name: agent case uses "invoke_agent", non-agent case uses "chat" + if assistant_name: + span_name = f"{SPAN_NAME_INVOKE_AGENT} {assistant_name}" + elif model: + span_name = f"{SPAN_NAME_CHAT} {model}" else: span_name = OperationName.RESPONSES.value diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py index 03da5580ebfa..050268a6e133 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py @@ -103,6 +103,10 @@ AGENT_TYPE_HOSTED = "hosted" AGENT_TYPE_UNKNOWN = "unknown" +# Span name prefixes for responses API operations +SPAN_NAME_INVOKE_AGENT = "invoke_agent" +SPAN_NAME_CHAT = "chat" + class OperationName(Enum): CREATE_AGENT = "create_agent" diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py index 66fb4fb0972a..8bf3b5077780 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py @@ -9,6 +9,7 @@ import pytest from typing import Optional, Tuple from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_CHAT, SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from openai import OpenAI @@ -224,7 +225,7 @@ def test_sync_non_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -304,7 +305,7 @@ def test_sync_non_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -394,7 +395,7 @@ def test_sync_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -700,7 +701,7 @@ def test_sync_non_streaming_without_conversation(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -833,7 +834,7 @@ def test_sync_function_tool_with_content_recording_non_streaming(self, **kwargs) # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2 # Validate first span (user message + tool call) @@ -1029,7 +1030,7 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2 # Validate first span (user message + tool call) @@ -1201,7 +1202,7 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2 # Validate first span (user message + tool call) - no content @@ -1391,7 +1392,7 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2 # Validate first span (user message + tool call) - no content @@ -1816,7 +1817,7 @@ def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, ** # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1920,7 +1921,7 @@ def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwar # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2016,7 +2017,7 @@ def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2115,7 +2116,7 @@ def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **k # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2209,7 +2210,7 @@ def test_image_only_content_off_binary_off_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2278,7 +2279,7 @@ def test_image_only_content_off_binary_on_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2347,7 +2348,7 @@ def test_image_only_content_on_binary_off_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2416,7 +2417,7 @@ def test_image_only_content_on_binary_on_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2494,7 +2495,7 @@ def test_text_and_image_content_off_binary_off_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2567,7 +2568,7 @@ def test_text_and_image_content_off_binary_on_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2640,7 +2641,7 @@ def test_text_and_image_content_on_binary_off_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2713,7 +2714,7 @@ def test_text_and_image_content_on_binary_on_non_streaming(self, **kwargs): assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2795,7 +2796,7 @@ def test_image_only_content_off_binary_off_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2872,7 +2873,7 @@ def test_image_only_content_off_binary_on_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2949,7 +2950,7 @@ def test_image_only_content_on_binary_off_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3026,7 +3027,7 @@ def test_image_only_content_on_binary_on_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3111,7 +3112,7 @@ def test_text_and_image_content_off_binary_off_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3192,7 +3193,7 @@ def test_text_and_image_content_off_binary_on_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3273,7 +3274,7 @@ def test_text_and_image_content_on_binary_off_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3354,7 +3355,7 @@ def test_text_and_image_content_on_binary_on_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3415,7 +3416,7 @@ def test_responses_stream_method_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3488,7 +3489,7 @@ def test_responses_stream_method_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -3612,7 +3613,7 @@ def test_responses_stream_method_with_tools_with_content_recording(self, **kwarg # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 2 # Validate first span (user message + tool call) @@ -3766,7 +3767,7 @@ def test_responses_stream_method_with_tools_without_content_recording(self, **kw # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 2 # Validate first span - should have events with tool call structure but no details @@ -3967,7 +3968,7 @@ def test_workflow_agent_non_streaming_with_content_recording(self, **kwargs): # Verify workflow action events self.exporter.force_flush() # Workflow agents use agent name in span, not deployment name - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -4078,7 +4079,7 @@ def test_workflow_agent_non_streaming_without_content_recording(self, **kwargs): # Verify workflow action events (content recording off) self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -4287,7 +4288,7 @@ def test_workflow_agent_streaming_with_content_recording(self, **kwargs): # Verify workflow action events in streaming mode self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -4403,7 +4404,7 @@ def test_workflow_agent_streaming_without_content_recording(self, **kwargs): # Verify workflow action events (content recording off) self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -4508,7 +4509,7 @@ def test_prompt_agent_with_responses_non_streaming(self, **kwargs): # Verify traces contain agent name and id self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) >= 1 # Validate span attributes @@ -4585,7 +4586,7 @@ def test_prompt_agent_with_responses_streaming(self, **kwargs): # Verify traces contain agent name and id self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) >= 1 # Validate span attributes diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py index 461abae0ce90..171ac7cc53dc 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py @@ -8,6 +8,7 @@ import json import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_CHAT, SPAN_NAME_INVOKE_AGENT from azure.ai.projects.models import FunctionTool, PromptAgentDefinition from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier @@ -71,7 +72,7 @@ async def test_async_non_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -161,7 +162,7 @@ async def test_async_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -447,7 +448,7 @@ async def test_async_function_tool_with_content_recording_streaming(self, **kwar # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2 # Validate first span (user message + tool call) @@ -639,7 +640,7 @@ async def test_async_function_tool_without_content_recording_streaming(self, **k # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2 # Validate first span (user message + tool call) - no content @@ -766,7 +767,7 @@ async def test_async_multiple_text_inputs_with_content_recording_non_streaming(s # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -870,7 +871,7 @@ async def test_async_multiple_text_inputs_with_content_recording_streaming(self, # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -966,7 +967,7 @@ async def test_async_multiple_text_inputs_without_content_recording_non_streamin # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1065,7 +1066,7 @@ async def test_async_image_only_content_off_binary_off_non_streaming(self, **kwa assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1135,7 +1136,7 @@ async def test_async_image_only_content_off_binary_on_non_streaming(self, **kwar assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1205,7 +1206,7 @@ async def test_async_image_only_content_on_binary_off_non_streaming(self, **kwar assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1275,7 +1276,7 @@ async def test_async_image_only_content_on_binary_on_non_streaming(self, **kwarg assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1354,7 +1355,7 @@ async def test_async_text_and_image_content_off_binary_off_non_streaming(self, * assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1428,7 +1429,7 @@ async def test_async_text_and_image_content_off_binary_on_non_streaming(self, ** assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1502,7 +1503,7 @@ async def test_async_text_and_image_content_on_binary_off_non_streaming(self, ** assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1576,7 +1577,7 @@ async def test_async_text_and_image_content_on_binary_on_non_streaming(self, **k assert result.output is not None self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1659,7 +1660,7 @@ async def test_async_image_only_content_off_binary_off_streaming(self, **kwargs) assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1737,7 +1738,7 @@ async def test_async_image_only_content_off_binary_on_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1815,7 +1816,7 @@ async def test_async_image_only_content_on_binary_off_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1893,7 +1894,7 @@ async def test_async_image_only_content_on_binary_on_streaming(self, **kwargs): assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -1979,7 +1980,7 @@ async def test_async_text_and_image_content_off_binary_off_streaming(self, **kwa assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2061,7 +2062,7 @@ async def test_async_text_and_image_content_off_binary_on_streaming(self, **kwar assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2143,7 +2144,7 @@ async def test_async_text_and_image_content_on_binary_off_streaming(self, **kwar assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2225,7 +2226,7 @@ async def test_async_text_and_image_content_on_binary_on_streaming(self, **kwarg assert len(full_content) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2305,7 +2306,7 @@ async def test_async_multiple_text_inputs_without_content_recording_streaming(se # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2397,7 +2398,7 @@ async def test_async_responses_stream_method_with_content_recording(self, **kwar # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2477,7 +2478,7 @@ async def test_async_responses_stream_method_without_content_recording(self, **k # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 1 span = spans[0] @@ -2608,7 +2609,7 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 2 # Validate first span (user message + tool call) @@ -2762,7 +2763,7 @@ async def test_async_responses_stream_method_with_tools_without_content_recordin # Check spans - should have 2 responses spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {deployment_name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 2 # Validate first span - should have events with tool call structure but no details @@ -2877,7 +2878,7 @@ async def test_async_workflow_agent_non_streaming_with_content_recording(self, * # Verify workflow action events self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -2993,7 +2994,7 @@ async def test_async_workflow_agent_non_streaming_without_content_recording(self # Verify workflow action events (content recording off) self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -3121,7 +3122,7 @@ async def test_async_workflow_agent_streaming_with_content_recording(self, **kwa # Verify workflow action events in streaming mode self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -3242,7 +3243,7 @@ async def test_async_workflow_agent_streaming_without_content_recording(self, ** # Verify workflow action events (content recording off) self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow_agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow_agent.name}") assert len(spans) >= 1 span = spans[0] @@ -3353,7 +3354,7 @@ async def test_async_prompt_agent_with_responses_non_streaming(self, **kwargs): # Verify traces contain agent name and id self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) >= 1 # Validate span attributes @@ -3432,7 +3433,7 @@ async def test_async_prompt_agent_with_responses_streaming(self, **kwargs): # Verify traces contain agent name and id self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) >= 1 # Validate span attributes diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py index b17e6d197a0c..5dbcb4566c87 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py @@ -9,6 +9,7 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -98,7 +99,7 @@ def test_sync_browser_automation_non_streaming_with_content_recording(self, **kw assert len(response.output) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] @@ -229,7 +230,7 @@ def test_sync_browser_automation_non_streaming_without_content_recording(self, * ) self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] @@ -353,7 +354,7 @@ def test_sync_browser_automation_streaming_with_content_recording(self, **kwargs pass self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] @@ -478,7 +479,7 @@ def test_sync_browser_automation_streaming_without_content_recording(self, **kwa pass self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py index ec677693213d..0631495ff0b2 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py @@ -9,6 +9,7 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -101,7 +102,7 @@ async def test_async_browser_automation_non_streaming_with_content_recording(sel assert len(response.output) > 0 self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] @@ -228,7 +229,7 @@ async def test_async_browser_automation_non_streaming_without_content_recording( ) self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] @@ -348,7 +349,7 @@ async def test_async_browser_automation_streaming_with_content_recording(self, * pass self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] @@ -470,7 +471,7 @@ async def test_async_browser_automation_streaming_without_content_recording(self pass self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1 span = spans[0] diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py index e51478a6f554..13b0d8342186 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py @@ -10,6 +10,7 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -106,7 +107,7 @@ def test_sync_code_interpreter_non_streaming_with_content_recording(self, **kwar # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -292,7 +293,7 @@ def test_sync_code_interpreter_non_streaming_without_content_recording(self, **k # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -487,7 +488,7 @@ def test_sync_code_interpreter_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -677,7 +678,7 @@ def test_sync_code_interpreter_streaming_without_content_recording(self, **kwarg # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py index 7b73aeeabec0..5f2eb03e3fbe 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py @@ -10,6 +10,7 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -106,7 +107,7 @@ async def test_async_code_interpreter_non_streaming_with_content_recording(self, # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -292,7 +293,7 @@ async def test_async_code_interpreter_non_streaming_without_content_recording(se # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -487,7 +488,7 @@ async def test_async_code_interpreter_streaming_with_content_recording(self, **k # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -677,7 +678,7 @@ async def test_async_code_interpreter_streaming_without_content_recording(self, # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py index 5b01b733586c..92902d6fa908 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py @@ -10,6 +10,7 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -110,7 +111,7 @@ def test_sync_file_search_non_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -318,7 +319,7 @@ def test_sync_file_search_non_streaming_without_content_recording(self, **kwargs # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -526,7 +527,7 @@ def test_sync_file_search_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -730,7 +731,7 @@ def test_sync_file_search_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py index ca5a4abd872b..f215ee1072f2 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py @@ -10,6 +10,7 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -111,7 +112,7 @@ async def test_async_file_search_non_streaming_with_content_recording(self, **kw # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -319,7 +320,7 @@ async def test_async_file_search_non_streaming_without_content_recording(self, * # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -527,7 +528,7 @@ async def test_async_file_search_streaming_with_content_recording(self, **kwargs # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span @@ -731,7 +732,7 @@ async def test_async_file_search_streaming_without_content_recording(self, **kwa # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 1, "Should have one response span" # Validate response span diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py index 9c47dfab727f..9152d4b244f2 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py @@ -9,6 +9,7 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -108,11 +109,11 @@ def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): # Explicitly call and iterate through conversation items items = openai_client.conversations.items.list(conversation_id=conversation.id) for item in items: - pass # Just iterate to consume items + pass # Iterate to consume items # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span (MCP tool trigger) @@ -400,7 +401,7 @@ def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span (MCP tool trigger) @@ -683,7 +684,7 @@ def test_sync_mcp_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span @@ -922,7 +923,7 @@ def test_sync_mcp_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py index a5161456ed70..c0fd327890da 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py @@ -9,6 +9,7 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -113,7 +114,7 @@ async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span (MCP tool trigger) @@ -401,7 +402,7 @@ async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs) # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span (MCP tool trigger) @@ -684,7 +685,7 @@ async def test_async_mcp_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span @@ -923,7 +924,7 @@ async def test_async_mcp_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {agent.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {agent.name}") assert len(spans) == 2, "Should have two response spans (initial + approval)" # Validate first response span diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py index e4b5e0c40a94..dca9a911fd75 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py @@ -9,6 +9,7 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -256,7 +257,7 @@ def test_sync_workflow_non_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] @@ -417,7 +418,7 @@ def test_sync_workflow_non_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] @@ -583,7 +584,7 @@ def test_sync_workflow_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] @@ -750,7 +751,7 @@ def test_sync_workflow_streaming_without_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py index 22d5580bdd09..fcb55113a0eb 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py @@ -9,6 +9,7 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils +from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -252,7 +253,7 @@ async def test_async_workflow_non_streaming_with_content_recording(self, **kwarg # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] @@ -412,7 +413,7 @@ async def test_async_workflow_non_streaming_without_content_recording(self, **kw # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] @@ -576,7 +577,7 @@ async def test_async_workflow_streaming_with_content_recording(self, **kwargs): # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] @@ -741,7 +742,7 @@ async def test_async_workflow_streaming_without_content_recording(self, **kwargs # Check spans self.exporter.force_flush() - spans = self.exporter.get_spans_by_name(f"responses {workflow.name}") + spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_INVOKE_AGENT} {workflow.name}") assert len(spans) == 1 span = spans[0] From 140b5e0a64556de468897f9c2d08e9c0b3f1e190 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Fri, 30 Jan 2026 14:13:10 -0800 Subject: [PATCH 15/84] Sync eng/common directory with azure-sdk-tools for PR 13693 (#44942) * Add instruction to normalize package name * Add javascript validation * Add examples --------- Co-authored-by: Summer Warren --- .../sdk-details-in-release-plan.instructions.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/eng/common/instructions/azsdk-tools/sdk-details-in-release-plan.instructions.md b/eng/common/instructions/azsdk-tools/sdk-details-in-release-plan.instructions.md index c88a598ed1a9..bbf8b4841196 100644 --- a/eng/common/instructions/azsdk-tools/sdk-details-in-release-plan.instructions.md +++ b/eng/common/instructions/azsdk-tools/sdk-details-in-release-plan.instructions.md @@ -8,7 +8,7 @@ description: 'Identify languages configured in the TypeSpec project and add it t - For Java and Python, use `emitter-output-dir` for package name if it exists. Otherwise use `package-dir` to get the package name as fallback approach. - For .NET, use namespace property to get package name. - For JavaScript, use `packagedetails:name` property to get package name. - - For Go, use module name and remove `github.com/Azure/azure-sdk-for-go/` to get package name + - For Go, use module name and remove `github.com/Azure/azure-sdk-for-go/` to get package name. 3. Map the language name in emitter to one of the following in Pascal case(except .NET): - .NET - Java @@ -36,6 +36,16 @@ description: 'Identify languages configured in the TypeSpec project and add it t **Success Criteria**: Release plan exists or user informed to create one. # Step 3: Update Release Plan with SDK Information +> **(MANDATORY - DO NOT SKIP) ALWAYS validate all package names against the format rules AND the examples table before calling any update tool, even if the user provides SDK details directly. Auto-correct and inform the user of invalid package names.** +> - **JavaScript**: Must start with `@azure/` +> - **Go**: Must start with `sdk/` +> +> **Valid package name examples (compare against these to catch invalid formats):** +> | Language | Valid | Invalid | +> |----------|-------|---------| +> | JavaScript | `@azure/arm-compute` | `arm-compute`, `azure/arm-compute`,`@azure-arm-compute` | +> | Go (management plane) | `sdk/resourcemanager/compute/armcompute` | `sdk/armcompute`, `/sdk/compute`, `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute` | + **Goal**: Update the release plan with the languages and package names identified in Step 1. 1. Use `azsdk_update_sdk_details_in_release_plan` to update the release plan work item with the JSON object created in Step 1. 2. Confirm successful update of the release plan with the SDK information and summary of languages and package names. From 8ee53b2d1e2b326d3652bc313f0ed5503bebfd0b Mon Sep 17 00:00:00 2001 From: Darren Cohen <39422044+dargilco@users.noreply.github.com> Date: Fri, 30 Jan 2026 15:37:18 -0800 Subject: [PATCH 16/84] Fix warnings seen after tests are done running (#44933) --- sdk/ai/azure-ai-projects/tests/samples/sample_executor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/tests/samples/sample_executor.py b/sdk/ai/azure-ai-projects/tests/samples/sample_executor.py index a15b9b72b31d..46f62c506efc 100644 --- a/sdk/ai/azure-ai-projects/tests/samples/sample_executor.py +++ b/sdk/ai/azure-ai-projects/tests/samples/sample_executor.py @@ -186,7 +186,7 @@ def __init__( if not isinstance(test_var, str): continue value = kwargs.pop(test_var, None) - if value is not None: + if value is not None and isinstance(value, str): self.env_vars[sample_var] = value # Any remaining ALL_CAPS string kwargs are treated as env vars for the sample. From 7e86ab0076297173aae290c11fa14660bed2b125 Mon Sep 17 00:00:00 2001 From: saanikaguptamicrosoft Date: Mon, 2 Feb 2026 19:18:28 +0530 Subject: [PATCH 17/84] Skip list_secrets for identity-based datastores to prevent noisy telemetry traces (#44955) --- sdk/ml/azure-ai-ml/CHANGELOG.md | 2 ++ .../azure/ai/ml/_artifacts/_artifact_utilities.py | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/sdk/ml/azure-ai-ml/CHANGELOG.md b/sdk/ml/azure-ai-ml/CHANGELOG.md index 948d478b446b..e19534fa451b 100644 --- a/sdk/ml/azure-ai-ml/CHANGELOG.md +++ b/sdk/ml/azure-ai-ml/CHANGELOG.md @@ -6,6 +6,8 @@ ### Bugs Fixed +- Skip _list_secrets for identity-based datastores to prevent noisy telemetry traces. + ### Other Changes diff --git a/sdk/ml/azure-ai-ml/azure/ai/ml/_artifacts/_artifact_utilities.py b/sdk/ml/azure-ai-ml/azure/ai/ml/_artifacts/_artifact_utilities.py index c225a73e0d86..77fc69879521 100644 --- a/sdk/ml/azure-ai-ml/azure/ai/ml/_artifacts/_artifact_utilities.py +++ b/sdk/ml/azure-ai-ml/azure/ai/ml/_artifacts/_artifact_utilities.py @@ -42,6 +42,7 @@ from azure.ai.ml.constants._common import SHORT_URI_FORMAT, STORAGE_ACCOUNT_URLS from azure.ai.ml.entities import Environment from azure.ai.ml.entities._assets._artifacts.artifact import Artifact, ArtifactStorageInfo +from azure.ai.ml.entities._credentials import AadCredentialConfiguration, NoneCredentialConfiguration from azure.ai.ml.entities._datastore._constants import WORKSPACE_BLOB_STORE from azure.ai.ml.exceptions import ErrorTarget, MlException, ValidationException from azure.ai.ml.operations._datastore_operations import DatastoreOperations @@ -106,8 +107,12 @@ def get_datastore_info( ) try: - credential = operations._list_secrets(name=name, expirable_secret=True) - datastore_info["credential"] = credential.sas_token + if isinstance(datastore.credentials, (NoneCredentialConfiguration, AadCredentialConfiguration)): + module_logger.debug("Identity-based datastore detected. Skipping _list_secrets call") + datastore_info["credential"] = operations._credential + else: + credential = operations._list_secrets(name=name, expirable_secret=True) + datastore_info["credential"] = credential.sas_token except HttpResponseError: datastore_info["credential"] = operations._credential From 0e7afd85ec40adbd8db382a4dfc42e649f91112f Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Mon, 2 Feb 2026 09:55:33 -0800 Subject: [PATCH 18/84] Sync eng/common directory with azure-sdk-tools for PR 13750 (#44900) * Mark package as released using azsdk cli command --- .../templates/steps/install-azsdk-cli.yml | 16 +++++++ .../steps/mark-release-completion.yml | 7 ++- .../scripts/Mark-ReleasePlanCompletion.ps1 | 46 +++++++++---------- 3 files changed, 43 insertions(+), 26 deletions(-) create mode 100644 eng/common/pipelines/templates/steps/install-azsdk-cli.yml diff --git a/eng/common/pipelines/templates/steps/install-azsdk-cli.yml b/eng/common/pipelines/templates/steps/install-azsdk-cli.yml new file mode 100644 index 000000000000..3cbd66d9c4e5 --- /dev/null +++ b/eng/common/pipelines/templates/steps/install-azsdk-cli.yml @@ -0,0 +1,16 @@ +parameters: + InstallDirectory: $(Agent.TempDirectory) + SourceRootPath: '$(System.DefaultWorkingDirectory)' + +steps: + - task: Powershell@2 + displayName: 'Install Azure SDK Tools CLI' + inputs: + targetType: 'inline' + script: | + & "${{ parameters.SourceRootPath }}/eng/common/mcp/azure-sdk-mcp.ps1" -InstallDirectory ${{ parameters.InstallDirectory }} + $azsdkPath = Join-Path "${{ parameters.InstallDirectory }}" "azsdk$(if ($IsWindows) { '.exe' } else { '' })" + Write-Host "##vso[task.setvariable variable=AZSDK]$azsdkPath" + Write-Host "Set AZSDK variable to: $azsdkPath" + pwsh: true + workingDirectory: $(Pipeline.Workspace) \ No newline at end of file diff --git a/eng/common/pipelines/templates/steps/mark-release-completion.yml b/eng/common/pipelines/templates/steps/mark-release-completion.yml index 91a39dc48c94..0e4824872c69 100644 --- a/eng/common/pipelines/templates/steps/mark-release-completion.yml +++ b/eng/common/pipelines/templates/steps/mark-release-completion.yml @@ -4,13 +4,18 @@ parameters: SourceRootPath: $(Build.SourcesDirectory) steps: + - template: /eng/common/pipelines/templates/steps/install-azsdk-cli.yml + parameters: + SourceRootPath: ${{ parameters.SourceRootPath }} + - task: AzureCLI@2 inputs: azureSubscription: opensource-api-connection scriptType: pscore scriptLocation: scriptPath scriptPath: ${{ parameters.SourceRootPath }}/eng/common/scripts/Mark-ReleasePlanCompletion.ps1 - arguments: -PackageInfoFilePath '${{ parameters.ConfigFileDir }}/${{ parameters.PackageArtifactName }}.json' + arguments: > + -PackageInfoFilePath '${{ parameters.ConfigFileDir }}/${{ parameters.PackageArtifactName }}.json' -AzsdkExePath '$(AZSDK)' workingDirectory: $(Pipeline.Workspace) displayName: Mark package as released continueOnError: true diff --git a/eng/common/scripts/Mark-ReleasePlanCompletion.ps1 b/eng/common/scripts/Mark-ReleasePlanCompletion.ps1 index 2e623672daea..17605957fd2b 100644 --- a/eng/common/scripts/Mark-ReleasePlanCompletion.ps1 +++ b/eng/common/scripts/Mark-ReleasePlanCompletion.ps1 @@ -1,6 +1,8 @@ param( [Parameter(Mandatory = $true)] - [string]$PackageInfoFilePath + [string]$PackageInfoFilePath, + [Parameter(Mandatory = $true)] + [string]$AzsdkExePath ) <# @@ -12,12 +14,20 @@ param( .PARAMETER PackageInfoFilePath The path to the package information file (required) or path to the directory containing package information files. + +.PARAMETER AzsdkExePath + The path to the azsdk executable used to mark the release completion. #> Set-StrictMode -Version 3 . (Join-Path $PSScriptRoot common.ps1) -. (Join-Path $PSScriptRoot Helpers DevOps-WorkItem-Helpers.ps1) +#Validate azsdk executable path +if (-Not (Test-Path $AzsdkExePath)) +{ + Write-Error "The azsdk executable was not found at path '$AzsdkExePath'. Please ensure the executable exists and the path is correct." + exit 1 +} #Get package properties if (-Not (Test-Path $PackageInfoFilePath)) @@ -30,35 +40,21 @@ function Process-Package([string]$packageInfoPath) { # Get package info from json file created before updating version to daily dev $pkgInfo = Get-Content $packageInfoPath | ConvertFrom-Json - $PackageVersion = $pkgInfo.Version $PackageName = $pkgInfo.Name - if (!$PackageName -or !$PackageVersion) + if (!$PackageName) { - Write-Host "Package name or version is not available in the package information file. Skipping the release plan status update for the package." + Write-Host "Package name is not available in the package information file. Skipping the release plan status update for the package." return - } + } - # Check Azure DevOps Release Plan work items - Write-Host "Checking active release plan work items for package: $PackageName" - $workItems = Get-ReleasePlanForPackage $PackageName - if(!$workItems) + Write-Host "Marking release completion for package, name: $PackageName" + $releaseInfo = & $AzsdkExePath release-plan update-release-status --package-name $PackageName --language $LanguageDisplayName --status "Released" + if ($LASTEXITCODE -ne 0) { - Write-Host "No active release plans found for package name: $PackageName." - return - } - - $activeReleasePlan = $workItems - if($workItems.Count -gt 1 -and ($workItems -is [System.Array])) - { - $concatenatedIds = ($workItems | Select-Object -ExpandProperty id) -join ',' - Write-Host "Multiple release plans found for package name: $PackageName with work item IDs: $concatenatedIds. Using the first release plan to update release status." - $activeReleasePlan = $workItems[0] + ## Not all releases have a release plan. So we should not fail the script even if a release plan is missing. + Write-Host "Failed to mark release completion for package '$PackageName' using azsdk. Exit code: $LASTEXITCODE" } - # Update release status - Write-Host "Release plan work item ID: $($activeReleasePlan["id"])" - Write-Host "Marking release completion for package, name: $PackageName version: $PackageVersion" - Update-ReleaseStatusInReleasePlan $activeReleasePlan.id "Released" $PackageVersion - Write-Host "Successfully marked release completion for package, name: $PackageName version: $PackageVersion." + Write-Host "Details: $releaseInfo" } Write-Host "Finding all package info files in the path: $PackageInfoFilePath" From d69b18ec223a113eba6d5b31f918b2cf56215794 Mon Sep 17 00:00:00 2001 From: xitzhang Date: Mon, 2 Feb 2026 10:38:40 -0800 Subject: [PATCH 19/84] [VoiceLive]Release 1.2.0b3 (#44958) Co-authored-by: Xiting Zhang --- sdk/ai/azure-ai-voicelive/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-voicelive/CHANGELOG.md b/sdk/ai/azure-ai-voicelive/CHANGELOG.md index b44c4fffc9dc..9020d860c114 100644 --- a/sdk/ai/azure-ai-voicelive/CHANGELOG.md +++ b/sdk/ai/azure-ai-voicelive/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.2.0b3 (Unreleased) +## 1.2.0b3 (2026-02-02) ### Features Added From 87452f2b89a722ac5b9e6daaab5a843486e92fb3 Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Mon, 2 Feb 2026 11:20:06 -0800 Subject: [PATCH 20/84] Exporter release 1.0.0b47 (#44957) * Exporter release 1.0.0b47 * Amend date --- sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index 5c557160c402..d5d33e275d38 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0b47 (Unreleased) +## 1.0.0b47 (2026-02-03) ### Features Added - Rename metric names for customer sdk stats and set it on by default @@ -10,8 +10,6 @@ - Add support for user id and authId ([#44662](https://github.com/Azure/azure-sdk-for-python/pull/44662)) -### Breaking Changes - ### Bugs Fixed - Add custom metric mapping for customer sdkstats metric names to preserve casing ([#44855](https://github.com/Azure/azure-sdk-for-python/pull/44855)) From 47d01005717078ac80a5687745131d5101221f51 Mon Sep 17 00:00:00 2001 From: amber-Chen-86 Date: Mon, 2 Feb 2026 11:30:47 -0800 Subject: [PATCH 21/84] [Qna authoring] fix pylint/pyright for next version (#44889) * updated serilization * updated model base * updated tests * updated samples * update * updated test * updated --- .../authoring/_utils/model_base.py | 131 ++++++++++++++++-- .../authoring/_utils/serialization.py | 21 ++- .../sample_create_and_deploy_project_async.py | 10 +- .../sample_export_import_project_async.py | 6 + .../sample_update_knowledge_sources_async.py | 14 +- .../sample_create_and_deploy_project.py | 10 +- .../samples/sample_export_import_project.py | 6 + .../sample_update_knowledge_sources.py | 14 +- .../tests/helpers.py | 5 +- .../tests/test_create_and_deploy_project.py | 17 ++- .../test_create_and_deploy_project_async.py | 16 +-- .../tests/test_export_import_project.py | 17 +-- .../tests/test_export_import_project_async.py | 14 +- .../tests/test_update_knowledge_sources.py | 23 +-- .../test_update_knowledge_sources_async.py | 29 ++-- .../tests/testcase.py | 2 +- 16 files changed, 246 insertions(+), 89 deletions(-) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/model_base.py index 45d922b21ccc..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/model_base.py @@ -1,4 +1,4 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines,duplicate-code +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,6 +688,10 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -647,6 +701,16 @@ def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py index cca8513e0e67..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,7 +6,6 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: disable=line-too-long,useless-suppression,too-many-lines,duplicate-code,missing-module-docstring,missing-class-docstring,missing-function-docstring,consider-using-f-string,invalid-name,too-many-locals,too-many-branches # pyright: reportUnnecessaryTypeIgnoreComment=false @@ -787,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_create_and_deploy_project_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_create_and_deploy_project_async.py index 788f800fc8d0..deec3d6852c1 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_create_and_deploy_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_create_and_deploy_project_async.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + """Async sample - Create and deploy a Question Answering authoring project.""" import os @@ -15,7 +21,7 @@ async def sample_create_and_deploy_project_async(): client = QuestionAnsweringAuthoringClient(endpoint, AzureKeyCredential(key)) async with client: project_name = "IsaacNewton" - project = await client.create_project( + project = await client.create_project( # pylint: disable=no-value-for-parameter project_name=project_name, options={ "description": "Biography of Sir Isaac Newton", @@ -31,7 +37,7 @@ async def sample_create_and_deploy_project_async(): if p["projectName"] == project_name: print(f"Found project {p['projectName']}") - update_sources_poller = await client.begin_update_sources( + update_sources_poller = await client.begin_update_sources( # pylint: disable=no-value-for-parameter project_name=project_name, sources=[ _models.UpdateSourceRecord( diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_export_import_project_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_export_import_project_async.py index a1f3258484af..c8bf92acfff7 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_export_import_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_export_import_project_async.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + """Async sample - Export and import a Question Answering authoring project.""" import os diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_update_knowledge_sources_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_update_knowledge_sources_async.py index 5fbc34812413..58f48a738a8c 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_update_knowledge_sources_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/async_samples/sample_update_knowledge_sources_async.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + """Async sample - Update project knowledge sources and add QnAs & synonyms.""" import os @@ -15,7 +21,7 @@ async def sample_update_knowledge_sources_async(): client = QuestionAnsweringAuthoringClient(endpoint, AzureKeyCredential(key)) async with client: project_name = "MicrosoftFAQProject" - await client.create_project( + await client.create_project( # pylint: disable=no-value-for-parameter project_name=project_name, options={ "description": "Test project for some Microsoft QnAs", @@ -25,7 +31,7 @@ async def sample_update_knowledge_sources_async(): }, ) - sources_poller = await client.begin_update_sources( + sources_poller = await client.begin_update_sources( # pylint: disable=no-value-for-parameter project_name=project_name, sources=[ _models.UpdateSourceRecord( @@ -44,7 +50,7 @@ async def sample_update_knowledge_sources_async(): await sources_poller.result() print("Knowledge source added (MicrosoftFAQ)") - qna_poller = await client.begin_update_qnas( + qna_poller = await client.begin_update_qnas( # pylint: disable=no-value-for-parameter project_name=project_name, qnas=[ _models.UpdateQnaRecord( @@ -61,7 +67,7 @@ async def sample_update_knowledge_sources_async(): await qna_poller.result() print("QnA added (1 record)") - await client.update_synonyms( + await client.update_synonyms( # pylint: disable=no-value-for-parameter project_name=project_name, synonyms=_models.SynonymAssets( value=[ diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_create_and_deploy_project.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_create_and_deploy_project.py index de1a97d75277..d90276188291 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_create_and_deploy_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_create_and_deploy_project.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + """Sample - Create and deploy a Question Answering authoring project. This sample demonstrates how to: @@ -26,7 +32,7 @@ def sample_create_and_deploy_project(): client = QuestionAnsweringAuthoringClient(endpoint, AzureKeyCredential(key)) with client: project_name = "IsaacNewton" - project = client.create_project( + project = client.create_project( # pylint: disable=no-value-for-parameter project_name=project_name, options={ "description": "Biography of Sir Isaac Newton", @@ -46,7 +52,7 @@ def sample_create_and_deploy_project(): if p["projectName"] == project_name: print(f"Found project {p['projectName']}") - update_sources_poller = client.begin_update_sources( + update_sources_poller = client.begin_update_sources( # pylint: disable=no-value-for-parameter project_name=project_name, sources=[ _models.UpdateSourceRecord( diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_export_import_project.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_export_import_project.py index da92154cc985..df6402121b51 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_export_import_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_export_import_project.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + """Sample - Export and import a Question Answering authoring project. Shows how to: diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_update_knowledge_sources.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_update_knowledge_sources.py index cdeec7abca36..38dd1fd1e764 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_update_knowledge_sources.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/samples/sample_update_knowledge_sources.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + """Sample - Update project knowledge sources and add QnAs & synonyms. Demonstrates: @@ -26,7 +32,7 @@ def sample_update_knowledge_sources(): client = QuestionAnsweringAuthoringClient(endpoint, AzureKeyCredential(key)) with client: project_name = "MicrosoftFAQProject" - client.create_project( + client.create_project( # pylint: disable=no-value-for-parameter project_name=project_name, options={ "description": "Test project for some Microsoft QnAs", @@ -36,7 +42,7 @@ def sample_update_knowledge_sources(): }, ) - sources_poller = client.begin_update_sources( + sources_poller = client.begin_update_sources( # pylint: disable=no-value-for-parameter project_name=project_name, sources=[ _models.UpdateSourceRecord( @@ -55,7 +61,7 @@ def sample_update_knowledge_sources(): sources_poller.result() print("Knowledge source added (MicrosoftFAQ)") - qna_poller = client.begin_update_qnas( + qna_poller = client.begin_update_qnas( # pylint: disable=no-value-for-parameter project_name=project_name, qnas=[ _models.UpdateQnaRecord( @@ -72,7 +78,7 @@ def sample_update_knowledge_sources(): qna_poller.result() print("QnA added (1 record)") - client.update_synonyms( + client.update_synonyms( # pylint: disable=no-value-for-parameter project_name=project_name, synonyms=_models.SynonymAssets( value=[ diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/helpers.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/helpers.py index 9806e69dad4f..cec72f5947e1 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/helpers.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/helpers.py @@ -29,6 +29,7 @@ def create_test_project( return AuthoringTestHelper.export_project( client, project_name, delete_project=delete_old_project, **source_kwargs ) + return None @staticmethod def add_sources(client, project_name, **kwargs): @@ -49,7 +50,7 @@ def add_sources(client, project_name, **kwargs): poller.result() @staticmethod - def export_project(client, project_name, delete_project=True, **kwargs): + def export_project(client, project_name, delete_project=True, **kwargs): # pylint: disable=useless-return # begin_export poller is typed as LROPoller[None]; generator currently discards # the final body so result() returns None. We only validate successful completion. export_poller = client.begin_export(project_name=project_name, file_format="json", **kwargs) @@ -57,10 +58,8 @@ def export_project(client, project_name, delete_project=True, **kwargs): if delete_project: delete_poller = client.begin_delete_project(project_name=project_name, **kwargs) delete_poller.result() - # No export URL available due to None payload; caller should not depend on return value. return None - class AuthoringAsyncTestHelper: """Async utility helper for creating and exporting authoring test projects.""" diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project.py index 6a22ab86837c..31378f529966 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project.py @@ -1,11 +1,10 @@ # pylint: disable=line-too-long,useless-suppression -import pytest -from typing import Any, Dict, cast +from helpers import AuthoringTestHelper +from testcase import QuestionAnsweringAuthoringTestCase + from azure.core.credentials import AzureKeyCredential from azure.ai.language.questionanswering.authoring import QuestionAnsweringAuthoringClient -from helpers import AuthoringTestHelper -from testcase import QuestionAnsweringAuthoringTestCase class TestCreateAndDeploy(QuestionAnsweringAuthoringTestCase): @@ -20,12 +19,12 @@ def test_polling_interval(self, qna_authoring_creds): ) assert client._config.polling_interval == 1 - def test_create_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_create_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) project_name = "IsaacNewton" - client.create_project( + client.create_project( # pylint: disable=no-value-for-parameter project_name=project_name, options={ "description": "Biography of Sir Isaac Newton", @@ -37,7 +36,7 @@ def test_create_project(self, recorded_test, qna_authoring_creds): # type: igno found = any(p.get("projectName") == project_name for p in client.list_projects()) assert found - def test_deploy_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_deploy_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -46,12 +45,12 @@ def test_deploy_project(self, recorded_test, qna_authoring_creds): # type: igno client, project_name=project_name, is_deployable=True, - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) deployment_poller = client.begin_deploy_project( project_name=project_name, deployment_name="production", - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) # Preview LRO returns None; just ensure it completes without error deployment_poller.result() diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project_async.py index 4385d4d3c4e9..b9f1111c44f1 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_create_and_deploy_project_async.py @@ -1,21 +1,21 @@ import pytest -from typing import Any, Dict, cast +from helpers import AuthoringAsyncTestHelper +from testcase import QuestionAnsweringAuthoringTestCase + from azure.core.credentials import AzureKeyCredential from azure.ai.language.questionanswering.authoring.aio import QuestionAnsweringAuthoringClient -from helpers import AuthoringAsyncTestHelper -from testcase import QuestionAnsweringAuthoringTestCase class TestCreateAndDeployAsync(QuestionAnsweringAuthoringTestCase): @pytest.mark.asyncio - async def test_create_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_create_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) project_name = "IsaacNewton" async with client: - await client.create_project( + await client.create_project( # pylint: disable=no-value-for-parameter project_name=project_name, options={ "description": "Biography of Sir Isaac Newton", @@ -31,7 +31,7 @@ async def test_create_project(self, recorded_test, qna_authoring_creds): # type assert found @pytest.mark.asyncio - async def test_deploy_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_deploy_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -41,12 +41,12 @@ async def test_deploy_project(self, recorded_test, qna_authoring_creds): # type client, project_name=project_name, is_deployable=True, - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) deployment_poller = await client.begin_deploy_project( project_name=project_name, deployment_name="production", - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) # Preview LRO returns None; just await completion await deployment_poller.result() diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project.py index 69d2912feed5..d1b374223ad7 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project.py @@ -1,28 +1,29 @@ +from helpers import AuthoringTestHelper +from testcase import QuestionAnsweringAuthoringTestCase + from azure.core.credentials import AzureKeyCredential from azure.ai.language.questionanswering.authoring import QuestionAnsweringAuthoringClient, models as _models -from helpers import AuthoringTestHelper -from testcase import QuestionAnsweringAuthoringTestCase class TestExportAndImport(QuestionAnsweringAuthoringTestCase): - def test_export_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_export_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) project_name = "IsaacNewton" AuthoringTestHelper.create_test_project( - client, project_name=project_name, polling_interval=0 if self.is_playback else None + client, project_name=project_name, polling_interval=0 if self.is_playback else None # pylint: disable=using-constant-test ) export_poller = client.begin_export( project_name=project_name, file_format="json", - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) export_poller.result() # LROPoller[None]; ensure no exception assert export_poller.done() - def test_import_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_import_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -33,7 +34,7 @@ def test_import_project(self, recorded_test, qna_authoring_creds): # type: igno project_name=project_name, get_export_url=False, delete_old_project=False, - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) # Wait briefly until project is visible (eventual consistency safeguard) visible = any(p.get("projectName") == project_name for p in client.list_projects()) @@ -63,7 +64,7 @@ def test_import_project(self, recorded_test, qna_authoring_creds): # type: igno project_name=project_name, body=project_payload, file_format="json", - polling_interval=0 if self.is_playback else None, + polling_interval=0 if self.is_playback else None, # pylint: disable=using-constant-test ) import_poller.result() # LROPoller[None]; ensure completion assert import_poller.done() diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project_async.py index eb6836402720..dafe287b8a41 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_export_import_project_async.py @@ -1,17 +1,17 @@ -import pytest import asyncio -from typing import Any, Dict, cast -from azure.ai.language.questionanswering.authoring import models as _models -from azure.core.credentials import AzureKeyCredential -from azure.ai.language.questionanswering.authoring.aio import QuestionAnsweringAuthoringClient +import pytest from helpers import AuthoringAsyncTestHelper from testcase import QuestionAnsweringAuthoringTestCase +from azure.ai.language.questionanswering.authoring import models as _models +from azure.core.credentials import AzureKeyCredential +from azure.ai.language.questionanswering.authoring.aio import QuestionAnsweringAuthoringClient + class TestExportAndImportAsync(QuestionAnsweringAuthoringTestCase): @pytest.mark.asyncio - async def test_export_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_export_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -28,7 +28,7 @@ async def test_export_project(self, recorded_test, qna_authoring_creds): # type assert poller.done() @pytest.mark.asyncio - async def test_import_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_import_project(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources.py index 9c8e324e8288..f104a87f739e 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources.py @@ -1,14 +1,15 @@ -from azure.core.credentials import AzureKeyCredential -from azure.ai.language.questionanswering.authoring import QuestionAnsweringAuthoringClient -from azure.ai.language.questionanswering.authoring import models as _models from typing import cast from helpers import AuthoringTestHelper from testcase import QuestionAnsweringAuthoringTestCase +from azure.core.credentials import AzureKeyCredential +from azure.ai.language.questionanswering.authoring import QuestionAnsweringAuthoringClient +from azure.ai.language.questionanswering.authoring import models as _models + class TestSourcesQnasSynonyms(QuestionAnsweringAuthoringTestCase): - def test_add_source(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_add_source(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -30,16 +31,16 @@ def test_add_source(self, recorded_test, qna_authoring_creds): # type: ignore[n } ) ] - poller = client.begin_update_sources( + poller = client.begin_update_sources( # pylint: disable=no-value-for-parameter project_name=project_name, sources=cast(list[_models.UpdateSourceRecord], update_source_ops), content_type="application/json", - polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] + polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] # pylint: disable=using-constant-test ) poller.result() assert any(s.get("displayName") == source_display_name for s in client.list_sources(project_name=project_name)) - def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -59,11 +60,11 @@ def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignore[name } ) ] - poller = client.begin_update_qnas( + poller = client.begin_update_qnas( # pylint: disable=no-value-for-parameter project_name=project_name, qnas=cast(list[_models.UpdateQnaRecord], update_qna_ops), content_type="application/json", - polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] + polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] # pylint: disable=using-constant-test ) poller.result() assert any( @@ -71,7 +72,7 @@ def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignore[name for q in client.list_qnas(project_name=project_name) ) - def test_add_synonym(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + def test_add_synonym(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) @@ -82,7 +83,7 @@ def test_add_synonym(self, recorded_test, qna_authoring_creds): # type: ignore[ _models.WordAlterations(alterations=["qnamaker", "qna maker"]), ] ) - client.update_synonyms( + client.update_synonyms( # pylint: disable=no-value-for-parameter project_name=project_name, synonyms=synonyms_model, content_type="application/json", diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources_async.py index a565ef5ffcb7..39a485f54a79 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/test_update_knowledge_sources_async.py @@ -1,23 +1,24 @@ -import pytest from typing import cast +import pytest +from helpers import AuthoringAsyncTestHelper +from testcase import QuestionAnsweringAuthoringTestCase + from azure.core.credentials import AzureKeyCredential from azure.ai.language.questionanswering.authoring.aio import QuestionAnsweringAuthoringClient from azure.ai.language.questionanswering.authoring import models as _models -from helpers import AuthoringAsyncTestHelper -from testcase import QuestionAnsweringAuthoringTestCase class TestSourcesQnasSynonymsAsync(QuestionAnsweringAuthoringTestCase): @pytest.mark.asyncio - async def test_add_source(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_add_source(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) project_name = "IsaacNewton" async with client: await AuthoringAsyncTestHelper.create_test_project( - client, project_name=project_name, polling_interval=0 if self.is_playback else None + client, project_name=project_name, polling_interval=0 if self.is_playback else None # pylint: disable=using-constant-test ) update_source_ops = [ _models.UpdateSourceRecord( @@ -34,11 +35,11 @@ async def test_add_source(self, recorded_test, qna_authoring_creds): # type: ig } ) ] - poller = await client.begin_update_sources( + poller = await client.begin_update_sources( # pylint: disable=no-value-for-parameter project_name=project_name, sources=cast(list[_models.UpdateSourceRecord], update_source_ops), content_type="application/json", - polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] + polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] # pylint: disable=using-constant-test ) await poller.result() found = False @@ -48,14 +49,14 @@ async def test_add_source(self, recorded_test, qna_authoring_creds): # type: ig assert found @pytest.mark.asyncio - async def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) project_name = "IsaacNewton" async with client: await AuthoringAsyncTestHelper.create_test_project( - client, project_name=project_name, polling_interval=0 if self.is_playback else None + client, project_name=project_name, polling_interval=0 if self.is_playback else None # pylint: disable=using-constant-test ) question = "What is the easiest way to use azure services in my .NET project?" answer = "Using Microsoft's Azure SDKs" @@ -71,11 +72,11 @@ async def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignor } ) ] - poller = await client.begin_update_qnas( + poller = await client.begin_update_qnas( # pylint: disable=no-value-for-parameter project_name=project_name, qnas=cast(list[_models.UpdateQnaRecord], update_qna_ops), content_type="application/json", - polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] + polling_interval=0 if self.is_playback else None, # type: ignore[arg-type] # pylint: disable=using-constant-test ) await poller.result() found = False @@ -85,21 +86,21 @@ async def test_add_qna(self, recorded_test, qna_authoring_creds): # type: ignor assert found @pytest.mark.asyncio - async def test_add_synonym(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] + async def test_add_synonym(self, recorded_test, qna_authoring_creds): # type: ignore[name-defined] # pylint: disable=unused-argument client = QuestionAnsweringAuthoringClient( qna_authoring_creds["endpoint"], AzureKeyCredential(qna_authoring_creds["key"]) ) project_name = "IsaacNewton" async with client: await AuthoringAsyncTestHelper.create_test_project( - client, project_name=project_name, polling_interval=0 if self.is_playback else None + client, project_name=project_name, polling_interval=0 if self.is_playback else None # pylint: disable=using-constant-test ) synonyms_model = _models.SynonymAssets( value=[ _models.WordAlterations(alterations=["qnamaker", "qna maker"]), ] ) - await client.update_synonyms( + await client.update_synonyms( # pylint: disable=no-value-for-parameter project_name=project_name, synonyms=synonyms_model, content_type="application/json", diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/testcase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/testcase.py index a8fb6a4a8d00..3a7239e403a9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/testcase.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/tests/testcase.py @@ -4,6 +4,6 @@ class QuestionAnsweringAuthoringTestCase(AzureRecordedTestCase): @property def kwargs_for_polling(self): - if self.is_playback: + if self.is_playback: # pylint: disable=using-constant-test return {"polling_interval": 0} return {} From e9c19a1a29fad944ec0660f6c3da8cf82efad363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?McCoy=20Pati=C3=B1o?= <39780829+mccoyp@users.noreply.github.com> Date: Mon, 2 Feb 2026 12:02:13 -0800 Subject: [PATCH 22/84] [Key Vault] Update continuation tokens (#44879) --- .../CHANGELOG.md | 8 ++- .../keyvault/administration/_backup_client.py | 56 ++++++++++++++++++- .../administration/_internal/polling.py | 11 +++- .../azure/keyvault/administration/_version.py | 2 +- .../administration/aio/_backup_client.py | 5 +- .../azure-keyvault-administration/setup.py | 2 +- 6 files changed, 74 insertions(+), 10 deletions(-) diff --git a/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md index 3b902caa0f26..e35340edc081 100644 --- a/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md +++ b/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md @@ -1,15 +1,21 @@ # Release History -## 4.6.1 (Unreleased) +## 4.7.0 (Unreleased) ### Features Added ### Breaking Changes +- Changed the continuation token format. Continuation tokens generated by previous versions of + `azure-keyvault-administration` are not compatible with this version. Similarly, continuation tokens generated by + previous versions of this library are not compatible with versions of `azure-core>=1.38.0`. + ### Bugs Fixed ### Other Changes +- Updated minimum `azure-core` version to 1.38.0 + ## 4.6.0 (2025-06-16) ### Features Added diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_backup_client.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_backup_client.py index 714907cdf182..b6b5a9ecf04e 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_backup_client.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_backup_client.py @@ -4,12 +4,13 @@ # ------------------------------------ import base64 import functools -import pickle +import json from typing import Any, Callable, Optional, overload from urllib.parse import urlparse from typing_extensions import Literal +from azure.core.pipeline import PipelineResponse from azure.core.polling import LROPoller from azure.core.tracing.decorator import distributed_trace @@ -19,12 +20,61 @@ from ._internal.polling import KeyVaultBackupClientPolling, KeyVaultBackupClientPollingMethod -def _parse_status_url(url): +def _parse_status_url(url: str) -> str: parsed = urlparse(url) job_id = parsed.path.split("/")[2] return job_id +def _get_continuation_token(pipeline_response: PipelineResponse) -> str: + """Returns an opaque token which can be used by the user to rehydrate/restart the LRO. + + Saves the state of the LRO based on a status response so that polling can be resumed from that context. Because + the service has different operations for backup/restore starting vs. status checking, the caller is expected to + first use the status URL from the initial response to make a status request and then pass that status response to + this function to be serialized into a continuation token. + + :param pipeline_response: The pipeline response of the operation status request. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :returns: An opaque continuation token that can be provided to Core to rehydrate the LRO. + :rtype: str + """ + # Headers needed for LRO rehydration - use an allowlist approach for security + lro_headers = {"azure-asyncoperation", "operation-location", "location", "content-type", "retry-after"} + response = pipeline_response.http_response + filtered_headers = {k: v for k, v in response.headers.items() if k.lower() in lro_headers} + + request = response.request + # Serialize the essential parts of the PipelineResponse to JSON. + if request: + request_headers = {} + # Preserve x-ms-client-request-id for request correlation + if "x-ms-client-request-id" in request.headers: + request_headers["x-ms-client-request-id"] = request.headers["x-ms-client-request-id"] + request_state = { + "method": request.method, + "url": request.url, + "headers": request_headers, + } + else: + request_state = None + + # Use a versioned token schema: {"version": , "data": } + # This allows for future compatibility checking when deserializing + token = { + "version": 1, + "data": { + "request": request_state, + "response": { + "status_code": response.status_code, + "headers": filtered_headers, + "content": base64.b64encode(response.content).decode("ascii"), + }, + }, + } + return base64.b64encode(json.dumps(token, separators=(",", ":")).encode("utf-8")).decode("ascii") + + class KeyVaultBackupClient(KeyVaultClientBase): """Performs Key Vault backup and restore operations. @@ -56,7 +106,7 @@ def _use_continuation_token(self, continuation_token: str, status_method: Callab ) if "azure-asyncoperation" not in pipeline_response.http_response.headers: pipeline_response.http_response.headers["azure-asyncoperation"] = status_url - return base64.b64encode(pickle.dumps(pipeline_response)).decode("ascii") + return _get_continuation_token(pipeline_response) @overload def begin_backup( diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/polling.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/polling.py index eba971b80c47..955c6a9ea6a6 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/polling.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/polling.py @@ -15,7 +15,7 @@ class KeyVaultBackupClientPolling(OperationResourcePolling): def __init__(self) -> None: self._polling_url = "" - super(KeyVaultBackupClientPolling, self).__init__(operation_location_header="azure-asyncoperation") + super().__init__(operation_location_header="azure-asyncoperation") def get_polling_url(self) -> str: return self._polling_url @@ -34,4 +34,13 @@ def set_initial_status(self, pipeline_response: "PipelineResponse") -> str: class KeyVaultBackupClientPollingMethod(LROBasePolling): def get_continuation_token(self) -> str: + """ + Get a continuation token to resume the polling later. + + :return: A continuation token. + :rtype: str + """ + # Because of the operation structure, we need to use a "continuation token" that is just the status URL. + # This URL can then be used to fetch the status of the operation when resuming, at which point a genuine + # continuation token will be created from the response and provided to Core. return base64.b64encode(self._operation.get_polling_url().encode()).decode("ascii") diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py index e097932524a1..2599c734f6f5 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py @@ -3,4 +3,4 @@ # Licensed under the MIT License. # ------------------------------------ -VERSION = "4.6.1" +VERSION = "4.7.0" diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/_backup_client.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/_backup_client.py index cc27d245b00e..f3dc496572bb 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/_backup_client.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/_backup_client.py @@ -4,7 +4,6 @@ # ------------------------------------ import base64 import functools -import pickle from typing import Any, Callable, Optional, overload from typing_extensions import Literal @@ -13,7 +12,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from .._generated.models import PreBackupOperationParameters, PreRestoreOperationParameters, SASTokenParameter -from .._backup_client import _parse_status_url +from .._backup_client import _get_continuation_token, _parse_status_url from .._internal import AsyncKeyVaultClientBase, parse_folder_url from .._internal.async_polling import KeyVaultAsyncBackupClientPollingMethod from .._internal.polling import KeyVaultBackupClientPolling @@ -51,7 +50,7 @@ async def _use_continuation_token(self, continuation_token: str, status_method: ) if "azure-asyncoperation" not in pipeline_response.http_response.headers: pipeline_response.http_response.headers["azure-asyncoperation"] = status_url - return base64.b64encode(pickle.dumps(pipeline_response)).decode("ascii") + return _get_continuation_token(pipeline_response) @overload async def begin_backup( diff --git a/sdk/keyvault/azure-keyvault-administration/setup.py b/sdk/keyvault/azure-keyvault-administration/setup.py index 186dd18143f0..0edb70640803 100644 --- a/sdk/keyvault/azure-keyvault-administration/setup.py +++ b/sdk/keyvault/azure-keyvault-administration/setup.py @@ -62,7 +62,7 @@ ), install_requires=[ "isodate>=0.6.1", - "azure-core>=1.31.0", + "azure-core>=1.38.0", "typing-extensions>=4.6.0", ], python_requires=">=3.9", From 3dd1fa5a6f19f37538ce85aafadc0981f2851af2 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Feb 2026 15:42:08 -0800 Subject: [PATCH 23/84] Remove editable install flags from dev_requirements.txt ***NO_CI*** (#44943) - Removed -e flag from 217 dependency lines across 125 dev_requirements.txt files - Preserved -e flag for azure-sdk-tools and tests/* paths as required - No other changes made to requirement files ***NO_CI*** Co-authored-by: JennyPng <63012604+JennyPng@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: JennyPng <63012604+JennyPng@users.noreply.github.com> --- .../azure-mgmt-advisor/dev_requirements.txt | 4 ++-- .../azure-agrifood-farming/dev_requirements.txt | 4 ++-- .../azure-mgmt-apicenter/dev_requirements.txt | 2 +- .../azure-mgmt-apimanagement/dev_requirements.txt | 2 +- .../dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 8 ++++---- .../azure-appconfiguration/dev_requirements.txt | 2 +- .../azure-mgmt-appcontainers/dev_requirements.txt | 2 +- .../azure-mgmt-appplatform/dev_requirements.txt | 2 +- sdk/appservice/azure-mgmt-web/dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- sdk/astro/azure-mgmt-astro/dev_requirements.txt | 2 +- .../azure-mgmt-authorization/dev_requirements.txt | 2 +- .../azure-mgmt-automation/dev_requirements.txt | 2 +- .../azure-mgmt-azurestackhci/dev_requirements.txt | 2 +- sdk/batch/azure-batch/dev_requirements.txt | 2 +- sdk/batch/azure-mgmt-batch/dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- sdk/cdn/azure-mgmt-cdn/dev_requirements.txt | 4 ++-- sdk/chaos/azure-mgmt-chaos/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-mgmt-commerce/dev_requirements.txt | 2 +- .../dev_requirements.txt | 8 ++++---- .../azure-communication-chat/dev_requirements.txt | 2 +- .../azure-communication-email/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-communication-rooms/dev_requirements.txt | 2 +- .../azure-communication-sms/dev_requirements.txt | 2 +- .../azure-mgmt-communication/dev_requirements.txt | 8 ++++---- sdk/compute/azure-mgmt-avs/dev_requirements.txt | 2 +- .../azure-mgmt-compute/dev_requirements.txt | 10 +++++----- .../azure-mgmt-imagebuilder/dev_requirements.txt | 2 +- .../azure-mgmt-computefleet/dev_requirements.txt | 8 ++++---- .../dev_requirements.txt | 6 +++--- .../azure-confidentialledger/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../azure-mgmt-confluent/dev_requirements.txt | 2 +- .../azure-mgmt-connectedcache/dev_requirements.txt | 6 +++--- .../azure-mgmt-consumption/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- sdk/core/azure-common/dev_requirements.txt | 2 +- sdk/cosmos/azure-cosmos/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 6 +++--- .../azure-mgmt-databox/dev_requirements.txt | 2 +- .../azure-mgmt-datafactory/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-mgmt-datamigration/dev_requirements.txt | 2 +- .../azure-mgmt-dataprotection/dev_requirements.txt | 2 +- .../azure-mgmt-defendereasm/dev_requirements.txt | 2 +- .../azure-mgmt-dellstorage/dev_requirements.txt | 6 +++--- .../azure-mgmt-dependencymap/dev_requirements.txt | 6 +++--- .../azure-mgmt-devcenter/dev_requirements.txt | 2 +- sdk/devhub/azure-mgmt-devhub/dev_requirements.txt | 2 +- .../azure-mgmt-deviceregistry/dev_requirements.txt | 2 +- .../azure-iot-deviceupdate/dev_requirements.txt | 2 +- .../dev_requirements.txt | 8 ++++---- .../azure-mgmt-devtestlabs/dev_requirements.txt | 4 ++-- .../azure-digitaltwins-core/dev_requirements.txt | 2 +- .../azure-mgmt-digitaltwins/dev_requirements.txt | 6 +++--- .../azure-mgmt-durabletask/dev_requirements.txt | 6 +++--- .../azure-mgmt-edgeorder/dev_requirements.txt | 2 +- .../azure-mgmt-edgezones/dev_requirements.txt | 8 ++++---- .../azure-mgmt-elasticsan/dev_requirements.txt | 2 +- .../azure-ai-evaluation/dev_requirements.txt | 2 +- sdk/eventgrid/azure-eventgrid/dev_requirements.txt | 6 +++--- .../azure-mgmt-eventgrid/dev_requirements.txt | 4 ++-- .../azure-mgmt-eventhub/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- sdk/fabric/azure-mgmt-fabric/dev_requirements.txt | 6 +++--- .../azure-ai-formrecognizer/dev_requirements.txt | 2 +- .../azure-mgmt-graphservices/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-mgmt-hdinsight/dev_requirements.txt | 12 ++++++------ .../dev_requirements.txt | 8 ++++---- .../azure-mgmt-hybridcompute/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 8 ++++---- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- sdk/iothub/azure-mgmt-iothub/dev_requirements.txt | 4 ++-- .../azure-mgmt-iotoperations/dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../azure-keyvault-secrets/dev_requirements.txt | 2 +- .../azure-mgmt-keyvault/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- .../azure-mgmt-largeinstance/dev_requirements.txt | 2 +- .../azure-mgmt-loadtesting/dev_requirements.txt | 4 ++-- .../azure-mgmt-loganalytics/dev_requirements.txt | 4 ++-- sdk/logic/azure-mgmt-logic/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-maps-geolocation/dev_requirements.txt | 4 ++-- sdk/maps/azure-maps-render/dev_requirements.txt | 4 ++-- sdk/maps/azure-maps-route/dev_requirements.txt | 4 ++-- sdk/maps/azure-maps-search/dev_requirements.txt | 4 ++-- sdk/maps/azure-maps-timezone/dev_requirements.txt | 4 ++-- sdk/maps/azure-maps-weather/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 4 ++-- sdk/media/azure-mgmt-media/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-mgmt-mongocluster/dev_requirements.txt | 8 ++++---- .../azure-mgmt-mongodbatlas/dev_requirements.txt | 6 +++--- .../azure-mgmt-monitor/dev_requirements.txt | 14 +++++++------- .../azure-monitor-ingestion/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-mgmt-neonpostgres/dev_requirements.txt | 6 +++--- sdk/netapp/azure-mgmt-netapp/dev_requirements.txt | 6 +++--- sdk/network/azure-mgmt-dns/dev_requirements.txt | 4 ++-- .../azure-mgmt-network/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../azure-mgmt-networkcloud/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- sdk/nginx/azure-mgmt-nginx/dev_requirements.txt | 2 +- .../dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 6 +++--- .../azure-mgmt-oracledatabase/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../azure-mgmt-peering/dev_requirements.txt | 4 ++-- .../azure-ai-personalizer/dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../azure-purview-catalog/dev_requirements.txt | 2 +- .../azure-purview-scanning/dev_requirements.txt | 2 +- .../azure-purview-sharing/dev_requirements.txt | 2 +- .../azure-mgmt-quantum/dev_requirements.txt | 2 +- sdk/qumulo/azure-mgmt-qumulo/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- sdk/redis/azure-mgmt-redis/dev_requirements.txt | 2 +- sdk/relay/azure-mgmt-relay/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- .../azure-mgmt-resourcehealth/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-schemaregistry/dev_requirements.txt | 2 +- sdk/scvmm/azure-mgmt-scvmm/dev_requirements.txt | 2 +- sdk/search/azure-mgmt-search/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 6 +++--- .../azure-mgmt-securitydevops/dev_requirements.txt | 2 +- .../azure-mgmt-selfhelp/dev_requirements.txt | 2 +- .../azure-mgmt-servicebus/dev_requirements.txt | 4 ++-- .../azure-servicebus/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-mgmt-servicelinker/dev_requirements.txt | 2 +- .../dev_requirements.txt | 4 ++-- .../azure-mgmt-sitemanager/dev_requirements.txt | 6 +++--- sdk/sphere/azure-mgmt-sphere/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 2 +- sdk/sql/azure-mgmt-sql/dev_requirements.txt | 4 ++-- .../azure-mgmt-standbypool/dev_requirements.txt | 2 +- .../azure-mgmt-storage/dev_requirements.txt | 2 +- .../azure-mgmt-storagesync/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 6 +++--- .../azure-storage-blob/dev_requirements.txt | 4 ++-- .../dev_requirements.txt | 6 +++--- .../azure-storage-file-share/dev_requirements.txt | 6 +++--- .../azure-storage-queue/dev_requirements.txt | 4 ++-- .../azure-mgmt-storageactions/dev_requirements.txt | 2 +- .../azure-mgmt-storagemover/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-synapse-artifacts/dev_requirements.txt | 2 +- .../azure-mgmt-terraform/dev_requirements.txt | 6 +++--- .../azure-mgmt-testbase/dev_requirements.txt | 2 +- .../azure-ai-textanalytics/dev_requirements.txt | 2 +- .../dev_requirements.txt | 2 +- .../azure-ai-translation-text/dev_requirements.txt | 4 ++-- .../azure-mgmt-trustedsigning/dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- .../azure-mgmt-voiceservices/dev_requirements.txt | 2 +- .../azure-mgmt-webpubsub/dev_requirements.txt | 2 +- .../dev_requirements.txt | 6 +++--- .../dev_requirements.txt | 2 +- 202 files changed, 353 insertions(+), 353 deletions(-) diff --git a/sdk/advisor/azure-mgmt-advisor/dev_requirements.txt b/sdk/advisor/azure-mgmt-advisor/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/advisor/azure-mgmt-advisor/dev_requirements.txt +++ b/sdk/advisor/azure-mgmt-advisor/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/agrifood/azure-agrifood-farming/dev_requirements.txt b/sdk/agrifood/azure-agrifood-farming/dev_requirements.txt index 64d8f38a420f..90c8f164b7e9 100644 --- a/sdk/agrifood/azure-agrifood-farming/dev_requirements.txt +++ b/sdk/agrifood/azure-agrifood-farming/dev_requirements.txt @@ -1,5 +1,5 @@ aiohttp==3.8.3 python-dateutil==2.8.2 --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity -e ../../../eng/tools/azure-sdk-tools \ No newline at end of file diff --git a/sdk/apicenter/azure-mgmt-apicenter/dev_requirements.txt b/sdk/apicenter/azure-mgmt-apicenter/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/apicenter/azure-mgmt-apicenter/dev_requirements.txt +++ b/sdk/apicenter/azure-mgmt-apicenter/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/apimanagement/azure-mgmt-apimanagement/dev_requirements.txt b/sdk/apimanagement/azure-mgmt-apimanagement/dev_requirements.txt index e61667f279ee..0a8d1282d521 100644 --- a/sdk/apimanagement/azure-mgmt-apimanagement/dev_requirements.txt +++ b/sdk/apimanagement/azure-mgmt-apimanagement/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/appcomplianceautomation/azure-mgmt-appcomplianceautomation/dev_requirements.txt b/sdk/appcomplianceautomation/azure-mgmt-appcomplianceautomation/dev_requirements.txt index 731391f73e3b..4935ec8e9d54 100644 --- a/sdk/appcomplianceautomation/azure-mgmt-appcomplianceautomation/dev_requirements.txt +++ b/sdk/appcomplianceautomation/azure-mgmt-appcomplianceautomation/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource \ No newline at end of file +../../identity/azure-identity +../../resources/azure-mgmt-resource \ No newline at end of file diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/dev_requirements.txt b/sdk/appconfiguration/azure-appconfiguration-provider/dev_requirements.txt index ae1f2f2b15aa..4b92e5616f7b 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/dev_requirements.txt +++ b/sdk/appconfiguration/azure-appconfiguration-provider/dev_requirements.txt @@ -1,7 +1,7 @@ --e ../../core/azure-core --e ../azure-appconfiguration --e ../../identity/azure-identity --e ../../keyvault/azure-keyvault-secrets +../../core/azure-core +../azure-appconfiguration +../../identity/azure-identity +../../keyvault/azure-keyvault-secrets aiohttp>=3.0 -e ../../../eng/tools/azure-sdk-tools dnspython \ No newline at end of file diff --git a/sdk/appconfiguration/azure-appconfiguration/dev_requirements.txt b/sdk/appconfiguration/azure-appconfiguration/dev_requirements.txt index 705af04eb4c3..ccba96b7845c 100644 --- a/sdk/appconfiguration/azure-appconfiguration/dev_requirements.txt +++ b/sdk/appconfiguration/azure-appconfiguration/dev_requirements.txt @@ -1,4 +1,4 @@ ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 -e ../../../eng/tools/azure-sdk-tools \ No newline at end of file diff --git a/sdk/appcontainers/azure-mgmt-appcontainers/dev_requirements.txt b/sdk/appcontainers/azure-mgmt-appcontainers/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/appcontainers/azure-mgmt-appcontainers/dev_requirements.txt +++ b/sdk/appcontainers/azure-mgmt-appcontainers/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/appplatform/azure-mgmt-appplatform/dev_requirements.txt b/sdk/appplatform/azure-mgmt-appplatform/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/appplatform/azure-mgmt-appplatform/dev_requirements.txt +++ b/sdk/appplatform/azure-mgmt-appplatform/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/appservice/azure-mgmt-web/dev_requirements.txt b/sdk/appservice/azure-mgmt-web/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/appservice/azure-mgmt-web/dev_requirements.txt +++ b/sdk/appservice/azure-mgmt-web/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/arizeaiobservabilityeval/azure-mgmt-arizeaiobservabilityeval/dev_requirements.txt b/sdk/arizeaiobservabilityeval/azure-mgmt-arizeaiobservabilityeval/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/arizeaiobservabilityeval/azure-mgmt-arizeaiobservabilityeval/dev_requirements.txt +++ b/sdk/arizeaiobservabilityeval/azure-mgmt-arizeaiobservabilityeval/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/astro/azure-mgmt-astro/dev_requirements.txt b/sdk/astro/azure-mgmt-astro/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/astro/azure-mgmt-astro/dev_requirements.txt +++ b/sdk/astro/azure-mgmt-astro/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/authorization/azure-mgmt-authorization/dev_requirements.txt b/sdk/authorization/azure-mgmt-authorization/dev_requirements.txt index 21dffe8d9f28..7549444d1bc8 100644 --- a/sdk/authorization/azure-mgmt-authorization/dev_requirements.txt +++ b/sdk/authorization/azure-mgmt-authorization/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource azure-identity aiohttp \ No newline at end of file diff --git a/sdk/automation/azure-mgmt-automation/dev_requirements.txt b/sdk/automation/azure-mgmt-automation/dev_requirements.txt index f7ad9f9adf27..a8e71c5456b3 100644 --- a/sdk/automation/azure-mgmt-automation/dev_requirements.txt +++ b/sdk/automation/azure-mgmt-automation/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity azure-mgmt-resource<=21.1.0 aiohttp \ No newline at end of file diff --git a/sdk/azurestackhci/azure-mgmt-azurestackhci/dev_requirements.txt b/sdk/azurestackhci/azure-mgmt-azurestackhci/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/azurestackhci/azure-mgmt-azurestackhci/dev_requirements.txt +++ b/sdk/azurestackhci/azure-mgmt-azurestackhci/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/batch/azure-batch/dev_requirements.txt b/sdk/batch/azure-batch/dev_requirements.txt index 06a838c51c92..183ff8171ed7 100644 --- a/sdk/batch/azure-batch/dev_requirements.txt +++ b/sdk/batch/azure-batch/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../azure-mgmt-batch +../azure-mgmt-batch ../../core/azure-core # -e ../../identity/azure-identity azure-identity==1.17.0 diff --git a/sdk/batch/azure-mgmt-batch/dev_requirements.txt b/sdk/batch/azure-mgmt-batch/dev_requirements.txt index 00f05861f2c6..ab67d6e884ee 100644 --- a/sdk/batch/azure-mgmt-batch/dev_requirements.txt +++ b/sdk/batch/azure-mgmt-batch/dev_requirements.txt @@ -1,7 +1,7 @@ -e ../../../eng/tools/azure-sdk-tools azure-mgmt-keyvault<9.0.0 azure-mgmt-network<19.0.0 --e ../../resources/azure-mgmt-resource --e ../../storage/azure-mgmt-storage --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../storage/azure-mgmt-storage +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/billingbenefits/azure-mgmt-billingbenefits/dev_requirements.txt b/sdk/billingbenefits/azure-mgmt-billingbenefits/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/billingbenefits/azure-mgmt-billingbenefits/dev_requirements.txt +++ b/sdk/billingbenefits/azure-mgmt-billingbenefits/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/carbonoptimization/azure-mgmt-carbonoptimization/dev_requirements.txt b/sdk/carbonoptimization/azure-mgmt-carbonoptimization/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/carbonoptimization/azure-mgmt-carbonoptimization/dev_requirements.txt +++ b/sdk/carbonoptimization/azure-mgmt-carbonoptimization/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/cdn/azure-mgmt-cdn/dev_requirements.txt b/sdk/cdn/azure-mgmt-cdn/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/cdn/azure-mgmt-cdn/dev_requirements.txt +++ b/sdk/cdn/azure-mgmt-cdn/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/chaos/azure-mgmt-chaos/dev_requirements.txt b/sdk/chaos/azure-mgmt-chaos/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/chaos/azure-mgmt-chaos/dev_requirements.txt +++ b/sdk/chaos/azure-mgmt-chaos/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt index d85e980ba5ab..9b07154dfb12 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt index 06543e63230c..c6c61de0d536 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/commerce/azure-mgmt-commerce/dev_requirements.txt b/sdk/commerce/azure-mgmt-commerce/dev_requirements.txt index ab6cd9c7ce39..0b3af944d4fe 100644 --- a/sdk/commerce/azure-mgmt-commerce/dev_requirements.txt +++ b/sdk/commerce/azure-mgmt-commerce/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity \ No newline at end of file +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/dev_requirements.txt b/sdk/communication/azure-communication-callautomation/dev_requirements.txt index 7b4345d39272..e134cf274cd2 100644 --- a/sdk/communication/azure-communication-callautomation/dev_requirements.txt +++ b/sdk/communication/azure-communication-callautomation/dev_requirements.txt @@ -1,7 +1,7 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../azure-communication-identity --e ../azure-communication-phonenumbers --e ../../servicebus/azure-servicebus +../../identity/azure-identity +../azure-communication-identity +../azure-communication-phonenumbers +../../servicebus/azure-servicebus ../../core/azure-core aiohttp>=3.0 diff --git a/sdk/communication/azure-communication-chat/dev_requirements.txt b/sdk/communication/azure-communication-chat/dev_requirements.txt index b3a15c06229d..c9669e4f72dd 100644 --- a/sdk/communication/azure-communication-chat/dev_requirements.txt +++ b/sdk/communication/azure-communication-chat/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../azure-communication-identity +../azure-communication-identity aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/communication/azure-communication-email/dev_requirements.txt b/sdk/communication/azure-communication-email/dev_requirements.txt index a92c38d993fc..dfbca19feb7f 100644 --- a/sdk/communication/azure-communication-email/dev_requirements.txt +++ b/sdk/communication/azure-communication-email/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../core/azure-core aiohttp>=3.0 aiounittest>=1.4 diff --git a/sdk/communication/azure-communication-identity/dev_requirements.txt b/sdk/communication/azure-communication-identity/dev_requirements.txt index 0386e1599d54..25c8da815626 100644 --- a/sdk/communication/azure-communication-identity/dev_requirements.txt +++ b/sdk/communication/azure-communication-identity/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../core/azure-core ../azure-mgmt-communication aiohttp>=3.0 diff --git a/sdk/communication/azure-communication-jobrouter/dev_requirements.txt b/sdk/communication/azure-communication-jobrouter/dev_requirements.txt index 7d28d1d34897..0c7e4d5e3071 100644 --- a/sdk/communication/azure-communication-jobrouter/dev_requirements.txt +++ b/sdk/communication/azure-communication-jobrouter/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../core/azure-core aiohttp>=3.0 aiounittest>=1.4 diff --git a/sdk/communication/azure-communication-phonenumbers/dev_requirements.txt b/sdk/communication/azure-communication-phonenumbers/dev_requirements.txt index 7607bf1b7d76..f5a45df21370 100644 --- a/sdk/communication/azure-communication-phonenumbers/dev_requirements.txt +++ b/sdk/communication/azure-communication-phonenumbers/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../core/azure-core ../azure-mgmt-communication aiohttp diff --git a/sdk/communication/azure-communication-rooms/dev_requirements.txt b/sdk/communication/azure-communication-rooms/dev_requirements.txt index e7b452ea0f88..054f57ff0867 100644 --- a/sdk/communication/azure-communication-rooms/dev_requirements.txt +++ b/sdk/communication/azure-communication-rooms/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../azure-communication-identity +../azure-communication-identity ../../core/azure-core ../../identity/azure-identity aiohttp>=3.0 diff --git a/sdk/communication/azure-communication-sms/dev_requirements.txt b/sdk/communication/azure-communication-sms/dev_requirements.txt index f3af189dc584..1e3db03f7e76 100644 --- a/sdk/communication/azure-communication-sms/dev_requirements.txt +++ b/sdk/communication/azure-communication-sms/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../core/azure-core aiohttp>=3.0 aiounittest>=1.4 diff --git a/sdk/communication/azure-mgmt-communication/dev_requirements.txt b/sdk/communication/azure-mgmt-communication/dev_requirements.txt index 27d18e448032..c00b999fe876 100644 --- a/sdk/communication/azure-mgmt-communication/dev_requirements.txt +++ b/sdk/communication/azure-mgmt-communication/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../notificationhubs/azure-mgmt-notificationhubs --e ../../identity/azure-identity --e ../../core/azure-core --e ../../resources/azure-mgmt-resource +../../notificationhubs/azure-mgmt-notificationhubs +../../identity/azure-identity +../../core/azure-core +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/compute/azure-mgmt-avs/dev_requirements.txt b/sdk/compute/azure-mgmt-avs/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/compute/azure-mgmt-avs/dev_requirements.txt +++ b/sdk/compute/azure-mgmt-avs/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/compute/azure-mgmt-compute/dev_requirements.txt b/sdk/compute/azure-mgmt-compute/dev_requirements.txt index b5e00a02098a..1402d7934329 100644 --- a/sdk/compute/azure-mgmt-compute/dev_requirements.txt +++ b/sdk/compute/azure-mgmt-compute/dev_requirements.txt @@ -1,9 +1,9 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../authorization/azure-mgmt-authorization --e ../../storage/azure-mgmt-storage --e ../../network/azure-mgmt-network --e ../../resources/azure-mgmt-resource +../../authorization/azure-mgmt-authorization +../../storage/azure-mgmt-storage +../../network/azure-mgmt-network +../../resources/azure-mgmt-resource aiohttp>=3.0; python_version >= '3.5' --e ../../identity/azure-identity +../../identity/azure-identity azure-storage-blob==12.9.0 azure-mgmt-keyvault==10.0.0 \ No newline at end of file diff --git a/sdk/compute/azure-mgmt-imagebuilder/dev_requirements.txt b/sdk/compute/azure-mgmt-imagebuilder/dev_requirements.txt index b026bee1adf7..f3e7f26d8bec 100644 --- a/sdk/compute/azure-mgmt-imagebuilder/dev_requirements.txt +++ b/sdk/compute/azure-mgmt-imagebuilder/dev_requirements.txt @@ -1,2 +1,2 @@ --e ../../core/azure-core +../../core/azure-core -e ../../../eng/tools/azure-sdk-tools \ No newline at end of file diff --git a/sdk/computefleet/azure-mgmt-computefleet/dev_requirements.txt b/sdk/computefleet/azure-mgmt-computefleet/dev_requirements.txt index 145c0e09d584..4a66c56eb861 100644 --- a/sdk/computefleet/azure-mgmt-computefleet/dev_requirements.txt +++ b/sdk/computefleet/azure-mgmt-computefleet/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../resources/azure-mgmt-resource +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/computeschedule/azure-mgmt-computeschedule/dev_requirements.txt b/sdk/computeschedule/azure-mgmt-computeschedule/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/computeschedule/azure-mgmt-computeschedule/dev_requirements.txt +++ b/sdk/computeschedule/azure-mgmt-computeschedule/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/confidentialledger/azure-confidentialledger/dev_requirements.txt b/sdk/confidentialledger/azure-confidentialledger/dev_requirements.txt index 0bcd5ba03d2d..75e0500c7e94 100644 --- a/sdk/confidentialledger/azure-confidentialledger/dev_requirements.txt +++ b/sdk/confidentialledger/azure-confidentialledger/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity ../azure-confidentialledger-certificate aiohttp diff --git a/sdk/confidentialledger/azure-mgmt-confidentialledger/dev_requirements.txt b/sdk/confidentialledger/azure-mgmt-confidentialledger/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/confidentialledger/azure-mgmt-confidentialledger/dev_requirements.txt +++ b/sdk/confidentialledger/azure-mgmt-confidentialledger/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/confluent/azure-mgmt-confluent/dev_requirements.txt b/sdk/confluent/azure-mgmt-confluent/dev_requirements.txt index 853026eb097d..02870f10dd95 100644 --- a/sdk/confluent/azure-mgmt-confluent/dev_requirements.txt +++ b/sdk/confluent/azure-mgmt-confluent/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource diff --git a/sdk/connectedcache/azure-mgmt-connectedcache/dev_requirements.txt b/sdk/connectedcache/azure-mgmt-connectedcache/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/connectedcache/azure-mgmt-connectedcache/dev_requirements.txt +++ b/sdk/connectedcache/azure-mgmt-connectedcache/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt b/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt +++ b/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/containerorchestratorruntime/azure-mgmt-containerorchestratorruntime/dev_requirements.txt b/sdk/containerorchestratorruntime/azure-mgmt-containerorchestratorruntime/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/containerorchestratorruntime/azure-mgmt-containerorchestratorruntime/dev_requirements.txt +++ b/sdk/containerorchestratorruntime/azure-mgmt-containerorchestratorruntime/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/containerregistry/azure-mgmt-containerregistry/dev_requirements.txt b/sdk/containerregistry/azure-mgmt-containerregistry/dev_requirements.txt index dcab81cb7721..d9f47e07cac2 100644 --- a/sdk/containerregistry/azure-mgmt-containerregistry/dev_requirements.txt +++ b/sdk/containerregistry/azure-mgmt-containerregistry/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../storage/azure-mgmt-storage +../../storage/azure-mgmt-storage azure-identity aiohttp \ No newline at end of file diff --git a/sdk/containerservice/azure-mgmt-containerservice/dev_requirements.txt b/sdk/containerservice/azure-mgmt-containerservice/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/containerservice/azure-mgmt-containerservice/dev_requirements.txt +++ b/sdk/containerservice/azure-mgmt-containerservice/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/containerservice/azure-mgmt-containerservicefleet/dev_requirements.txt b/sdk/containerservice/azure-mgmt-containerservicefleet/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/containerservice/azure-mgmt-containerservicefleet/dev_requirements.txt +++ b/sdk/containerservice/azure-mgmt-containerservicefleet/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/core/azure-common/dev_requirements.txt b/sdk/core/azure-common/dev_requirements.txt index 965f80cfbf8c..4841be83cac9 100644 --- a/sdk/core/azure-common/dev_requirements.txt +++ b/sdk/core/azure-common/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../azure-core +../azure-core msrestazure \ No newline at end of file diff --git a/sdk/cosmos/azure-cosmos/dev_requirements.txt b/sdk/cosmos/azure-cosmos/dev_requirements.txt index 82cfa079a8b1..b50acc3ddc52 100644 --- a/sdk/cosmos/azure-cosmos/dev_requirements.txt +++ b/sdk/cosmos/azure-cosmos/dev_requirements.txt @@ -1,4 +1,4 @@ aiohttp>=3.8.5,<=3.12.2 --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity -e ../../../eng/tools/azure-sdk-tools diff --git a/sdk/cosmosdbforpostgresql/azure-mgmt-cosmosdbforpostgresql/dev_requirements.txt b/sdk/cosmosdbforpostgresql/azure-mgmt-cosmosdbforpostgresql/dev_requirements.txt index 731391f73e3b..4935ec8e9d54 100644 --- a/sdk/cosmosdbforpostgresql/azure-mgmt-cosmosdbforpostgresql/dev_requirements.txt +++ b/sdk/cosmosdbforpostgresql/azure-mgmt-cosmosdbforpostgresql/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource \ No newline at end of file +../../identity/azure-identity +../../resources/azure-mgmt-resource \ No newline at end of file diff --git a/sdk/databasewatcher/azure-mgmt-databasewatcher/dev_requirements.txt b/sdk/databasewatcher/azure-mgmt-databasewatcher/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/databasewatcher/azure-mgmt-databasewatcher/dev_requirements.txt +++ b/sdk/databasewatcher/azure-mgmt-databasewatcher/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/databox/azure-mgmt-databox/dev_requirements.txt b/sdk/databox/azure-mgmt-databox/dev_requirements.txt index e61667f279ee..0a8d1282d521 100644 --- a/sdk/databox/azure-mgmt-databox/dev_requirements.txt +++ b/sdk/databox/azure-mgmt-databox/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/datafactory/azure-mgmt-datafactory/dev_requirements.txt b/sdk/datafactory/azure-mgmt-datafactory/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/datafactory/azure-mgmt-datafactory/dev_requirements.txt +++ b/sdk/datafactory/azure-mgmt-datafactory/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/datalake/azure-mgmt-datalake-analytics/dev_requirements.txt b/sdk/datalake/azure-mgmt-datalake-analytics/dev_requirements.txt index 6269988b3895..13a0dc095579 100644 --- a/sdk/datalake/azure-mgmt-datalake-analytics/dev_requirements.txt +++ b/sdk/datalake/azure-mgmt-datalake-analytics/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity azure-mgmt-resource<=21.1.0 \ No newline at end of file diff --git a/sdk/datamigration/azure-mgmt-datamigration/dev_requirements.txt b/sdk/datamigration/azure-mgmt-datamigration/dev_requirements.txt index b2b0572449a8..511b73ed953a 100644 --- a/sdk/datamigration/azure-mgmt-datamigration/dev_requirements.txt +++ b/sdk/datamigration/azure-mgmt-datamigration/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../network/azure-mgmt-network +../../network/azure-mgmt-network aiohttp diff --git a/sdk/dataprotection/azure-mgmt-dataprotection/dev_requirements.txt b/sdk/dataprotection/azure-mgmt-dataprotection/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/dataprotection/azure-mgmt-dataprotection/dev_requirements.txt +++ b/sdk/dataprotection/azure-mgmt-dataprotection/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/defendereasm/azure-mgmt-defendereasm/dev_requirements.txt b/sdk/defendereasm/azure-mgmt-defendereasm/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/defendereasm/azure-mgmt-defendereasm/dev_requirements.txt +++ b/sdk/defendereasm/azure-mgmt-defendereasm/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/dell/azure-mgmt-dellstorage/dev_requirements.txt b/sdk/dell/azure-mgmt-dellstorage/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/dell/azure-mgmt-dellstorage/dev_requirements.txt +++ b/sdk/dell/azure-mgmt-dellstorage/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/dependencymap/azure-mgmt-dependencymap/dev_requirements.txt b/sdk/dependencymap/azure-mgmt-dependencymap/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/dependencymap/azure-mgmt-dependencymap/dev_requirements.txt +++ b/sdk/dependencymap/azure-mgmt-dependencymap/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/devcenter/azure-mgmt-devcenter/dev_requirements.txt b/sdk/devcenter/azure-mgmt-devcenter/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/devcenter/azure-mgmt-devcenter/dev_requirements.txt +++ b/sdk/devcenter/azure-mgmt-devcenter/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/devhub/azure-mgmt-devhub/dev_requirements.txt b/sdk/devhub/azure-mgmt-devhub/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/devhub/azure-mgmt-devhub/dev_requirements.txt +++ b/sdk/devhub/azure-mgmt-devhub/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/deviceregistry/azure-mgmt-deviceregistry/dev_requirements.txt b/sdk/deviceregistry/azure-mgmt-deviceregistry/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/deviceregistry/azure-mgmt-deviceregistry/dev_requirements.txt +++ b/sdk/deviceregistry/azure-mgmt-deviceregistry/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/deviceupdate/azure-iot-deviceupdate/dev_requirements.txt b/sdk/deviceupdate/azure-iot-deviceupdate/dev_requirements.txt index 6a461a6042ef..2aae7f17a9a6 100644 --- a/sdk/deviceupdate/azure-iot-deviceupdate/dev_requirements.txt +++ b/sdk/deviceupdate/azure-iot-deviceupdate/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 diff --git a/sdk/devopsinfrastructure/azure-mgmt-devopsinfrastructure/dev_requirements.txt b/sdk/devopsinfrastructure/azure-mgmt-devopsinfrastructure/dev_requirements.txt index 9ae345aab155..a2d98257100f 100644 --- a/sdk/devopsinfrastructure/azure-mgmt-devopsinfrastructure/dev_requirements.txt +++ b/sdk/devopsinfrastructure/azure-mgmt-devopsinfrastructure/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../resources/azure-mgmt-resource +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/devtestlabs/azure-mgmt-devtestlabs/dev_requirements.txt b/sdk/devtestlabs/azure-mgmt-devtestlabs/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/devtestlabs/azure-mgmt-devtestlabs/dev_requirements.txt +++ b/sdk/devtestlabs/azure-mgmt-devtestlabs/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/digitaltwins/azure-digitaltwins-core/dev_requirements.txt b/sdk/digitaltwins/azure-digitaltwins-core/dev_requirements.txt index 2fccf969f8c0..9dc040972d26 100644 --- a/sdk/digitaltwins/azure-digitaltwins-core/dev_requirements.txt +++ b/sdk/digitaltwins/azure-digitaltwins-core/dev_requirements.txt @@ -1,7 +1,7 @@ ../../core/azure-core azure-mgmt-authorization azure-mgmt-digitaltwins --e ../../identity/azure-identity +../../identity/azure-identity -e ../../../eng/tools/azure-sdk-tools aiohttp>=3.0 ../../nspkg/azure-digitaltwins-nspkg \ No newline at end of file diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/dev_requirements.txt b/sdk/digitaltwins/azure-mgmt-digitaltwins/dev_requirements.txt index 1fd77689a23f..4180cbb7f70a 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/dev_requirements.txt +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../../resources/azure-mgmt-msi --e ../../resources/azure-mgmt-resource +../../identity/azure-identity +../../resources/azure-mgmt-msi +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/durabletask/azure-mgmt-durabletask/dev_requirements.txt b/sdk/durabletask/azure-mgmt-durabletask/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/durabletask/azure-mgmt-durabletask/dev_requirements.txt +++ b/sdk/durabletask/azure-mgmt-durabletask/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/edgeorder/azure-mgmt-edgeorder/dev_requirements.txt b/sdk/edgeorder/azure-mgmt-edgeorder/dev_requirements.txt index e61667f279ee..0a8d1282d521 100644 --- a/sdk/edgeorder/azure-mgmt-edgeorder/dev_requirements.txt +++ b/sdk/edgeorder/azure-mgmt-edgeorder/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/edgezones/azure-mgmt-edgezones/dev_requirements.txt b/sdk/edgezones/azure-mgmt-edgezones/dev_requirements.txt index 9ae345aab155..a2d98257100f 100644 --- a/sdk/edgezones/azure-mgmt-edgezones/dev_requirements.txt +++ b/sdk/edgezones/azure-mgmt-edgezones/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../resources/azure-mgmt-resource +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/elasticsan/azure-mgmt-elasticsan/dev_requirements.txt b/sdk/elasticsan/azure-mgmt-elasticsan/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/elasticsan/azure-mgmt-elasticsan/dev_requirements.txt +++ b/sdk/elasticsan/azure-mgmt-elasticsan/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/evaluation/azure-ai-evaluation/dev_requirements.txt b/sdk/evaluation/azure-ai-evaluation/dev_requirements.txt index 0c4b10439567..de4a368aea50 100644 --- a/sdk/evaluation/azure-ai-evaluation/dev_requirements.txt +++ b/sdk/evaluation/azure-ai-evaluation/dev_requirements.txt @@ -12,4 +12,4 @@ aiohttp filelock promptflow-core>=1.17.1 promptflow-devkit>=1.17.1 --e ../azure-ai-evaluation[redteam] +../azure-ai-evaluation[redteam] diff --git a/sdk/eventgrid/azure-eventgrid/dev_requirements.txt b/sdk/eventgrid/azure-eventgrid/dev_requirements.txt index 12a7e31245ff..db0eac072b34 100644 --- a/sdk/eventgrid/azure-eventgrid/dev_requirements.txt +++ b/sdk/eventgrid/azure-eventgrid/dev_requirements.txt @@ -1,8 +1,8 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity azure-mgmt-resource==22.0.0 --e ../azure-mgmt-eventgrid +../azure-mgmt-eventgrid azure-storage-queue cloudevents<=2.0.0; python_version >= "3.7" aiohttp>=3.0 diff --git a/sdk/eventgrid/azure-mgmt-eventgrid/dev_requirements.txt b/sdk/eventgrid/azure-mgmt-eventgrid/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/eventgrid/azure-mgmt-eventgrid/dev_requirements.txt +++ b/sdk/eventgrid/azure-mgmt-eventgrid/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/eventhub/azure-mgmt-eventhub/dev_requirements.txt b/sdk/eventhub/azure-mgmt-eventhub/dev_requirements.txt index 34facc48d189..9523b649ecfb 100644 --- a/sdk/eventhub/azure-mgmt-eventhub/dev_requirements.txt +++ b/sdk/eventhub/azure-mgmt-eventhub/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core +../../core/azure-core ../azure-eventhub azure-data-tables==12.2.0 aiohttp \ No newline at end of file diff --git a/sdk/extendedlocation/azure-mgmt-extendedlocation/dev_requirements.txt b/sdk/extendedlocation/azure-mgmt-extendedlocation/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/extendedlocation/azure-mgmt-extendedlocation/dev_requirements.txt +++ b/sdk/extendedlocation/azure-mgmt-extendedlocation/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/fabric/azure-mgmt-fabric/dev_requirements.txt b/sdk/fabric/azure-mgmt-fabric/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/fabric/azure-mgmt-fabric/dev_requirements.txt +++ b/sdk/fabric/azure-mgmt-fabric/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/dev_requirements.txt b/sdk/formrecognizer/azure-ai-formrecognizer/dev_requirements.txt index 06543e63230c..c6c61de0d536 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/dev_requirements.txt +++ b/sdk/formrecognizer/azure-ai-formrecognizer/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/graphservices/azure-mgmt-graphservices/dev_requirements.txt b/sdk/graphservices/azure-mgmt-graphservices/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/graphservices/azure-mgmt-graphservices/dev_requirements.txt +++ b/sdk/graphservices/azure-mgmt-graphservices/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/hardwaresecuritymodules/azure-mgmt-hardwaresecuritymodules/dev_requirements.txt b/sdk/hardwaresecuritymodules/azure-mgmt-hardwaresecuritymodules/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/hardwaresecuritymodules/azure-mgmt-hardwaresecuritymodules/dev_requirements.txt +++ b/sdk/hardwaresecuritymodules/azure-mgmt-hardwaresecuritymodules/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/hdinsight/azure-mgmt-hdinsight/dev_requirements.txt b/sdk/hdinsight/azure-mgmt-hdinsight/dev_requirements.txt index 28de0b640276..170c4eb5df12 100644 --- a/sdk/hdinsight/azure-mgmt-hdinsight/dev_requirements.txt +++ b/sdk/hdinsight/azure-mgmt-hdinsight/dev_requirements.txt @@ -1,9 +1,9 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../keyvault/azure-keyvault-keys --e ../../keyvault/azure-mgmt-keyvault --e ../../resources/azure-mgmt-resource --e ../../storage/azure-mgmt-storage +../../core/azure-core +../../keyvault/azure-keyvault-keys +../../keyvault/azure-mgmt-keyvault +../../resources/azure-mgmt-resource +../../storage/azure-mgmt-storage azure-mgmt-loganalytics==2.0.0 --e ../../resources/azure-mgmt-msi/ +../../resources/azure-mgmt-msi/ aiohttp \ No newline at end of file diff --git a/sdk/healthdataaiservices/azure-mgmt-healthdataaiservices/dev_requirements.txt b/sdk/healthdataaiservices/azure-mgmt-healthdataaiservices/dev_requirements.txt index 145c0e09d584..4a66c56eb861 100644 --- a/sdk/healthdataaiservices/azure-mgmt-healthdataaiservices/dev_requirements.txt +++ b/sdk/healthdataaiservices/azure-mgmt-healthdataaiservices/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../resources/azure-mgmt-resource +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/hybridcompute/azure-mgmt-hybridcompute/dev_requirements.txt b/sdk/hybridcompute/azure-mgmt-hybridcompute/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/hybridcompute/azure-mgmt-hybridcompute/dev_requirements.txt +++ b/sdk/hybridcompute/azure-mgmt-hybridcompute/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/hybridconnectivity/azure-mgmt-hybridconnectivity/dev_requirements.txt b/sdk/hybridconnectivity/azure-mgmt-hybridconnectivity/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/hybridconnectivity/azure-mgmt-hybridconnectivity/dev_requirements.txt +++ b/sdk/hybridconnectivity/azure-mgmt-hybridconnectivity/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/hybridcontainerservice/azure-mgmt-hybridcontainerservice/dev_requirements.txt b/sdk/hybridcontainerservice/azure-mgmt-hybridcontainerservice/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/hybridcontainerservice/azure-mgmt-hybridcontainerservice/dev_requirements.txt +++ b/sdk/hybridcontainerservice/azure-mgmt-hybridcontainerservice/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/hybridkubernetes/azure-mgmt-hybridkubernetes/dev_requirements.txt b/sdk/hybridkubernetes/azure-mgmt-hybridkubernetes/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/hybridkubernetes/azure-mgmt-hybridkubernetes/dev_requirements.txt +++ b/sdk/hybridkubernetes/azure-mgmt-hybridkubernetes/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/impactreporting/azure-mgmt-impactreporting/dev_requirements.txt b/sdk/impactreporting/azure-mgmt-impactreporting/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/impactreporting/azure-mgmt-impactreporting/dev_requirements.txt +++ b/sdk/impactreporting/azure-mgmt-impactreporting/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/informaticadatamanagement/azure-mgmt-informaticadatamanagement/dev_requirements.txt b/sdk/informaticadatamanagement/azure-mgmt-informaticadatamanagement/dev_requirements.txt index 145c0e09d584..4a66c56eb861 100644 --- a/sdk/informaticadatamanagement/azure-mgmt-informaticadatamanagement/dev_requirements.txt +++ b/sdk/informaticadatamanagement/azure-mgmt-informaticadatamanagement/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../resources/azure-mgmt-resource +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/iotfirmwaredefense/azure-mgmt-iotfirmwaredefense/dev_requirements.txt b/sdk/iotfirmwaredefense/azure-mgmt-iotfirmwaredefense/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/iotfirmwaredefense/azure-mgmt-iotfirmwaredefense/dev_requirements.txt +++ b/sdk/iotfirmwaredefense/azure-mgmt-iotfirmwaredefense/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/iothub/azure-iot-deviceprovisioning/dev_requirements.txt b/sdk/iothub/azure-iot-deviceprovisioning/dev_requirements.txt index 3a512b3216b3..3e9ed34f2d54 100644 --- a/sdk/iothub/azure-iot-deviceprovisioning/dev_requirements.txt +++ b/sdk/iothub/azure-iot-deviceprovisioning/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../core/azure-core aiohttp azure-iot-device diff --git a/sdk/iothub/azure-mgmt-iothub/dev_requirements.txt b/sdk/iothub/azure-mgmt-iothub/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/iothub/azure-mgmt-iothub/dev_requirements.txt +++ b/sdk/iothub/azure-mgmt-iothub/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/iotoperations/azure-mgmt-iotoperations/dev_requirements.txt b/sdk/iotoperations/azure-mgmt-iotoperations/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/iotoperations/azure-mgmt-iotoperations/dev_requirements.txt +++ b/sdk/iotoperations/azure-mgmt-iotoperations/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt b/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt index a0f77fe4aa33..5a42e3ef0a1b 100644 --- a/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt +++ b/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt @@ -1,7 +1,7 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../azure-keyvault-keys +../../core/azure-core +../../identity/azure-identity +../azure-keyvault-keys ../../nspkg/azure-keyvault-nspkg aiohttp>=3.0 azure-storage-blob==12.6.0 diff --git a/sdk/keyvault/azure-keyvault-certificates/dev_requirements.txt b/sdk/keyvault/azure-keyvault-certificates/dev_requirements.txt index 1cb45157c33f..b9e0c3fa837d 100644 --- a/sdk/keyvault/azure-keyvault-certificates/dev_requirements.txt +++ b/sdk/keyvault/azure-keyvault-certificates/dev_requirements.txt @@ -1,6 +1,6 @@ ../../core/azure-core -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../nspkg/azure-keyvault-nspkg aiohttp>=3.0 parameterized>=0.7.3 diff --git a/sdk/keyvault/azure-keyvault-secrets/dev_requirements.txt b/sdk/keyvault/azure-keyvault-secrets/dev_requirements.txt index e75279fdbb0d..33a0af44d452 100644 --- a/sdk/keyvault/azure-keyvault-secrets/dev_requirements.txt +++ b/sdk/keyvault/azure-keyvault-secrets/dev_requirements.txt @@ -1,5 +1,5 @@ ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity -e ../../../eng/tools/azure-sdk-tools ../../nspkg/azure-keyvault-nspkg aiohttp>=3.0 diff --git a/sdk/keyvault/azure-mgmt-keyvault/dev_requirements.txt b/sdk/keyvault/azure-mgmt-keyvault/dev_requirements.txt index 73ca229ca000..44d4d74db255 100644 --- a/sdk/keyvault/azure-mgmt-keyvault/dev_requirements.txt +++ b/sdk/keyvault/azure-mgmt-keyvault/dev_requirements.txt @@ -1,4 +1,4 @@ aiohttp>=3.0 -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensions/dev_requirements.txt b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensions/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensions/dev_requirements.txt +++ b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensions/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensiontypes/dev_requirements.txt b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensiontypes/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensiontypes/dev_requirements.txt +++ b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-extensiontypes/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-fluxconfigurations/dev_requirements.txt b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-fluxconfigurations/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-fluxconfigurations/dev_requirements.txt +++ b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-fluxconfigurations/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-privatelinkscopes/dev_requirements.txt b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-privatelinkscopes/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-privatelinkscopes/dev_requirements.txt +++ b/sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration-privatelinkscopes/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/lambdatesthyperexecute/azure-mgmt-lambdatesthyperexecute/dev_requirements.txt b/sdk/lambdatesthyperexecute/azure-mgmt-lambdatesthyperexecute/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/lambdatesthyperexecute/azure-mgmt-lambdatesthyperexecute/dev_requirements.txt +++ b/sdk/lambdatesthyperexecute/azure-mgmt-lambdatesthyperexecute/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/largeinstance/azure-mgmt-largeinstance/dev_requirements.txt b/sdk/largeinstance/azure-mgmt-largeinstance/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/largeinstance/azure-mgmt-largeinstance/dev_requirements.txt +++ b/sdk/largeinstance/azure-mgmt-largeinstance/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/loadtesting/azure-mgmt-loadtesting/dev_requirements.txt b/sdk/loadtesting/azure-mgmt-loadtesting/dev_requirements.txt index 28246caf0a17..4c1dba86cb33 100644 --- a/sdk/loadtesting/azure-mgmt-loadtesting/dev_requirements.txt +++ b/sdk/loadtesting/azure-mgmt-loadtesting/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-msi --e ../../identity/azure-identity +../../resources/azure-mgmt-msi +../../identity/azure-identity ../../keyvault/azure-mgmt-keyvault ../../keyvault/azure-keyvault-keys diff --git a/sdk/loganalytics/azure-mgmt-loganalytics/dev_requirements.txt b/sdk/loganalytics/azure-mgmt-loganalytics/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/loganalytics/azure-mgmt-loganalytics/dev_requirements.txt +++ b/sdk/loganalytics/azure-mgmt-loganalytics/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/logic/azure-mgmt-logic/dev_requirements.txt b/sdk/logic/azure-mgmt-logic/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/logic/azure-mgmt-logic/dev_requirements.txt +++ b/sdk/logic/azure-mgmt-logic/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/machinelearning/azure-mgmt-machinelearningservices/dev_requirements.txt b/sdk/machinelearning/azure-mgmt-machinelearningservices/dev_requirements.txt index 20ff417c02bd..518bc8c7ed3e 100644 --- a/sdk/machinelearning/azure-mgmt-machinelearningservices/dev_requirements.txt +++ b/sdk/machinelearning/azure-mgmt-machinelearningservices/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource \ No newline at end of file +../../resources/azure-mgmt-resource \ No newline at end of file diff --git a/sdk/managedapplications/azure-mgmt-managedapplications/dev_requirements.txt b/sdk/managedapplications/azure-mgmt-managedapplications/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/managedapplications/azure-mgmt-managedapplications/dev_requirements.txt +++ b/sdk/managedapplications/azure-mgmt-managedapplications/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/managednetworkfabric/azure-mgmt-managednetworkfabric/dev_requirements.txt b/sdk/managednetworkfabric/azure-mgmt-managednetworkfabric/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/managednetworkfabric/azure-mgmt-managednetworkfabric/dev_requirements.txt +++ b/sdk/managednetworkfabric/azure-mgmt-managednetworkfabric/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/maps/azure-maps-geolocation/dev_requirements.txt b/sdk/maps/azure-maps-geolocation/dev_requirements.txt index bc92292c3921..58d4669999ec 100644 --- a/sdk/maps/azure-maps-geolocation/dev_requirements.txt +++ b/sdk/maps/azure-maps-geolocation/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.8' \ No newline at end of file diff --git a/sdk/maps/azure-maps-render/dev_requirements.txt b/sdk/maps/azure-maps-render/dev_requirements.txt index bc92292c3921..58d4669999ec 100644 --- a/sdk/maps/azure-maps-render/dev_requirements.txt +++ b/sdk/maps/azure-maps-render/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.8' \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/dev_requirements.txt b/sdk/maps/azure-maps-route/dev_requirements.txt index bc92292c3921..58d4669999ec 100644 --- a/sdk/maps/azure-maps-route/dev_requirements.txt +++ b/sdk/maps/azure-maps-route/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.8' \ No newline at end of file diff --git a/sdk/maps/azure-maps-search/dev_requirements.txt b/sdk/maps/azure-maps-search/dev_requirements.txt index bc92292c3921..58d4669999ec 100644 --- a/sdk/maps/azure-maps-search/dev_requirements.txt +++ b/sdk/maps/azure-maps-search/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.8' \ No newline at end of file diff --git a/sdk/maps/azure-maps-timezone/dev_requirements.txt b/sdk/maps/azure-maps-timezone/dev_requirements.txt index 989b918a1950..a5a85f123bb5 100644 --- a/sdk/maps/azure-maps-timezone/dev_requirements.txt +++ b/sdk/maps/azure-maps-timezone/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.8' diff --git a/sdk/maps/azure-maps-weather/dev_requirements.txt b/sdk/maps/azure-maps-weather/dev_requirements.txt index bc92292c3921..58d4669999ec 100644 --- a/sdk/maps/azure-maps-weather/dev_requirements.txt +++ b/sdk/maps/azure-maps-weather/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.8' \ No newline at end of file diff --git a/sdk/marketplaceordering/azure-mgmt-marketplaceordering/dev_requirements.txt b/sdk/marketplaceordering/azure-mgmt-marketplaceordering/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/marketplaceordering/azure-mgmt-marketplaceordering/dev_requirements.txt +++ b/sdk/marketplaceordering/azure-mgmt-marketplaceordering/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/media/azure-mgmt-media/dev_requirements.txt b/sdk/media/azure-mgmt-media/dev_requirements.txt index b77a3dcef691..7fa092802b91 100644 --- a/sdk/media/azure-mgmt-media/dev_requirements.txt +++ b/sdk/media/azure-mgmt-media/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../storage/azure-mgmt-storage --e ../../resources/azure-mgmt-resource \ No newline at end of file +../../storage/azure-mgmt-storage +../../resources/azure-mgmt-resource \ No newline at end of file diff --git a/sdk/migrate/azure-mgmt-migrationassessment/dev_requirements.txt b/sdk/migrate/azure-mgmt-migrationassessment/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/migrate/azure-mgmt-migrationassessment/dev_requirements.txt +++ b/sdk/migrate/azure-mgmt-migrationassessment/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/migrationdiscovery/azure-mgmt-migrationdiscoverysap/dev_requirements.txt b/sdk/migrationdiscovery/azure-mgmt-migrationdiscoverysap/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/migrationdiscovery/azure-mgmt-migrationdiscoverysap/dev_requirements.txt +++ b/sdk/migrationdiscovery/azure-mgmt-migrationdiscoverysap/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/dev_requirements.txt b/sdk/mongocluster/azure-mgmt-mongocluster/dev_requirements.txt index 9babb5bf7a93..443f2aea4937 100644 --- a/sdk/mongocluster/azure-mgmt-mongocluster/dev_requirements.txt +++ b/sdk/mongocluster/azure-mgmt-mongocluster/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core --e ../../resources/azure-mgmt-resource +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/mongodbatlas/azure-mgmt-mongodbatlas/dev_requirements.txt b/sdk/mongodbatlas/azure-mgmt-mongodbatlas/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/mongodbatlas/azure-mgmt-mongodbatlas/dev_requirements.txt +++ b/sdk/mongodbatlas/azure-mgmt-mongodbatlas/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/monitor/azure-mgmt-monitor/dev_requirements.txt b/sdk/monitor/azure-mgmt-monitor/dev_requirements.txt index 90bb1bdc8f69..990711303cfc 100644 --- a/sdk/monitor/azure-mgmt-monitor/dev_requirements.txt +++ b/sdk/monitor/azure-mgmt-monitor/dev_requirements.txt @@ -1,12 +1,12 @@ -e ../../../eng/tools/azure-sdk-tools aiohttp>=3.0; python_version >= '3.5' --e ../../storage/azure-mgmt-storage --e ../../eventhub/azure-mgmt-eventhub +../../storage/azure-mgmt-storage +../../eventhub/azure-mgmt-eventhub azure-mgmt-loganalytics --e ../../appservice/azure-mgmt-web +../../appservice/azure-mgmt-web azure-mgmt-compute --e ../../network/azure-mgmt-network --e ../../applicationinsights/azure-mgmt-applicationinsights --e ../../logic/azure-mgmt-logic +../../network/azure-mgmt-network +../../applicationinsights/azure-mgmt-applicationinsights +../../logic/azure-mgmt-logic --e ../../identity/azure-identity \ No newline at end of file +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/monitor/azure-monitor-ingestion/dev_requirements.txt b/sdk/monitor/azure-monitor-ingestion/dev_requirements.txt index 14873106554f..9b07154dfb12 100644 --- a/sdk/monitor/azure-monitor-ingestion/dev_requirements.txt +++ b/sdk/monitor/azure-monitor-ingestion/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity aiohttp>=3.0 diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/dev_requirements.txt b/sdk/monitor/azure-monitor-opentelemetry-exporter/dev_requirements.txt index 5309592ff9cb..a8c945244621 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/dev_requirements.txt +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core ../../core/azure-core-tracing-opentelemetry --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0; python_version >= '3.7' fixedint<1.0.0,>=0.1.6 diff --git a/sdk/mysqlflexibleservers/azure-mgmt-mysqlflexibleservers/dev_requirements.txt b/sdk/mysqlflexibleservers/azure-mgmt-mysqlflexibleservers/dev_requirements.txt index 363b9b043307..a1e3befeac5f 100644 --- a/sdk/mysqlflexibleservers/azure-mgmt-mysqlflexibleservers/dev_requirements.txt +++ b/sdk/mysqlflexibleservers/azure-mgmt-mysqlflexibleservers/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity pytest-mock aiohttp \ No newline at end of file diff --git a/sdk/neonpostgres/azure-mgmt-neonpostgres/dev_requirements.txt b/sdk/neonpostgres/azure-mgmt-neonpostgres/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/neonpostgres/azure-mgmt-neonpostgres/dev_requirements.txt +++ b/sdk/neonpostgres/azure-mgmt-neonpostgres/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/netapp/azure-mgmt-netapp/dev_requirements.txt b/sdk/netapp/azure-mgmt-netapp/dev_requirements.txt index e1188ac06cb0..08cbd7f5f58f 100644 --- a/sdk/netapp/azure-mgmt-netapp/dev_requirements.txt +++ b/sdk/netapp/azure-mgmt-netapp/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../../sdk/identity/azure-identity --e ../../network/azure-mgmt-network --e ../../resources/azure-mgmt-resource +../../../sdk/identity/azure-identity +../../network/azure-mgmt-network +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/network/azure-mgmt-dns/dev_requirements.txt b/sdk/network/azure-mgmt-dns/dev_requirements.txt index 3096f31f1525..93bf0d2cfe66 100644 --- a/sdk/network/azure-mgmt-dns/dev_requirements.txt +++ b/sdk/network/azure-mgmt-dns/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../azure-mgmt-network --e ../../identity/azure-identity +../azure-mgmt-network +../../identity/azure-identity azure-mgmt-resource<=21.1.0 aiohttp \ No newline at end of file diff --git a/sdk/network/azure-mgmt-network/dev_requirements.txt b/sdk/network/azure-mgmt-network/dev_requirements.txt index 9caa16912d6f..9ebdc50b51ec 100644 --- a/sdk/network/azure-mgmt-network/dev_requirements.txt +++ b/sdk/network/azure-mgmt-network/dev_requirements.txt @@ -1,7 +1,7 @@ -e ../../../eng/tools/azure-sdk-tools aiohttp>=3.0; python_version >= '3.5' --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity azure-mgmt-compute==26.1.0 azure-mgmt-storage==20.0.0 azure-mgmt-privatedns==1.0.0 \ No newline at end of file diff --git a/sdk/networkanalytics/azure-mgmt-networkanalytics/dev_requirements.txt b/sdk/networkanalytics/azure-mgmt-networkanalytics/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/networkanalytics/azure-mgmt-networkanalytics/dev_requirements.txt +++ b/sdk/networkanalytics/azure-mgmt-networkanalytics/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/networkcloud/azure-mgmt-networkcloud/dev_requirements.txt b/sdk/networkcloud/azure-mgmt-networkcloud/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/networkcloud/azure-mgmt-networkcloud/dev_requirements.txt +++ b/sdk/networkcloud/azure-mgmt-networkcloud/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/networkfunction/azure-mgmt-networkfunction/dev_requirements.txt b/sdk/networkfunction/azure-mgmt-networkfunction/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/networkfunction/azure-mgmt-networkfunction/dev_requirements.txt +++ b/sdk/networkfunction/azure-mgmt-networkfunction/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/newrelicobservability/azure-mgmt-newrelicobservability/dev_requirements.txt b/sdk/newrelicobservability/azure-mgmt-newrelicobservability/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/newrelicobservability/azure-mgmt-newrelicobservability/dev_requirements.txt +++ b/sdk/newrelicobservability/azure-mgmt-newrelicobservability/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/nginx/azure-mgmt-nginx/dev_requirements.txt b/sdk/nginx/azure-mgmt-nginx/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/nginx/azure-mgmt-nginx/dev_requirements.txt +++ b/sdk/nginx/azure-mgmt-nginx/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/notificationhubs/azure-mgmt-notificationhubs/dev_requirements.txt b/sdk/notificationhubs/azure-mgmt-notificationhubs/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/notificationhubs/azure-mgmt-notificationhubs/dev_requirements.txt +++ b/sdk/notificationhubs/azure-mgmt-notificationhubs/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/onlineexperimentation/azure-mgmt-onlineexperimentation/dev_requirements.txt b/sdk/onlineexperimentation/azure-mgmt-onlineexperimentation/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/onlineexperimentation/azure-mgmt-onlineexperimentation/dev_requirements.txt +++ b/sdk/onlineexperimentation/azure-mgmt-onlineexperimentation/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/oracledatabase/azure-mgmt-oracledatabase/dev_requirements.txt b/sdk/oracledatabase/azure-mgmt-oracledatabase/dev_requirements.txt index 140277587710..ea5bfc44d77a 100644 --- a/sdk/oracledatabase/azure-mgmt-oracledatabase/dev_requirements.txt +++ b/sdk/oracledatabase/azure-mgmt-oracledatabase/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource +../../identity/azure-identity +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/dev_requirements.txt b/sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/dev_requirements.txt +++ b/sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/peering/azure-mgmt-peering/dev_requirements.txt b/sdk/peering/azure-mgmt-peering/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/peering/azure-mgmt-peering/dev_requirements.txt +++ b/sdk/peering/azure-mgmt-peering/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/personalizer/azure-ai-personalizer/dev_requirements.txt b/sdk/personalizer/azure-ai-personalizer/dev_requirements.txt index 06543e63230c..c6c61de0d536 100644 --- a/sdk/personalizer/azure-ai-personalizer/dev_requirements.txt +++ b/sdk/personalizer/azure-ai-personalizer/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/pineconevectordb/azure-mgmt-pineconevectordb/dev_requirements.txt b/sdk/pineconevectordb/azure-mgmt-pineconevectordb/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/pineconevectordb/azure-mgmt-pineconevectordb/dev_requirements.txt +++ b/sdk/pineconevectordb/azure-mgmt-pineconevectordb/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/planetarycomputer/azure-mgmt-planetarycomputer/dev_requirements.txt b/sdk/planetarycomputer/azure-mgmt-planetarycomputer/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/planetarycomputer/azure-mgmt-planetarycomputer/dev_requirements.txt +++ b/sdk/planetarycomputer/azure-mgmt-planetarycomputer/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/playwrighttesting/azure-mgmt-playwrighttesting/dev_requirements.txt b/sdk/playwrighttesting/azure-mgmt-playwrighttesting/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/playwrighttesting/azure-mgmt-playwrighttesting/dev_requirements.txt +++ b/sdk/playwrighttesting/azure-mgmt-playwrighttesting/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/portalservices/azure-mgmt-portalservicescopilot/dev_requirements.txt b/sdk/portalservices/azure-mgmt-portalservicescopilot/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/portalservices/azure-mgmt-portalservicescopilot/dev_requirements.txt +++ b/sdk/portalservices/azure-mgmt-portalservicescopilot/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/postgresqlflexibleservers/azure-mgmt-postgresqlflexibleservers/dev_requirements.txt b/sdk/postgresqlflexibleservers/azure-mgmt-postgresqlflexibleservers/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/postgresqlflexibleservers/azure-mgmt-postgresqlflexibleservers/dev_requirements.txt +++ b/sdk/postgresqlflexibleservers/azure-mgmt-postgresqlflexibleservers/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/purestorageblock/azure-mgmt-purestorageblock/dev_requirements.txt b/sdk/purestorageblock/azure-mgmt-purestorageblock/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/purestorageblock/azure-mgmt-purestorageblock/dev_requirements.txt +++ b/sdk/purestorageblock/azure-mgmt-purestorageblock/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/purview/azure-purview-administration/dev_requirements.txt b/sdk/purview/azure-purview-administration/dev_requirements.txt index 877f1a961d54..812d4654cc0e 100644 --- a/sdk/purview/azure-purview-administration/dev_requirements.txt +++ b/sdk/purview/azure-purview-administration/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../nspkg/azure-purview-nspkg aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/purview/azure-purview-catalog/dev_requirements.txt b/sdk/purview/azure-purview-catalog/dev_requirements.txt index 7e6a8b9938e7..82cb5eb23419 100644 --- a/sdk/purview/azure-purview-catalog/dev_requirements.txt +++ b/sdk/purview/azure-purview-catalog/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/purview/azure-purview-scanning/dev_requirements.txt b/sdk/purview/azure-purview-scanning/dev_requirements.txt index 877f1a961d54..812d4654cc0e 100644 --- a/sdk/purview/azure-purview-scanning/dev_requirements.txt +++ b/sdk/purview/azure-purview-scanning/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../nspkg/azure-purview-nspkg aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/purview/azure-purview-sharing/dev_requirements.txt b/sdk/purview/azure-purview-sharing/dev_requirements.txt index 877f1a961d54..812d4654cc0e 100644 --- a/sdk/purview/azure-purview-sharing/dev_requirements.txt +++ b/sdk/purview/azure-purview-sharing/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity ../../nspkg/azure-purview-nspkg aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/quantum/azure-mgmt-quantum/dev_requirements.txt b/sdk/quantum/azure-mgmt-quantum/dev_requirements.txt index 853026eb097d..02870f10dd95 100644 --- a/sdk/quantum/azure-mgmt-quantum/dev_requirements.txt +++ b/sdk/quantum/azure-mgmt-quantum/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource diff --git a/sdk/qumulo/azure-mgmt-qumulo/dev_requirements.txt b/sdk/qumulo/azure-mgmt-qumulo/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/qumulo/azure-mgmt-qumulo/dev_requirements.txt +++ b/sdk/qumulo/azure-mgmt-qumulo/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/recoveryservices/azure-mgmt-recoveryservices/dev_requirements.txt b/sdk/recoveryservices/azure-mgmt-recoveryservices/dev_requirements.txt index a3b630dc9903..a2789e665096 100644 --- a/sdk/recoveryservices/azure-mgmt-recoveryservices/dev_requirements.txt +++ b/sdk/recoveryservices/azure-mgmt-recoveryservices/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource requests aiohttp \ No newline at end of file diff --git a/sdk/recoveryservices/azure-mgmt-recoveryservicessiterecovery/dev_requirements.txt b/sdk/recoveryservices/azure-mgmt-recoveryservicessiterecovery/dev_requirements.txt index 17cbfebeed05..7b8ae89f1079 100644 --- a/sdk/recoveryservices/azure-mgmt-recoveryservicessiterecovery/dev_requirements.txt +++ b/sdk/recoveryservices/azure-mgmt-recoveryservicessiterecovery/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools requests --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/recoveryservicesdatareplication/azure-mgmt-recoveryservicesdatareplication/dev_requirements.txt b/sdk/recoveryservicesdatareplication/azure-mgmt-recoveryservicesdatareplication/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/recoveryservicesdatareplication/azure-mgmt-recoveryservicesdatareplication/dev_requirements.txt +++ b/sdk/recoveryservicesdatareplication/azure-mgmt-recoveryservicesdatareplication/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/dev_requirements.txt b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/dev_requirements.txt +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/redis/azure-mgmt-redis/dev_requirements.txt b/sdk/redis/azure-mgmt-redis/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/redis/azure-mgmt-redis/dev_requirements.txt +++ b/sdk/redis/azure-mgmt-redis/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/relay/azure-mgmt-relay/dev_requirements.txt b/sdk/relay/azure-mgmt-relay/dev_requirements.txt index ea044d41bcd5..f802d9f73053 100644 --- a/sdk/relay/azure-mgmt-relay/dev_requirements.txt +++ b/sdk/relay/azure-mgmt-relay/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity \ No newline at end of file +../../resources/azure-mgmt-resource +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/remoterendering/azure-mixedreality-remoterendering/dev_requirements.txt b/sdk/remoterendering/azure-mixedreality-remoterendering/dev_requirements.txt index d183dd30d80e..078b40b46c40 100644 --- a/sdk/remoterendering/azure-mixedreality-remoterendering/dev_requirements.txt +++ b/sdk/remoterendering/azure-mixedreality-remoterendering/dev_requirements.txt @@ -2,5 +2,5 @@ ../../core/azure-core ../../mixedreality/azure-mixedreality-authentication aiohttp>=3.0 --e ../../identity/azure-identity +../../identity/azure-identity configargparse diff --git a/sdk/resourcehealth/azure-mgmt-resourcehealth/dev_requirements.txt b/sdk/resourcehealth/azure-mgmt-resourcehealth/dev_requirements.txt index e61667f279ee..0a8d1282d521 100644 --- a/sdk/resourcehealth/azure-mgmt-resourcehealth/dev_requirements.txt +++ b/sdk/resourcehealth/azure-mgmt-resourcehealth/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp diff --git a/sdk/resources/azure-mgmt-resource-deployments/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-deployments/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/resources/azure-mgmt-resource-deployments/dev_requirements.txt +++ b/sdk/resources/azure-mgmt-resource-deployments/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/resources/azure-mgmt-resource-deploymentscripts/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-deploymentscripts/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/resources/azure-mgmt-resource-deploymentscripts/dev_requirements.txt +++ b/sdk/resources/azure-mgmt-resource-deploymentscripts/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/resources/azure-mgmt-resource-deploymentstacks/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-deploymentstacks/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/resources/azure-mgmt-resource-deploymentstacks/dev_requirements.txt +++ b/sdk/resources/azure-mgmt-resource-deploymentstacks/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/resources/azure-mgmt-resource-templatespecs/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-templatespecs/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/resources/azure-mgmt-resource-templatespecs/dev_requirements.txt +++ b/sdk/resources/azure-mgmt-resource-templatespecs/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/schemaregistry/azure-schemaregistry-avroencoder/dev_requirements.txt b/sdk/schemaregistry/azure-schemaregistry-avroencoder/dev_requirements.txt index 403c3377816d..74b51e9f1061 100644 --- a/sdk/schemaregistry/azure-schemaregistry-avroencoder/dev_requirements.txt +++ b/sdk/schemaregistry/azure-schemaregistry-avroencoder/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 azure-schemaregistry diff --git a/sdk/schemaregistry/azure-schemaregistry/dev_requirements.txt b/sdk/schemaregistry/azure-schemaregistry/dev_requirements.txt index 972944c11e1f..31d6ed3a1294 100644 --- a/sdk/schemaregistry/azure-schemaregistry/dev_requirements.txt +++ b/sdk/schemaregistry/azure-schemaregistry/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core +../../core/azure-core azure-identity==1.17.0 jsonschema>=4.10.3 aiohttp>=3.0 diff --git a/sdk/scvmm/azure-mgmt-scvmm/dev_requirements.txt b/sdk/scvmm/azure-mgmt-scvmm/dev_requirements.txt index 20ff417c02bd..518bc8c7ed3e 100644 --- a/sdk/scvmm/azure-mgmt-scvmm/dev_requirements.txt +++ b/sdk/scvmm/azure-mgmt-scvmm/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource \ No newline at end of file +../../resources/azure-mgmt-resource \ No newline at end of file diff --git a/sdk/search/azure-mgmt-search/dev_requirements.txt b/sdk/search/azure-mgmt-search/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/search/azure-mgmt-search/dev_requirements.txt +++ b/sdk/search/azure-mgmt-search/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/secretsstoreextension/azure-mgmt-secretsstoreextension/dev_requirements.txt b/sdk/secretsstoreextension/azure-mgmt-secretsstoreextension/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/secretsstoreextension/azure-mgmt-secretsstoreextension/dev_requirements.txt +++ b/sdk/secretsstoreextension/azure-mgmt-secretsstoreextension/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/securitydevops/azure-mgmt-securitydevops/dev_requirements.txt b/sdk/securitydevops/azure-mgmt-securitydevops/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/securitydevops/azure-mgmt-securitydevops/dev_requirements.txt +++ b/sdk/securitydevops/azure-mgmt-securitydevops/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/dev_requirements.txt b/sdk/selfhelp/azure-mgmt-selfhelp/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/dev_requirements.txt +++ b/sdk/selfhelp/azure-mgmt-selfhelp/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/servicebus/azure-mgmt-servicebus/dev_requirements.txt b/sdk/servicebus/azure-mgmt-servicebus/dev_requirements.txt index c6c49ae74ebd..2e3da863badd 100644 --- a/sdk/servicebus/azure-mgmt-servicebus/dev_requirements.txt +++ b/sdk/servicebus/azure-mgmt-servicebus/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/servicebus/azure-servicebus/dev_requirements.txt b/sdk/servicebus/azure-servicebus/dev_requirements.txt index 07b18eebf10d..43a5c4f0bedf 100644 --- a/sdk/servicebus/azure-servicebus/dev_requirements.txt +++ b/sdk/servicebus/azure-servicebus/dev_requirements.txt @@ -1,4 +1,4 @@ --e ../../core/azure-core +../../core/azure-core azure-identity~=1.17.0 -e ../../../eng/tools/azure-sdk-tools azure-mgmt-servicebus~=8.0.0 diff --git a/sdk/servicefabricmanagedclusters/azure-mgmt-servicefabricmanagedclusters/dev_requirements.txt b/sdk/servicefabricmanagedclusters/azure-mgmt-servicefabricmanagedclusters/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/servicefabricmanagedclusters/azure-mgmt-servicefabricmanagedclusters/dev_requirements.txt +++ b/sdk/servicefabricmanagedclusters/azure-mgmt-servicefabricmanagedclusters/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/servicelinker/azure-mgmt-servicelinker/dev_requirements.txt b/sdk/servicelinker/azure-mgmt-servicelinker/dev_requirements.txt index 8d28c99cdf65..dafc8467ecc2 100644 --- a/sdk/servicelinker/azure-mgmt-servicelinker/dev_requirements.txt +++ b/sdk/servicelinker/azure-mgmt-servicelinker/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/servicenetworking/azure-mgmt-servicenetworking/dev_requirements.txt b/sdk/servicenetworking/azure-mgmt-servicenetworking/dev_requirements.txt index bb03d6c61439..a248c967d56c 100644 --- a/sdk/servicenetworking/azure-mgmt-servicenetworking/dev_requirements.txt +++ b/sdk/servicenetworking/azure-mgmt-servicenetworking/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource +../../identity/azure-identity +../../resources/azure-mgmt-resource aiohttp \ No newline at end of file diff --git a/sdk/sitemanager/azure-mgmt-sitemanager/dev_requirements.txt b/sdk/sitemanager/azure-mgmt-sitemanager/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/sitemanager/azure-mgmt-sitemanager/dev_requirements.txt +++ b/sdk/sitemanager/azure-mgmt-sitemanager/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/sphere/azure-mgmt-sphere/dev_requirements.txt b/sdk/sphere/azure-mgmt-sphere/dev_requirements.txt index 5944a9bd9ea7..a3da85aa0ecd 100644 --- a/sdk/sphere/azure-mgmt-sphere/dev_requirements.txt +++ b/sdk/sphere/azure-mgmt-sphere/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity --e ../../resources/azure-mgmt-resource +../../identity/azure-identity +../../resources/azure-mgmt-resource diff --git a/sdk/springappdiscovery/azure-mgmt-springappdiscovery/dev_requirements.txt b/sdk/springappdiscovery/azure-mgmt-springappdiscovery/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/springappdiscovery/azure-mgmt-springappdiscovery/dev_requirements.txt +++ b/sdk/springappdiscovery/azure-mgmt-springappdiscovery/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/sql/azure-mgmt-sql/dev_requirements.txt b/sdk/sql/azure-mgmt-sql/dev_requirements.txt index 564ac1b9c87f..d6181f7461db 100644 --- a/sdk/sql/azure-mgmt-sql/dev_requirements.txt +++ b/sdk/sql/azure-mgmt-sql/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../resources/azure-mgmt-resource --e ../../identity/azure-identity +../../resources/azure-mgmt-resource +../../identity/azure-identity aiohttp diff --git a/sdk/standbypool/azure-mgmt-standbypool/dev_requirements.txt b/sdk/standbypool/azure-mgmt-standbypool/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/standbypool/azure-mgmt-standbypool/dev_requirements.txt +++ b/sdk/standbypool/azure-mgmt-standbypool/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/storage/azure-mgmt-storage/dev_requirements.txt b/sdk/storage/azure-mgmt-storage/dev_requirements.txt index cf48adcd5737..49bcac30e6dd 100644 --- a/sdk/storage/azure-mgmt-storage/dev_requirements.txt +++ b/sdk/storage/azure-mgmt-storage/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools aiohttp>=3.0; python_version >= '3.5' azure-mgmt-network==19.0.0 --e ../../resources/azure-mgmt-resource \ No newline at end of file +../../resources/azure-mgmt-resource \ No newline at end of file diff --git a/sdk/storage/azure-mgmt-storagesync/dev_requirements.txt b/sdk/storage/azure-mgmt-storagesync/dev_requirements.txt index 82829b518c04..945f821bef64 100644 --- a/sdk/storage/azure-mgmt-storagesync/dev_requirements.txt +++ b/sdk/storage/azure-mgmt-storagesync/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-mgmt-core --e ../../core/azure-core \ No newline at end of file +../../core/azure-mgmt-core +../../core/azure-core \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob-changefeed/dev_requirements.txt b/sdk/storage/azure-storage-blob-changefeed/dev_requirements.txt index ef31e80b2815..fdbe1f812c3e 100644 --- a/sdk/storage/azure-storage-blob-changefeed/dev_requirements.txt +++ b/sdk/storage/azure-storage-blob-changefeed/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../azure-storage-blob +../../core/azure-core +../../identity/azure-identity +../azure-storage-blob aiohttp>=3.0 cryptography==44.0.3 # TODO: Pinned due to cryptography compatibility issue in CI. Revisit once resolved. diff --git a/sdk/storage/azure-storage-blob/dev_requirements.txt b/sdk/storage/azure-storage-blob/dev_requirements.txt index 59b2a0246bce..de5100414c4c 100644 --- a/sdk/storage/azure-storage-blob/dev_requirements.txt +++ b/sdk/storage/azure-storage-blob/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity azure-mgmt-storage==20.1.0 aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/storage/azure-storage-file-datalake/dev_requirements.txt b/sdk/storage/azure-storage-file-datalake/dev_requirements.txt index 28dacba7b2e5..0320c5f673ca 100644 --- a/sdk/storage/azure-storage-file-datalake/dev_requirements.txt +++ b/sdk/storage/azure-storage-file-datalake/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../azure-storage-blob +../../core/azure-core +../../identity/azure-identity +../azure-storage-blob aiohttp>=3.0 diff --git a/sdk/storage/azure-storage-file-share/dev_requirements.txt b/sdk/storage/azure-storage-file-share/dev_requirements.txt index 28dacba7b2e5..0320c5f673ca 100644 --- a/sdk/storage/azure-storage-file-share/dev_requirements.txt +++ b/sdk/storage/azure-storage-file-share/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../azure-storage-blob +../../core/azure-core +../../identity/azure-identity +../azure-storage-blob aiohttp>=3.0 diff --git a/sdk/storage/azure-storage-queue/dev_requirements.txt b/sdk/storage/azure-storage-queue/dev_requirements.txt index 8b9f66470236..5d13b39709f6 100644 --- a/sdk/storage/azure-storage-queue/dev_requirements.txt +++ b/sdk/storage/azure-storage-queue/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity azure-mgmt-storage==20.1.0 aiohttp>=3.0 diff --git a/sdk/storageactions/azure-mgmt-storageactions/dev_requirements.txt b/sdk/storageactions/azure-mgmt-storageactions/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/storageactions/azure-mgmt-storageactions/dev_requirements.txt +++ b/sdk/storageactions/azure-mgmt-storageactions/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/storagemover/azure-mgmt-storagemover/dev_requirements.txt b/sdk/storagemover/azure-mgmt-storagemover/dev_requirements.txt index 8e0ca828ce26..03dba171e250 100644 --- a/sdk/storagemover/azure-mgmt-storagemover/dev_requirements.txt +++ b/sdk/storagemover/azure-mgmt-storagemover/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp diff --git a/sdk/streamanalytics/azure-mgmt-streamanalytics/dev_requirements.txt b/sdk/streamanalytics/azure-mgmt-streamanalytics/dev_requirements.txt index bf320ddc6af1..17e43ec54f41 100644 --- a/sdk/streamanalytics/azure-mgmt-streamanalytics/dev_requirements.txt +++ b/sdk/streamanalytics/azure-mgmt-streamanalytics/dev_requirements.txt @@ -1,3 +1,3 @@ aiohttp>=3.0; python_version >= '3.5' -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity \ No newline at end of file +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/synapse/azure-synapse-artifacts/dev_requirements.txt b/sdk/synapse/azure-synapse-artifacts/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/synapse/azure-synapse-artifacts/dev_requirements.txt +++ b/sdk/synapse/azure-synapse-artifacts/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/terraform/azure-mgmt-terraform/dev_requirements.txt b/sdk/terraform/azure-mgmt-terraform/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/terraform/azure-mgmt-terraform/dev_requirements.txt +++ b/sdk/terraform/azure-mgmt-terraform/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/testbase/azure-mgmt-testbase/dev_requirements.txt b/sdk/testbase/azure-mgmt-testbase/dev_requirements.txt index ab6cd9c7ce39..0b3af944d4fe 100644 --- a/sdk/testbase/azure-mgmt-testbase/dev_requirements.txt +++ b/sdk/testbase/azure-mgmt-testbase/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity \ No newline at end of file +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/dev_requirements.txt b/sdk/textanalytics/azure-ai-textanalytics/dev_requirements.txt index d85e980ba5ab..9b07154dfb12 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/dev_requirements.txt +++ b/sdk/textanalytics/azure-ai-textanalytics/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 diff --git a/sdk/translation/azure-ai-translation-document/dev_requirements.txt b/sdk/translation/azure-ai-translation-document/dev_requirements.txt index d9d342a7a6db..89ea9479a1e4 100644 --- a/sdk/translation/azure-ai-translation-document/dev_requirements.txt +++ b/sdk/translation/azure-ai-translation-document/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core azure-storage-blob==12.9.0 --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 pytz diff --git a/sdk/translation/azure-ai-translation-text/dev_requirements.txt b/sdk/translation/azure-ai-translation-text/dev_requirements.txt index 663226ebe334..27462ab2e069 100644 --- a/sdk/translation/azure-ai-translation-text/dev_requirements.txt +++ b/sdk/translation/azure-ai-translation-text/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity +../../core/azure-core +../../identity/azure-identity msrestazure aiohttp>=3.0 \ No newline at end of file diff --git a/sdk/trustedsigning/azure-mgmt-trustedsigning/dev_requirements.txt b/sdk/trustedsigning/azure-mgmt-trustedsigning/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/trustedsigning/azure-mgmt-trustedsigning/dev_requirements.txt +++ b/sdk/trustedsigning/azure-mgmt-trustedsigning/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/videoanalyzer/azure-media-videoanalyzer-edge/dev_requirements.txt b/sdk/videoanalyzer/azure-media-videoanalyzer-edge/dev_requirements.txt index 907b3c023a58..0266bf6586ee 100644 --- a/sdk/videoanalyzer/azure-media-videoanalyzer-edge/dev_requirements.txt +++ b/sdk/videoanalyzer/azure-media-videoanalyzer-edge/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core --e ../../identity/azure-identity +../../identity/azure-identity aiohttp>=3.0 aiodns>=2.0 diff --git a/sdk/voiceservices/azure-mgmt-voiceservices/dev_requirements.txt b/sdk/voiceservices/azure-mgmt-voiceservices/dev_requirements.txt index 3d4691d0e417..4a746c21163c 100644 --- a/sdk/voiceservices/azure-mgmt-voiceservices/dev_requirements.txt +++ b/sdk/voiceservices/azure-mgmt-voiceservices/dev_requirements.txt @@ -1,2 +1,2 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity diff --git a/sdk/webpubsub/azure-mgmt-webpubsub/dev_requirements.txt b/sdk/webpubsub/azure-mgmt-webpubsub/dev_requirements.txt index 144a72d434c4..21cc05c69feb 100644 --- a/sdk/webpubsub/azure-mgmt-webpubsub/dev_requirements.txt +++ b/sdk/webpubsub/azure-mgmt-webpubsub/dev_requirements.txt @@ -1,3 +1,3 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity aiohttp \ No newline at end of file diff --git a/sdk/weightsandbiases/azure-mgmt-weightsandbiases/dev_requirements.txt b/sdk/weightsandbiases/azure-mgmt-weightsandbiases/dev_requirements.txt index b64e417f58cc..ece056fe0984 100644 --- a/sdk/weightsandbiases/azure-mgmt-weightsandbiases/dev_requirements.txt +++ b/sdk/weightsandbiases/azure-mgmt-weightsandbiases/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../core/azure-core --e ../../identity/azure-identity --e ../../core/azure-mgmt-core +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core aiohttp \ No newline at end of file diff --git a/sdk/workloads/azure-mgmt-workloadssapvirtualinstance/dev_requirements.txt b/sdk/workloads/azure-mgmt-workloadssapvirtualinstance/dev_requirements.txt index 04152404db48..9a31d1958a64 100644 --- a/sdk/workloads/azure-mgmt-workloadssapvirtualinstance/dev_requirements.txt +++ b/sdk/workloads/azure-mgmt-workloadssapvirtualinstance/dev_requirements.txt @@ -1,5 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools --e ../../identity/azure-identity +../../identity/azure-identity azure-mgmt-msi azure-mgmt-authorization azure-mgmt-network From 7d26b949a81274fac6f1eea41a0a554b8b8b6c77 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 3 Feb 2026 01:14:33 +0000 Subject: [PATCH 24/84] Guard NodeLogManager against recursive stdout/stderr forwarding (#44844) * Initial plan * fix: avoid recursive stdout/stderr forwarding in evaluation logging Co-authored-by: nagkumar91 <4727422+nagkumar91@users.noreply.github.com> * fix: refine log writer test and recursion guard Co-authored-by: nagkumar91 <4727422+nagkumar91@users.noreply.github.com> * fix: align recursion guard typing with Set Co-authored-by: nagkumar91 <4727422+nagkumar91@users.noreply.github.com> * fix: address pylint line-too-long and protected-access warnings - Break long ternary expressions in NodeLogManager.__init__ into multi-line if/else blocks to stay under 100 char limit - Add pylint disable comment for protected-access on _prev_out which is accessed within the same class during unwrapping * Update test (#44868) * Update CHANGELOG.md --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: nagkumar91 <4727422+nagkumar91@users.noreply.github.com> Co-authored-by: Nagkumar Arkalgud Co-authored-by: Nagkumar Arkalgud Co-authored-by: Wenxing Zhu --- .../azure-ai-evaluation/CHANGELOG.md | 6 +++ .../ai/evaluation/_legacy/_common/_logging.py | 29 +++++++++++-- .../tests/unittests/test_logging.py | 42 +++++++++++++++++++ 3 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 sdk/evaluation/azure-ai-evaluation/tests/unittests/test_logging.py diff --git a/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md b/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md index 89cb46d005a9..3b63dc81ae57 100644 --- a/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md +++ b/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 1.15.0 (Unreleased) + +### Bugs Fixed + +- Prevent recursive stdout/stderr forwarding when NodeLogManager is nested, avoiding RecursionError in concurrent evaluation runs. + ## 1.14.0 (2026-01-05) ### Bugs Fixed diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_legacy/_common/_logging.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_legacy/_common/_logging.py index 9d6a5507aaf9..9851b7e6136a 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_legacy/_common/_logging.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_legacy/_common/_logging.py @@ -171,8 +171,14 @@ class NodeLogManager: """ def __init__(self, record_datetime: bool = True): - self.stdout_logger = NodeLogWriter(sys.stdout, record_datetime) - self.stderr_logger = NodeLogWriter(sys.stderr, record_datetime, is_stderr=True) + if isinstance(sys.stdout, NodeLogWriter): + self.stdout_logger = sys.stdout + else: + self.stdout_logger = NodeLogWriter(sys.stdout, record_datetime) + if isinstance(sys.stderr, NodeLogWriter): + self.stderr_logger = sys.stderr + else: + self.stderr_logger = NodeLogWriter(sys.stderr, record_datetime, is_stderr=True) def __enter__(self) -> "NodeLogManager": """Replace sys.stdout and sys.stderr with NodeLogWriter.""" @@ -215,6 +221,7 @@ def __init__(self, prev_stdout: Union[TextIOBase, Any], record_datetime: bool = self._prev_out: Union[TextIOBase, Any] = prev_stdout self._record_datetime: bool = record_datetime self._is_stderr: bool = is_stderr + self._fallback_out: Optional[TextIOBase] = sys.__stderr__ if is_stderr else sys.__stdout__ def set_node_info(self, run_id: str, node_name: str, line_number: int) -> None: """Set node info to a context variable. @@ -252,7 +259,8 @@ def write(self, s: str) -> int: log_info: Optional[NodeInfo] = self._context.get() s = scrub_credentials(s) # Remove credential from string. if log_info is None: - return self._prev_out.write(s) + out = self._resolve_prev_out() + return out.write(s) if out is not None else 0 else: self._write_to_flow_log(log_info, s) stdout: Optional[StringIO] = self.run_id_to_stdout.get(log_info.run_id) @@ -270,12 +278,25 @@ def flush(self): """Override TextIO's flush method.""" node_info: Optional[NodeInfo] = self._context.get() if node_info is None: - self._prev_out.flush() + out = self._resolve_prev_out() + if out is not None: + out.flush() else: string_io = self.run_id_to_stdout.get(node_info.run_id) if string_io is not None: string_io.flush() + def _resolve_prev_out(self) -> Optional[TextIOBase]: + current = self._prev_out + visited: Set[int] = set() + while isinstance(current, NodeLogWriter): + current_id = id(current) + if current_id in visited: + return self._fallback_out + visited.add(current_id) + current = current._prev_out # pylint: disable=protected-access + return current if current is not None else self._fallback_out + def _write_to_flow_log(self, log_info: NodeInfo, s: str): """Save stdout log to flow_logger and stderr log to logger.""" # If user uses "print('log message.')" to log, then diff --git a/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_logging.py b/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_logging.py new file mode 100644 index 000000000000..d190cfe97780 --- /dev/null +++ b/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_logging.py @@ -0,0 +1,42 @@ +import sys +from contextlib import ExitStack +from io import StringIO + +import pytest + +from azure.ai.evaluation._legacy._common._logging import NodeLogManager, NodeLogWriter + + +@pytest.mark.unittest +def test_node_log_writer_unwraps_nested_prev_out(monkeypatch): + base_out = StringIO() + inner = NodeLogWriter(base_out) + outer = NodeLogWriter(inner) + + outer.write("hello") + + assert base_out.getvalue() == "hello" + + +@pytest.mark.unittest +def test_nested_node_log_manager_does_not_recurse(monkeypatch): + base_out = StringIO() + base_err = StringIO() + monkeypatch.setattr(sys, "stdout", base_out) + monkeypatch.setattr(sys, "stderr", base_err) + monkeypatch.setattr(sys, "__stdout__", base_out) + monkeypatch.setattr(sys, "__stderr__", base_err) + + original_limit = sys.getrecursionlimit() + sys.setrecursionlimit(300) + try: + with ExitStack() as stack: + for _ in range(500): + stack.enter_context(NodeLogManager()) + print("nested") + sys.stderr.write("stderr") + finally: + sys.setrecursionlimit(original_limit) + + assert "nested" in base_out.getvalue() + assert "stderr" in base_err.getvalue() From 1976fbce89a967bae3a35b4d0323d872bfebc611 Mon Sep 17 00:00:00 2001 From: xitzhang Date: Mon, 2 Feb 2026 23:22:39 -0800 Subject: [PATCH 25/84] [VoiceLive] Skip pyaudio dependency on Ubuntu/macOS (#44919) * [VoiceLive] Skip pyaudio dependency on Ubuntu/macOS * update --------- Co-authored-by: Xiting Zhang --- sdk/ai/azure-ai-voicelive/README.md | 3 +++ .../azure-ai-voicelive/dev_requirements.txt | 2 +- sdk/ai/azure-ai-voicelive/pyproject.toml | 2 +- .../samples/BASIC_VOICE_ASSISTANT.md | 26 ++++++++++++++++--- sdk/ai/azure-ai-voicelive/samples/README.md | 23 ++++++++++++++-- .../samples/async_function_calling_sample.py | 12 +++++++-- .../samples/async_mcp_sample.py | 12 +++++++-- .../samples/supervisor_agent_sample.py | 12 +++++++-- 8 files changed, 79 insertions(+), 13 deletions(-) diff --git a/sdk/ai/azure-ai-voicelive/README.md b/sdk/ai/azure-ai-voicelive/README.md index e33bb7535f36..cf1b1a2d8bb4 100644 --- a/sdk/ai/azure-ai-voicelive/README.md +++ b/sdk/ai/azure-ai-voicelive/README.md @@ -33,6 +33,9 @@ python -m pip install azure-ai-voicelive python -m pip install "azure-ai-voicelive[aiohttp]" # For voice samples (includes audio processing) +# First install PyAudio dependencies for your platform: +# Linux: sudo apt-get install -y portaudio19-dev libasound2-dev +# macOS: brew install portaudio python -m pip install azure-ai-voicelive[aiohttp] pyaudio python-dotenv ``` diff --git a/sdk/ai/azure-ai-voicelive/dev_requirements.txt b/sdk/ai/azure-ai-voicelive/dev_requirements.txt index babde7a9e9a1..ffa5c1ebca5d 100644 --- a/sdk/ai/azure-ai-voicelive/dev_requirements.txt +++ b/sdk/ai/azure-ai-voicelive/dev_requirements.txt @@ -4,7 +4,7 @@ aiohttp python-dotenv isodate websockets -pyaudio; platform_python_implementation == 'CPython' and python_version < '3.13' +pyaudio; platform_python_implementation == 'CPython' and python_version < '3.13' and sys_platform == 'win32' azure.identity pytest-rerunfailures>=13.0 pytest-asyncio diff --git a/sdk/ai/azure-ai-voicelive/pyproject.toml b/sdk/ai/azure-ai-voicelive/pyproject.toml index 5fdee2a8b6d1..3e2540ab6842 100644 --- a/sdk/ai/azure-ai-voicelive/pyproject.toml +++ b/sdk/ai/azure-ai-voicelive/pyproject.toml @@ -51,7 +51,7 @@ test = [ "python-dotenv", "azure-identity", "soundfile", - "pyaudio; platform_python_implementation == 'CPython' and python_version < '3.13'", + "pyaudio; platform_python_implementation == 'CPython' and python_version < '3.13' and sys_platform == 'win32'", ] [project.urls] diff --git a/sdk/ai/azure-ai-voicelive/samples/BASIC_VOICE_ASSISTANT.md b/sdk/ai/azure-ai-voicelive/samples/BASIC_VOICE_ASSISTANT.md index 768f915a250d..ca7302cbd1a6 100644 --- a/sdk/ai/azure-ai-voicelive/samples/BASIC_VOICE_ASSISTANT.md +++ b/sdk/ai/azure-ai-voicelive/samples/BASIC_VOICE_ASSISTANT.md @@ -19,9 +19,29 @@ This sample demonstrates a complete voice assistant implementation using the Azu ## Installation -```bash -pip install azure-ai-voicelive pyaudio python-dotenv -``` +1. **Install the SDK**: + ```bash + pip install azure-ai-voicelive python-dotenv + ``` + +2. **Install PyAudio** (required for audio capture/playback): + + PyAudio requires PortAudio to be installed on your system: + + - **Linux (Ubuntu/Debian)**: + ```bash + sudo apt-get install -y portaudio19-dev libasound2-dev + pip install pyaudio + ``` + - **macOS**: + ```bash + brew install portaudio + pip install pyaudio + ``` + - **Windows**: + ```bash + pip install pyaudio + ``` ## Configuration diff --git a/sdk/ai/azure-ai-voicelive/samples/README.md b/sdk/ai/azure-ai-voicelive/samples/README.md index 41529c87416f..bb113070478d 100644 --- a/sdk/ai/azure-ai-voicelive/samples/README.md +++ b/sdk/ai/azure-ai-voicelive/samples/README.md @@ -15,10 +15,29 @@ This directory contains sample applications demonstrating various capabilities o 1. **Install dependencies**: ```bash - pip install azure-ai-voicelive[aiohttp] pyaudio python-dotenv + pip install azure-ai-voicelive[aiohttp] python-dotenv ``` -2. **Configure environment variables**: +2. **Install PyAudio** (required for audio samples): + + PyAudio requires PortAudio to be installed on your system: + + - **Linux (Ubuntu/Debian)**: + ```bash + sudo apt-get install -y portaudio19-dev libasound2-dev + pip install pyaudio + ``` + - **macOS**: + ```bash + brew install portaudio + pip install pyaudio + ``` + - **Windows**: + ```bash + pip install pyaudio + ``` + +3. **Configure environment variables**: Create a `.env` file at the root of the azure-ai-voicelive directory or in the samples directory with the following variables: diff --git a/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py b/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py index 4b804ef4e447..2d80f8bcb16b 100644 --- a/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py +++ b/sdk/ai/azure-ai-voicelive/samples/async_function_calling_sample.py @@ -45,7 +45,10 @@ try: import pyaudio except ImportError: - print("This sample requires pyaudio. Install with: pip install pyaudio") + print("This sample requires pyaudio. Install with:") + print(" Linux: sudo apt-get install -y portaudio19-dev libasound2-dev && pip install pyaudio") + print(" macOS: brew install portaudio && pip install pyaudio") + print(" Windows: pip install pyaudio") sys.exit(1) # Environment variable loading @@ -770,7 +773,12 @@ def signal_handler(sig, frame): print("❌ Missing required dependencies:") for dep in missing_deps: print(f" - {dep}") - print("\nInstall with: pip install azure-ai-voicelive pyaudio python-dotenv") + print("\nInstall with:") + print(" pip install azure-ai-voicelive python-dotenv") + print(" For PyAudio:") + print(" Linux: sudo apt-get install -y portaudio19-dev libasound2-dev && pip install pyaudio") + print(" macOS: brew install portaudio && pip install pyaudio") + print(" Windows: pip install pyaudio") sys.exit(1) # Check audio system diff --git a/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py b/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py index a9f120caf6d6..dba44749167e 100644 --- a/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py +++ b/sdk/ai/azure-ai-voicelive/samples/async_mcp_sample.py @@ -42,7 +42,10 @@ try: import pyaudio except ImportError: - print("This sample requires pyaudio. Install with: pip install pyaudio") + print("This sample requires pyaudio. Install with:") + print(" Linux: sudo apt-get install -y portaudio19-dev libasound2-dev && pip install pyaudio") + print(" macOS: brew install portaudio && pip install pyaudio") + print(" Windows: pip install pyaudio") sys.exit(1) # Environment variable loading @@ -707,7 +710,12 @@ def signal_handler(sig, frame): print("❌ Missing required dependencies:") for dep in missing_deps: print(f" - {dep}") - print("\nInstall with: pip install azure-ai-voicelive pyaudio python-dotenv") + print("\nInstall with:") + print(" pip install azure-ai-voicelive python-dotenv") + print(" For PyAudio:") + print(" Linux: sudo apt-get install -y portaudio19-dev libasound2-dev && pip install pyaudio") + print(" macOS: brew install portaudio && pip install pyaudio") + print(" Windows: pip install pyaudio") sys.exit(1) # Check audio system diff --git a/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py b/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py index 9514cf835e63..2b43bcd1a85c 100644 --- a/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py +++ b/sdk/ai/azure-ai-voicelive/samples/supervisor_agent_sample.py @@ -30,7 +30,10 @@ try: import pyaudio except ImportError: - print("This sample requires pyaudio. Install with: pip install pyaudio") + print("This sample requires pyaudio. Install with:") + print(" Linux: sudo apt-get install -y portaudio19-dev libasound2-dev && pip install pyaudio") + print(" macOS: brew install portaudio && pip install pyaudio") + print(" Windows: pip install pyaudio") sys.exit(1) # Environment variable loading @@ -599,7 +602,12 @@ def signal_handler(sig, frame): print("❌ Missing required dependencies:") for dep in missing_deps: print(f" - {dep}") - print("\nInstall with: pip install azure-ai-voicelive pyaudio python-dotenv") + print("\nInstall with:") + print(" pip install azure-ai-voicelive python-dotenv") + print(" For PyAudio:") + print(" Linux: sudo apt-get install -y portaudio19-dev libasound2-dev && pip install pyaudio") + print(" macOS: brew install portaudio && pip install pyaudio") + print(" Windows: pip install pyaudio") sys.exit(1) # Check audio system From 198921dc68a697a600fe54d151bedf595f38fa4f Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Tue, 3 Feb 2026 09:23:12 -0800 Subject: [PATCH 26/84] Increment package version after release of azure-monitor-opentelemetry-exporter (#44977) Co-authored-by: rads-1996 --- .../CHANGELOG.md | 12 +++++++++++- .../azure/monitor/opentelemetry/exporter/_version.py | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index d5d33e275d38..478a2e1a41f7 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.0.0b48 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.0.0b47 (2026-02-03) ### Features Added @@ -773,4 +783,4 @@ - Initial alpha release -# cSpell:enable \ No newline at end of file +# cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py index 5eaf2c721d53..0c991711c5fc 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py @@ -5,4 +5,4 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "1.0.0b47" +VERSION = "1.0.0b48" From 981a14fbe2ab9df75312330bdfa47809a3840212 Mon Sep 17 00:00:00 2001 From: amber-Chen-86 Date: Tue, 3 Feb 2026 09:41:27 -0800 Subject: [PATCH 27/84] [Textanalytics] fix pylint/pyright for next version (#44785) * fix pyright * fix pyright for question authoring * fix pyright for questionanswering * updates * fixed next-pylint for text analytics * updated tests * updated tests * updated tag * update * updated snippets * added # type: ignore[override] * update * fix mypy * update dev requirements * updated --------- Co-authored-by: Rajarshi Sarkar <73562869+sarkar-rajarshi@users.noreply.github.com> --- .../questionanswering/_utils/serialization.py | 19 ++- .../authoring/_utils/serialization.py | 19 ++- .../tsp-location.yaml | 4 +- .../azure-ai-textanalytics/README.md | 25 +--- .../azure-ai-textanalytics/assets.json | 2 +- .../textanalytics/_operations/_operations.py | 28 ++-- .../azure/ai/textanalytics/_patch.py | 6 +- .../ai/textanalytics/_utils/model_base.py | 129 ++++++++++++++++-- .../ai/textanalytics/_utils/serialization.py | 17 ++- .../aio/_operations/_operations.py | 28 ++-- .../azure/ai/textanalytics/aio/_patch.py | 6 +- .../azure/ai/textanalytics/models/_models.py | 2 +- .../dev_requirements.txt | 3 +- .../azure-ai-textanalytics/pyproject.toml | 2 +- .../sample_abstract_summary_async.py | 15 +- .../sample_analyze_actions_async.py | 8 -- ...ample_analyze_healthcare_entities_async.py | 8 +- .../sample_authentication_async.py | 8 +- .../sample_extract_summary_async.py | 12 +- .../sample_multi_label_classify_async.py | 12 +- .../sample_recognize_custom_entities_async.py | 4 +- ...ii_entities_with_confidence_score_async.py | 13 +- ..._entities_with_redaction_policies_async.py | 6 +- .../sample_single_label_classify_async.py | 8 +- .../samples/sample_abstract_summary.py | 7 +- .../samples/sample_analyze_actions.py | 8 -- .../sample_analyze_healthcare_entities.py | 11 +- .../samples/sample_authentication.py | 6 +- .../samples/sample_extract_summary.py | 12 +- .../samples/sample_multi_label_classify.py | 10 +- ...nize_pii_entities_with_confidence_score.py | 13 +- ...ze_pii_entities_with_redaction_policies.py | 6 +- .../samples/sample_single_label_classify.py | 12 +- .../azure-ai-textanalytics/tests/conftest.py | 5 +- ...n_lro_task.py => test_abstract_summary.py} | 18 +-- ...sync.py => test_abstract_summary_async.py} | 10 +- ...phrases.py => test_extract_key_phrases.py} | 9 +- ...c.py => test_extract_key_phrases_async.py} | 10 +- ...on_lro_task.py => test_extract_summary.py} | 9 +- ...async.py => test_extract_summary_async.py} | 9 +- ...re_lro_task.py => test_health_care_lro.py} | 29 ++-- ...async.py => test_health_care_lro_async.py} | 15 +- ...etection.py => test_language_detection.py} | 9 +- ...nc.py => test_language_detection_async.py} | 9 +- ...o_task.py => test_multi_label_classify.py} | 10 +- ....py => test_multi_label_classify_async.py} | 10 +- ...entities.py => test_recognize_entities.py} | 9 +- ...nc.py => test_recognize_entities_async.py} | 9 +- ...task.py => test_recognize_entities_ner.py} | 12 +- ...y => test_recognize_entities_ner_async.py} | 10 +- ...s.py => test_recognize_linked_entities.py} | 9 +- ...> test_recognize_linked_entities_async.py} | 9 +- ...recognize_pii.py => test_recognize_pii.py} | 9 +- ...i_async.py => test_recognize_pii_async.py} | 9 +- ...=> test_recognize_pii_confidence_score.py} | 43 +++--- ...t_recognize_pii_confidence_score_async.py} | 45 +++--- ... test_recognize_pii_redaction_policies.py} | 11 +- ...recognize_pii_redaction_policies_async.py} | 13 +- ..._task.py => test_single_label_classify.py} | 10 +- ...py => test_single_label_classify_async.py} | 10 +- ...xt_sentiment.py => test_text_sentiment.py} | 9 +- ..._async.py => test_text_sentiment_async.py} | 9 +- 62 files changed, 556 insertions(+), 291 deletions(-) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_abstractive_summarization_lro_task.py => test_abstract_summary.py} (92%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_abstractive_summarization_lro_task_async.py => test_abstract_summary_async.py} (93%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_extract_key_phrases.py => test_extract_key_phrases.py} (81%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_extract_key_phrases_async.py => test_extract_key_phrases_async.py} (82%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_extractive_summarization_lro_task.py => test_extract_summary.py} (92%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_extractive_summarization_lro_task_async.py => test_extract_summary_async.py} (93%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_health_care_lro_task.py => test_health_care_lro.py} (74%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_health_care_lro_task_async.py => test_health_care_lro_async.py} (87%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_language_detection.py => test_language_detection.py} (77%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_language_detection_async.py => test_language_detection_async.py} (78%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_custom_multi_label_classification_lro_task.py => test_multi_label_classify.py} (86%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_custom_multi_label_classification_lro_task_async.py => test_multi_label_classify_async.py} (88%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_entities.py => test_recognize_entities.py} (83%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_entities_async.py => test_recognize_entities_async.py} (84%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_custom_entities_lro_task.py => test_recognize_entities_ner.py} (88%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_custom_entities_lro_task_async.py => test_recognize_entities_ner_async.py} (88%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_linked_entities.py => test_recognize_linked_entities.py} (84%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_linked_entities_async.py => test_recognize_linked_entities_async.py} (85%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_pii.py => test_recognize_pii.py} (81%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_pii_async.py => test_recognize_pii_async.py} (82%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_pii_confidence_score_threshold.py => test_recognize_pii_confidence_score.py} (61%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_pii_confidence_score_threshold_async.py => test_recognize_pii_confidence_score_async.py} (62%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_pii_redaction_policies.py => test_recognize_pii_redaction_policies.py} (86%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_recognize_pii_redaction_policies_async.py => test_recognize_pii_redaction_policies_async.py} (86%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_custom_single_label_classification_lro_task.py => test_single_label_classify.py} (86%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_custom_single_label_classification_lro_task_async.py => test_single_label_classify_async.py} (88%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_sentiment.py => test_text_sentiment.py} (84%) rename sdk/cognitivelanguage/azure-ai-textanalytics/tests/{test_analyze_text_sentiment_async.py => test_text_sentiment_async.py} (85%) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py index e81921cbb011..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py @@ -787,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py index e81921cbb011..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py @@ -787,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml index 707ff1f6cc0c..70f30533931b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml @@ -1,4 +1,4 @@ -directory: specification/cognitiveservices/Language.AnalyzeText-authoring -commit: a525e37a2b1546c47a778eda7106cfd7c04051e1 +directory: specification/cognitiveservices/data-plane/LanguageAnalyzeTextAuthoring +commit: 483301e475684d809bdc7e81aa786e84cfb4236f repo: Azure/azure-rest-api-specs additionalDirectories: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/README.md b/sdk/cognitivelanguage/azure-ai-textanalytics/README.md index 1be2ef2d0a95..fd63a71d2667 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/README.md +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/README.md @@ -69,7 +69,7 @@ from azure.ai.textanalytics import TextAnalysisClient endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] -text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) +text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable ``` @@ -126,7 +126,7 @@ from azure.ai.textanalytics import TextAnalysisClient endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] -text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) +text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable ``` @@ -164,7 +164,7 @@ from azure.identity import DefaultAzureCredential endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() -text_client = TextAnalysisClient(endpoint, credential=credential) +text_client = TextAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable ``` @@ -803,19 +803,12 @@ def sample_analyze_healthcare_entities(): print(f" Offset: {entity.offset}") print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}") - if entity.links: - for link in entity.links: - print(f" Link ID: {link.id}") - print(f" Data source: {link.data_source}") print() # Relations print("Relations:") for relation in doc.relations or []: print(f" Relation type: {relation.relation_type}") - for rel_entity in relation.entities or []: - print(f" Role: {rel_entity.role}") - print(f" Ref: {rel_entity.ref}") print() else: # Other action kinds, if present @@ -824,8 +817,8 @@ def sample_analyze_healthcare_entities(): f"\n[Non-healthcare action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-healthcare action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-healthcare action present] Error: {e}") ``` @@ -854,7 +847,6 @@ Note: Healthcare Entities Analysis is only available with API version v3.1 and n import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalysisClient from azure.ai.textanalytics.models import ( MultiLanguageTextInput, @@ -863,7 +855,6 @@ from azure.ai.textanalytics.models import ( KeyPhraseLROTask, EntityRecognitionOperationResult, KeyPhraseExtractionOperationResult, - EntityTag, ) @@ -931,12 +922,6 @@ def sample_analyze(): print(f" Type: {entity.type}") if hasattr(entity, "subcategory") and entity.subcategory: print(f" Subcategory: {entity.subcategory}") - if hasattr(entity, "tags") and entity.tags: - print(" Tags:") - for tag in entity.tags: - if isinstance(tag, EntityTag): - print(f" TagName: {tag.name}") - print(f" TagConfidenceScore: {tag.confidence_score}") print(f" Confidence score: {entity.confidence_score}") print() for err in action_result.results.errors: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json b/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json index c20f6411dd51..2e84d5bde809 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/cognitivelanguage/azure-ai-textanalytics", - "Tag": "python/cognitivelanguage/azure-ai-textanalytics_c820b61b7e" + "Tag": "python/cognitivelanguage/azure-ai-textanalytics_95abc8a0dd" } diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py index c56ea955c721..361efb3e6a6c 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py @@ -280,7 +280,10 @@ def analyze_text( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -365,7 +368,10 @@ def get_job_status( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -448,7 +454,10 @@ def _analyze_text_job_initial( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -462,7 +471,7 @@ def _analyze_text_job_initial( return deserialized # type: ignore @overload - def _begin_analyze_text_job( + def begin_analyze_text_job( self, *, text_input: _models.MultiLanguageTextInput, @@ -497,7 +506,7 @@ def _begin_analyze_text_job( """ @overload - def _begin_analyze_text_job( + def begin_analyze_text_job( self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -514,7 +523,7 @@ def _begin_analyze_text_job( """ @overload - def _begin_analyze_text_job( + def begin_analyze_text_job( self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -531,7 +540,7 @@ def _begin_analyze_text_job( """ @distributed_trace - def _begin_analyze_text_job( + def begin_analyze_text_job( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -651,7 +660,10 @@ def _cancel_job_initial(self, job_id: str, **kwargs: Any) -> Iterator[bytes]: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py index c0bc5c46f03f..155c134188dd 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py @@ -141,7 +141,7 @@ def __init__( kwargs["api_version"] = api_version super().__init__(endpoint=endpoint, credential=credential, **kwargs) - @overload + @overload # type: ignore[override] def begin_analyze_text_job( self, *, @@ -178,7 +178,7 @@ def begin_analyze_text_job( """ @overload - def begin_analyze_text_job( + def begin_analyze_text_job( # type: ignore[override] self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextLROPoller[ItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -196,7 +196,7 @@ def begin_analyze_text_job( """ @overload - def begin_analyze_text_job( + def begin_analyze_text_job( # type: ignore[override] self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextLROPoller[ItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py index 12926fa98dcf..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,6 +688,10 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -647,6 +701,16 @@ def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py index 45a3e44e45cb..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py index f941fb2d0920..3c3b0d63f346 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py @@ -185,7 +185,10 @@ async def analyze_text( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -270,7 +273,10 @@ async def get_job_status( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -353,7 +359,10 @@ async def _analyze_text_job_initial( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -367,7 +376,7 @@ async def _analyze_text_job_initial( return deserialized # type: ignore @overload - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, *, text_input: _models.MultiLanguageTextInput, @@ -402,7 +411,7 @@ async def _begin_analyze_text_job( """ @overload - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -419,7 +428,7 @@ async def _begin_analyze_text_job( """ @overload - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -436,7 +445,7 @@ async def _begin_analyze_text_job( """ @distributed_trace_async - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -557,7 +566,10 @@ async def _cancel_job_initial(self, job_id: str, **kwargs: Any) -> AsyncIterator except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py index d418bf365d3c..4dff8f288feb 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py @@ -127,7 +127,7 @@ def __init__( kwargs["api_version"] = api_version super().__init__(endpoint=endpoint, credential=credential, **kwargs) - @overload + @overload # type: ignore[override] async def begin_analyze_text_job( self, *, @@ -165,7 +165,7 @@ async def begin_analyze_text_job( """ @overload - async def begin_analyze_text_job( + async def begin_analyze_text_job( # type: ignore[override] self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextAsyncLROPoller[AsyncItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -184,7 +184,7 @@ async def begin_analyze_text_job( """ @overload - async def begin_analyze_text_job( + async def begin_analyze_text_job( # type: ignore[override] self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextAsyncLROPoller[AsyncItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py index 2adc7201371f..309446e81c02 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py @@ -6659,7 +6659,7 @@ class TextActions(_Model): total: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Count of total tasks. Required.""" items_property: Optional[list["_models.AnalyzeTextLROResult"]] = rest_field( - name="items", visibility=["read", "create", "update", "delete", "query"] + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" ) """Enumerable of Analyze text job results.""" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt index 0e53b6a72db5..396f26f367a1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core -aiohttp \ No newline at end of file +aiohttp +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml b/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml index 821860de4bd1..72aeea038b21 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml @@ -32,7 +32,7 @@ keywords = ["azure", "azure sdk"] dependencies = [ "isodate>=0.6.1", - "azure-core>=1.35.0", + "azure-core>=1.37.0", "typing-extensions>=4.6.0", ] dynamic = [ diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py index 81e64d95205a..e36686001865 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_abstractive_summarization_async.py +FILE: sample_abstract_summary_async.py DESCRIPTION: This sample demonstrates how to run an **abstractive summarization** action over text (async LRO). USAGE: - python sample_text_abstractive_summarization_async.py + python sample_abstract_summary_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -39,7 +39,7 @@ ) -async def sample_text_abstractive_summarization_async(): +async def sample_abstract_summary_async(): # settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -136,9 +136,6 @@ async def sample_text_abstractive_summarization_async(): print(f"\nDocument ID: {doc.id}") for s in doc.summaries or []: print(f" Summary: {s.text}") - if s.contexts: - for c in s.contexts: - print(f" Context offset={c.offset}, length={c.length}") else: # Other action kinds, if present try: @@ -146,15 +143,15 @@ async def sample_text_abstractive_summarization_async(): f"\n[Non-abstractive action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-abstractive action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-abstractive action present] Error: {e}") # [END text_abstractive_summarization_async] async def main(): - await sample_text_abstractive_summarization_async() + await sample_abstract_summary_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py index 41f07d950999..8ec180f68489 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py @@ -40,7 +40,6 @@ KeyPhraseLROTask, EntityRecognitionOperationResult, KeyPhraseExtractionOperationResult, - EntityTag, ) @@ -106,13 +105,6 @@ async def sample_analyze_actions_async(): print(f" Type: {entity.type}") if hasattr(entity, "subcategory") and entity.subcategory: print(f" Subcategory: {entity.subcategory}") - if hasattr(entity, "tags") and entity.tags: - print(" Tags:") - for tag in entity.tags: - if isinstance(tag, EntityTag): - print(f" TagName: {tag.name}") - print(f" TagConfidenceScore: {tag.confidence_score}") - print(f" Confidence score: {entity.confidence_score}") print() for err in action_result.results.errors: print(f" Error in document: {err.id}!") diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py index baa9073efc98..0b9c183eb2b7 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py @@ -113,10 +113,6 @@ async def sample_analyze_healthcare_entities_async(): print(f" Offset: {entity.offset}") print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}") - if entity.links: - for link in entity.links: - print(f" Link ID: {link.id}") - print(f" Data source: {link.data_source}") print() # Relations @@ -134,8 +130,8 @@ async def sample_analyze_healthcare_entities_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END analyze_healthcare_entities_async] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py index 76cc43d62a1a..a2bdfba0ff80 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py @@ -39,11 +39,11 @@ async def sample_authentication_api_key_async(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] - text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) + text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_ta_client_with_key_async] -async def sample_authentication_with_azure_active_directory(): +async def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -56,13 +56,13 @@ async def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() - text_client = TextAnalysisClient(endpoint, credential=credential) + text_client = TextAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable # [END create_ta_client_with_aad_async] async def main(): await sample_authentication_api_key_async() - await sample_authentication_with_azure_active_directory() + await sample_authentication_with_aad() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py index f2dc95702ed0..df1c149cb14f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_extractive_summarization_async.py +FILE: sample_extract_summary_async.py DESCRIPTION: This sample demonstrates how to run an **extractive summarization** action over text (async LRO). USAGE: - python sample_text_extractive_summarization_async.py + python sample_extract_summary_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -39,7 +39,7 @@ ) -async def sample_text_extractive_summarization_async(): +async def sample_extract_summary_async(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -149,15 +149,15 @@ async def sample_text_extractive_summarization_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END text_extractive_summarization_async] async def main(): - await sample_text_extractive_summarization_async() + await sample_extract_summary_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py index 00d524313f07..16f3df42c940 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_custom_multi_label_classification_async.py +FILE: sample_multi_label_classify_async.py DESCRIPTION: This sample demonstrates how to run a **custom multi-label classification** action over text (async LRO). USAGE: - python sample_text_custom_multi_label_classification_async.py + python sample_multi_label_classify_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -43,7 +43,7 @@ ) -async def sample_text_custom_multi_label_classification_async(): +async def sample_multi_label_classify_async(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -127,15 +127,15 @@ async def sample_text_custom_multi_label_classification_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END text_custom_multi_label_classification_async] async def main(): - await sample_text_custom_multi_label_classification_async() + await sample_multi_label_classify_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py index 424fbbbdc267..8622b86b0ca1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py @@ -117,8 +117,8 @@ async def sample_text_custom_entities_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END text_custom_entities_async] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py index 84b1d6c8e3a4..366a6d350f4c 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py @@ -5,14 +5,14 @@ # ------------------------------------ """ -FILE: sample_recognize_pii_entities_with_confidence_score_async.py +FILE: sample_pii_with_confidence_score_async.py DESCRIPTION: This sample demonstrates how to run **PII entity recognition** with confidence score thresholds (async), including entity-specific overrides. USAGE: - python sample_recognize_pii_entities_with_confidence_score_async.py + python sample_pii_with_confidence_score_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -43,17 +43,14 @@ ) -async def sample_recognize_pii_entities_with_confidence_score_async(): +async def sample_pii_with_confidence_score_async(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() async with TextAnalysisClient(endpoint, credential=credential) as client: # Input text - text = ( - "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. " - "John Doe is my name." - ) + text = "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. John Doe is my name." # Confidence score thresholds: # - Default threshold is 0.3 @@ -105,7 +102,7 @@ async def sample_recognize_pii_entities_with_confidence_score_async(): async def main(): - await sample_recognize_pii_entities_with_confidence_score_async() + await sample_pii_with_confidence_score_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py index fd5ea93a9128..4fd587e38aab 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py @@ -44,7 +44,7 @@ ) -async def sample_recognize_pii_entities_with_redaction_policies_async(): +async def sample_pii_with_redaction_policies_async(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -66,7 +66,6 @@ async def sample_recognize_pii_entities_with_redaction_policies_async(): redaction_policies=[ # Default policy: mask all categories (asterisks) EntityMaskPolicyType(policy_name="defaultPolicy", is_default=True), - # SSN: keep first 4 characters visible, mask the rest CharacterMaskPolicyType( policy_name="ssnMaskPolicy", @@ -74,7 +73,6 @@ async def sample_recognize_pii_entities_with_redaction_policies_async(): unmask_from_end=False, entity_types=["USSocialSecurityNumber"], ), - # Person & Email: replace with synthetic (fake) values SyntheticReplacementPolicyType( policy_name="syntheticPolicy", @@ -114,7 +112,7 @@ async def sample_recognize_pii_entities_with_redaction_policies_async(): async def main(): - await sample_recognize_pii_entities_with_redaction_policies_async() + await sample_pii_with_redaction_policies_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py index b2d22c832642..91bef000b490 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py @@ -43,7 +43,7 @@ ) -async def sample_text_custom_single_label_classification_async(): +async def sample_single_label_classify_async(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -127,15 +127,15 @@ async def sample_text_custom_single_label_classification_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Exception: {e}") # [END text_custom_single_label_classification_async] async def main(): - await sample_text_custom_single_label_classification_async() + await sample_single_label_classify_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py index a51ce09dd335..03cc56fbc7ac 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py @@ -134,9 +134,6 @@ def sample_text_abstractive_summarization(): print(f"\nDocument ID: {doc.id}") for s in doc.summaries or []: print(f" Summary: {s.text}") - if s.contexts: - for c in s.contexts: - print(f" Context offset={c.offset}, length={c.length}") else: # Other action kinds, if present try: @@ -144,8 +141,8 @@ def sample_text_abstractive_summarization(): f"\n[Non-abstractive action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-abstractive action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-abstractive action present] Error: {e}") # [END text_abstractive_summarization] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py index 5874fd3d3b5c..5627592a58be 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py @@ -31,7 +31,6 @@ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalysisClient from azure.ai.textanalytics.models import ( MultiLanguageTextInput, @@ -40,7 +39,6 @@ KeyPhraseLROTask, EntityRecognitionOperationResult, KeyPhraseExtractionOperationResult, - EntityTag, ) @@ -108,12 +106,6 @@ def sample_analyze(): print(f" Type: {entity.type}") if hasattr(entity, "subcategory") and entity.subcategory: print(f" Subcategory: {entity.subcategory}") - if hasattr(entity, "tags") and entity.tags: - print(" Tags:") - for tag in entity.tags: - if isinstance(tag, EntityTag): - print(f" TagName: {tag.name}") - print(f" TagConfidenceScore: {tag.confidence_score}") print(f" Confidence score: {entity.confidence_score}") print() for err in action_result.results.errors: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py index 41514cd10398..5af3044e3341 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py @@ -111,19 +111,12 @@ def sample_analyze_healthcare_entities(): print(f" Offset: {entity.offset}") print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}") - if entity.links: - for link in entity.links: - print(f" Link ID: {link.id}") - print(f" Data source: {link.data_source}") print() # Relations print("Relations:") for relation in doc.relations or []: print(f" Relation type: {relation.relation_type}") - for rel_entity in relation.entities or []: - print(f" Role: {rel_entity.role}") - print(f" Ref: {rel_entity.ref}") print() else: # Other action kinds, if present @@ -132,8 +125,8 @@ def sample_analyze_healthcare_entities(): f"\n[Non-healthcare action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-healthcare action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-healthcare action present] Error: {e}") # [END analyze_healthcare_entities] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py index 4f0ffe9ef552..780f1988ff0a 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py @@ -38,11 +38,11 @@ def sample_authentication_api_key(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] - text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) + text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_ta_client_with_key] -def sample_authentication_with_azure_active_directory(): +def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -55,7 +55,7 @@ def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() - text_client = TextAnalysisClient(endpoint, credential=credential) + text_client = TextAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable # [END create_ta_client_with_aad] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py index 38d9b56a14dc..23c234b9c327 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_extractive_summarization.py +FILE: sample_extract_summary.py DESCRIPTION: This sample demonstrates how to run an **extractive summarization** action over text. USAGE: - python sample_text_extractive_summarization.py + python sample_extract_summary.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -38,7 +38,7 @@ ) -def sample_text_extractive_summarization(): +def sample_extract_summary(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -144,15 +144,15 @@ def sample_text_extractive_summarization(): f"\n[Non-extractive action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-extractive action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-extractive action present] Error: {e}") # [END text_extractive_summarization] def main(): - sample_text_extractive_summarization() + sample_extract_summary() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py index b81ec7e91779..8bb169e9d29d 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py @@ -5,7 +5,7 @@ # ------------------------------------ """ -FILE: sample_text_custom_multi_label_classification.py +FILE: sample_multi_label_classify.py DESCRIPTION: This sample demonstrates how to run a **custom multi-label classification** action over text. @@ -42,7 +42,7 @@ ) -def sample_text_custom_multi_label_classification(): +def sample_multi_label_classify(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -121,15 +121,15 @@ def sample_text_custom_multi_label_classification(): f"\n[Non-CMLC action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-CMLC action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-CMLC action present] Error: {e}") # [END text_custom_multi_label_classification] def main(): - sample_text_custom_multi_label_classification() + sample_multi_label_classify() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py index 2203a94daf88..722e6e43fd35 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py @@ -41,7 +41,7 @@ ) -def sample_recognize_pii_entities_with_confidence_score(): +def sample_pii_with_confidence_score(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -49,10 +49,7 @@ def sample_recognize_pii_entities_with_confidence_score(): client = TextAnalysisClient(endpoint, credential=credential) # Input text - text = ( - "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. " - "John Doe is my name." - ) + text = "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. John Doe is my name." # Confidence score threshold configuration: # - Default threshold is 0.3 @@ -66,9 +63,7 @@ def sample_recognize_pii_entities_with_confidence_score(): ) body = TextPiiEntitiesRecognitionInput( - text_input=MultiLanguageTextInput( - multi_language_inputs=[MultiLanguageInput(id="1", text=text, language="en")] - ), + text_input=MultiLanguageTextInput(multi_language_inputs=[MultiLanguageInput(id="1", text=text, language="en")]), action_content=PiiActionContent( pii_categories=["All"], disable_entity_validation=True, @@ -102,7 +97,7 @@ def sample_recognize_pii_entities_with_confidence_score(): def main(): - sample_recognize_pii_entities_with_confidence_score() + sample_pii_with_confidence_score() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py index e20170fb7bae..7c5570cd4ce2 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py @@ -42,7 +42,7 @@ ) -def sample_recognize_pii_entities_with_redaction_policies(): +def sample_pii_with_redaction_policies(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -65,7 +65,6 @@ def sample_recognize_pii_entities_with_redaction_policies(): redaction_policies=[ # Default policy: mask all PII categories (asterisks) EntityMaskPolicyType(policy_name="defaultPolicy", is_default=True), - # For SSN: only mask characters except first 4 digits CharacterMaskPolicyType( policy_name="ssnMaskPolicy", @@ -73,7 +72,6 @@ def sample_recognize_pii_entities_with_redaction_policies(): unmask_from_end=False, entity_types=["USSocialSecurityNumber"], ), - # For Person & Email: replace with synthetic data (fake names/emails) SyntheticReplacementPolicyType( policy_name="syntheticPolicy", @@ -107,7 +105,7 @@ def sample_recognize_pii_entities_with_redaction_policies(): def main(): - sample_recognize_pii_entities_with_redaction_policies() + sample_pii_with_redaction_policies() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py index 71d87b82f81d..fa055617e50b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_custom_single_label_classification.py +FILE: sample_single_label_classify.py DESCRIPTION: This sample demonstrates how to run a **custom single-label classification** action over text. USAGE: - python sample_text_custom_single_label_classification.py + python sample_single_label_classify.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -42,7 +42,7 @@ ) -def sample_text_custom_single_label_classification(): +def sample_single_label_classify(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -121,15 +121,15 @@ def sample_text_custom_single_label_classification(): f"\n[Non-CSC action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-CSC action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-CSC action present] Error: {e}") # [END text_custom_single_label_classification] def main(): - sample_text_custom_single_label_classification() + sample_single_label_classify() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py index 53d000d3e73d..cf8fbcd9fb8c 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py @@ -5,19 +5,22 @@ ENV_ENDPOINT = "TEXT_ANALYSIS_ENDPOINT" ENV_KEY = "TEXT_ANALYSIS_KEY" + @pytest.fixture(scope="session") def text_analysis_endpoint(environment_variables: EnvironmentVariableLoader) -> str: """Endpoint for Text Analysis tests.""" return environment_variables.get(ENV_ENDPOINT) + @pytest.fixture(scope="session") def text_analysis_key(environment_variables: EnvironmentVariableLoader) -> str: """API key for Text Analysis tests.""" return environment_variables.get(ENV_KEY) + # autouse=True will trigger this fixture on each pytest run # test_proxy auto-starts the test proxy # patch_sleep and patch_async_sleep remove wait times during polling @pytest.fixture(scope="session", autouse=True) def start_proxy(test_proxy, patch_sleep, patch_async_sleep): - return \ No newline at end of file + return diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary.py similarity index 92% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary.py index b01fd8cc5bb9..acc6ce377a6f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -11,7 +19,6 @@ AbstractiveSummarizationOperationResult, AbstractiveSummaryActionResult, AbstractiveSummary, - SummaryContext, ) TextAnalysisPreparer = functools.partial( @@ -30,7 +37,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_abstractive_summarization_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_abstract_summary(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( @@ -115,11 +122,4 @@ def test_analyze_text_abstractive_summarization_lro_task(self, text_analysis_end assert isinstance(summary, AbstractiveSummary) assert summary.text is not None - # contexts may be optional - if summary.contexts is not None: - for ctx in summary.contexts: - assert isinstance(ctx, SummaryContext) - assert ctx.offset is not None - assert ctx.length is not None - assert found_abstractive, "Expected an AbstractiveSummarizationOperationResult in TextActions.items_property" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary_async.py similarity index 93% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary_async.py index 8bdc61ddb8f2..c1abc6af1d27 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools import pytest @@ -36,7 +44,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_abstractive_summarization_lro_task_async( + async def test_abstract_summary_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases.py similarity index 81% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases.py index 0c1df5f193d1..31261f793463 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -28,7 +35,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_extract_key_phrases(self, text_analysis_endpoint, text_analysis_key): + def test_extract_key_phrases(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases_async.py similarity index 82% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases_async.py index 52ef2a208343..015e73d3a879 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools import pytest @@ -34,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_extract_key_phrases_async(self, text_analysis_endpoint, text_analysis_key): + async def test_extract_key_phrases_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "We love this trail and make the trip every year. The views are breathtaking and well worth the hike! " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary.py similarity index 92% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary.py index 2289e7e2380c..7fddb0f9ca38 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -29,7 +36,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_extractive_summarization_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_extract_summary(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary_async.py similarity index 93% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary_async.py index 81017ba50b04..2815c3f92c96 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -35,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_extractive_summarization_lro_task_async( + async def test_extract_summary_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro.py similarity index 74% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro.py index 5f4e25127e67..f1d318618372 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro.py @@ -1,5 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools -import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential @@ -13,8 +19,6 @@ TextActions, ) -from azure.core.credentials import AzureKeyCredential - TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", @@ -37,7 +41,7 @@ def create_client(self, endpoint, key): class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_health_care_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_health_care_lro(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = "Prescribed 100mg ibuprofen, taken twice daily." @@ -88,26 +92,9 @@ def test_analyze_text_health_care_lro_task(self, text_analysis_endpoint, text_an assert doc.entities is not None assert doc.relations is not None - for entity in doc.entities: - assert entity is not None - assert entity.text is not None - assert entity.category is not None - assert entity.offset is not None - assert entity.length is not None - assert entity.confidence_score is not None - - if entity.links is not None: - for link in entity.links: - assert link is not None - assert link.id is not None - assert link.data_source is not None - for relation in doc.relations: assert relation is not None assert relation.relation_type is not None assert relation.entities is not None - for rel_entity in relation.entities: - assert rel_entity.role is not None - assert rel_entity.ref is not None assert found_healthcare, "Expected a HealthcareLROResult in TextActions.items_property" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro_async.py similarity index 87% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro_async.py index 27cb30ccf705..6cb331719cea 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -34,7 +41,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_health_care_lro_task_async(self, text_analysis_endpoint, text_analysis_key): + async def test_health_care_lro_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = "Prescribed 100mg ibuprofen, taken twice daily." @@ -91,12 +98,6 @@ async def test_analyze_text_health_care_lro_task_async(self, text_analysis_endpo assert entity.length is not None assert entity.confidence_score is not None - if entity.links is not None: - for link in entity.links: - assert link is not None - assert link.id is not None - assert link.data_source is not None - for relation in doc.relations: assert relation is not None assert relation.relation_type is not None diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection.py similarity index 77% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection.py index 1bb3bdf93f9d..aaf56169fb5a 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -27,7 +34,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_language_detection(self, text_analysis_endpoint, text_analysis_key): + def test_language_detection(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = "Sentences in different languages." diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection_async.py similarity index 78% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection_async.py index af48a0bb1ba6..56d965fdd130 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -33,7 +40,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_language_detection_async(self, text_analysis_endpoint, text_analysis_key): + async def test_language_detection_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = "Sentences in different languages." diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify.py index 2fb0bed4b290..89021fb6fba5 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -30,7 +38,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_custom_multi_label_classification_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_multi_label_classify(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) project_name = "multi-class-project" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify_async.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify_async.py index c4935cb3f774..a1b1f1ad3d60 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools import pytest @@ -36,7 +44,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_custom_multi_label_classification_lro_task_async( + async def test_multi_label_classify_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities.py similarity index 83% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities.py index 560a9e744b22..2d9538993bfc 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -29,7 +36,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_entities(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_entities(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_async.py similarity index 84% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_async.py index 84bbaecfef16..83ade53baa97 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -35,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_entities_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_entities_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "We love this trail and make the trip every year. The views are breathtaking and well worth the hike! " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner.py index 412698e617d6..cedd496fd259 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -15,8 +23,6 @@ NamedEntity, ) -from azure.core.credentials import AzureKeyCredential - TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", @@ -39,7 +45,7 @@ def create_client(self, endpoint, key): class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_custom_entities_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_entities(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) project_name = "Example-ner-project" deployment_name = "TestDeployment" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner_async.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner_async.py index 05683f785b0a..51498c3b17cc 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools import pytest @@ -37,7 +45,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_custom_entities_lro_task_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_entities_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: project_name = "Example-ner-project" deployment_name = "TestDeployment" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities.py similarity index 84% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities.py index 3644b4688770..20a40b61f6cb 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -30,7 +37,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_linked_entities(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_linked_entities(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py similarity index 85% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py index 7e6654cee8e6..2bb56454feaa 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -36,7 +43,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_linked_entities_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_linked_entities_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends, Steve " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii.py similarity index 81% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii.py index dd77a5ec2d19..84bcae87e035 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -28,7 +35,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_pii(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_pii(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_async.py similarity index 82% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_async.py index 7e3afbc21dea..a6e29ced9426 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_async.py @@ -1,4 +1,11 @@ # pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -35,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_pii_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_pii_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "Parker Doe has repaid all of their loans as of 2020-04-25. Their SSN is 859-98-0987. To contact them, " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score.py similarity index 61% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score.py index 01a2241db0b1..4d7e0e7dcf31 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -8,8 +15,6 @@ MultiLanguageInput, TextPiiEntitiesRecognitionInput, AnalyzeTextPiiResult, - PiiResultWithDetectedLanguage, - PiiEntity, ConfidenceScoreThreshold, ConfidenceScoreThresholdOverride, PiiActionContent, @@ -18,7 +23,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -31,7 +36,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase_NewPIIThresholds(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_pii_confidence_score_threshold(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_pii_confidence_score(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) # Input documents @@ -46,15 +51,11 @@ def test_analyze_text_recognize_pii_confidence_score_threshold(self, text_analys # Confidence score overrides ssn_override = ConfidenceScoreThresholdOverride(value=0.9, entity="USSocialSecurityNumber") - email_override = ConfidenceScoreThresholdOverride( - value=0.9, entity="Email" - ) - confidence_threshold = ConfidenceScoreThreshold( - default=0.3, overrides=[ssn_override, email_override] - ) + email_override = ConfidenceScoreThresholdOverride(value=0.9, entity="Email") + confidence_threshold = ConfidenceScoreThreshold(default=0.3, overrides=[ssn_override, email_override]) # Parameters parameters = PiiActionContent( - pii_categories=["All"], disable_entity_validation=True, confidence_score_threshold=confidence_threshold + pii_categories=["All"], confidence_score_threshold=confidence_threshold ) body = TextPiiEntitiesRecognitionInput(text_input=text_input, action_content=parameters) @@ -73,16 +74,16 @@ def test_analyze_text_recognize_pii_confidence_score_threshold(self, text_analys # Person should be masked out in text; SSN & Email should remain (filtered out as entities) assert "John Doe" not in redacted - assert "222-45-6789" in redacted - assert "john@example.com" in redacted + assert doc.entities is not None + assert len(doc.entities) > 0 + + # Person is present + assert any(e.category == "Person" for e in doc.entities), "Expected at least one Person entity" - # Only Person entities should be returned (SSN & Email removed by 0.9 thresholds) - assert len(doc.entities) == 2 - cats = {e.category for e in doc.entities} - assert cats == {"Person"} + # Verify SSN / Email are NOT returned as entities + bad_categories = {"USSocialSecurityNumber", "Email"} + bad_types = {"USSocialSecurityNumber", "Email"} - # Quick sanity on masking and confidence (no brittle exact names) for e in doc.entities: - assert e.category == "Person" - assert e.mask is not None and e.mask != e.text # masked - assert e.confidence_score >= 0.3 # respects default floor + assert e.category not in bad_categories + assert e.type not in bad_types diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score_async.py similarity index 62% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score_async.py index b5f54e036531..4e40209054fd 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score_async.py @@ -1,4 +1,11 @@ # pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -14,8 +21,6 @@ MultiLanguageInput, TextPiiEntitiesRecognitionInput, AnalyzeTextPiiResult, - PiiResultWithDetectedLanguage, - PiiEntity, ConfidenceScoreThreshold, ConfidenceScoreThresholdOverride, PiiActionContent, @@ -24,7 +29,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -38,7 +43,7 @@ class TestTextAnalysisCase_NewPIIThresholds(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_pii_confidence_score_threshold_async( + async def test_recognize_pii_confidence_score_async( # pylint: disable=name-too-long self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: @@ -55,16 +60,12 @@ async def test_analyze_text_recognize_pii_confidence_score_threshold_async( # Confidence score overrides ssn_override = ConfidenceScoreThresholdOverride(value=0.9, entity="USSocialSecurityNumber") - email_override = ConfidenceScoreThresholdOverride( - value=0.9, entity="Email" - ) - confidence_threshold = ConfidenceScoreThreshold( - default=0.3, overrides=[ssn_override, email_override] - ) + email_override = ConfidenceScoreThresholdOverride(value=0.9, entity="Email") + confidence_threshold = ConfidenceScoreThreshold(default=0.3, overrides=[ssn_override, email_override]) # Parameters parameters = PiiActionContent( - pii_categories=["All"], disable_entity_validation=True, confidence_score_threshold=confidence_threshold + pii_categories=["All"], confidence_score_threshold=confidence_threshold ) body = TextPiiEntitiesRecognitionInput(text_input=text_input, action_content=parameters) @@ -81,18 +82,18 @@ async def test_analyze_text_recognize_pii_confidence_score_threshold_async( doc = result.results.documents[0] redacted = doc.redacted_text - # Person should be masked out in text; SSN & Email should remain (filtered out as entities) + # Person should be masked out in text; assert "John Doe" not in redacted - assert "222-45-6789" in redacted - assert "john@example.com" in redacted + assert doc.entities is not None + assert len(doc.entities) > 0 + + # Person is present + assert any(e.category == "Person" for e in doc.entities), "Expected at least one Person entity" - # Only Person entities should be returned (SSN & Email removed by 0.9 thresholds) - assert len(doc.entities) == 2 - cats = {e.category for e in doc.entities} - assert cats == {"Person"} + # Verify SSN / Email are NOT returned as entities + bad_categories = {"USSocialSecurityNumber", "Email"} + bad_types = {"USSocialSecurityNumber", "Email"} - # Quick sanity on masking and confidence (no brittle exact names) for e in doc.entities: - assert e.category == "Person" - assert e.mask is not None and e.mask != e.text # masked - assert e.confidence_score >= 0.3 # respects default floor + assert e.category not in bad_categories + assert e.type not in bad_types diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies.py index 19e2eb955185..c5e322684e5e 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -17,7 +24,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -30,7 +37,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_pii_redaction_policies(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_pii_redaction_policies(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) # Documents diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies_async.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies_async.py index ac182453bf92..b87de711542f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -13,8 +20,6 @@ MultiLanguageInput, TextPiiEntitiesRecognitionInput, AnalyzeTextPiiResult, - PiiResultWithDetectedLanguage, - PiiEntity, PiiActionContent, EntityMaskPolicyType, CharacterMaskPolicyType, @@ -24,7 +29,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -38,7 +43,7 @@ class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_pii_redaction_policies_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_pii_redaction_policies_async(self, text_analysis_endpoint, text_analysis_key): # pylint: disable=name-too-long async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: # Documents diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify.py index 25ae2e4e39f9..7a2c57c9b1b1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -30,7 +38,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_custom_single_label_classification_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_single_label_classify(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) project_name = "single-class-project" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify_async.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify_async.py index 99db2549854e..886e7d50fea6 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + import functools import pytest @@ -36,7 +44,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_custom_single_label_classification_lro_task_async( + async def test_single_label_classify_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment.py similarity index 84% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment.py index 44e26e04f226..c2d78a07bc5e 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -28,7 +35,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_sentiment(self, text_analysis_endpoint, text_analysis_key): + def test_text_sentiment(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment_async.py similarity index 85% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment_async.py index 3b02385d940d..e3c207b72027 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- import functools import pytest @@ -34,7 +41,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_sentiment_async(self, text_analysis_endpoint, text_analysis_key): + async def test_text_sentiment_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "The food and service were unacceptable, but the concierge were nice. After talking to them about the " From f5fecc5bb0d22a2daf1d186013fccad406d9e3c7 Mon Sep 17 00:00:00 2001 From: amber-Chen-86 Date: Tue, 3 Feb 2026 10:16:35 -0800 Subject: [PATCH 28/84] [Textanalytics authoring] fix pylint/pyright for next version (#44853) * fix pyright * updapted samples * updated async samples * fix model_base * updated * updated --------- Co-authored-by: Rajarshi Sarkar <73562869+sarkar-rajarshi@users.noreply.github.com> --- .../authoring/_utils/model_base.py | 133 ++++++++++++++++-- .../dev_requirements.txt | 3 +- ...ample_assign_deployment_resources_async.py | 2 +- .../async/sample_authentication_async.py | 6 +- .../async/sample_cancel_training_job_async.py | 2 +- .../async/sample_create_project_async.py | 2 +- .../async/sample_delete_deployment_async.py | 2 +- .../async/sample_delete_project_async.py | 2 +- .../sample_delete_trained_model_async.py | 2 +- .../async/sample_deploy_project_async.py | 2 +- .../async/sample_export_project_async.py | 2 +- .../async/sample_get_deployment_async.py | 2 +- ...mple_get_model_evaluation_summary_async.py | 4 +- .../samples/async/sample_get_project_async.py | 2 +- .../async/sample_import_project_async.py | 2 +- ...ple_list_model_evaluation_results_async.py | 3 +- .../async/sample_load_snapshot_async.py | 2 +- .../async/sample_swap_deployments_async.py | 2 +- .../async/sample_train_project_async.py | 2 +- ...ple_unassign_deployment_resources_async.py | 3 +- .../samples/sample_authentication.py | 6 +- .../tests/test_cancel_training_job.py | 1 - .../tests/test_cancel_training_job_async.py | 1 - .../tests/test_delete_deployment.py | 1 - .../tests/test_delete_deployment_async.py | 1 - .../tests/test_deploy_project.py | 2 +- .../tests/test_deploy_project_async.py | 2 +- 27 files changed, 151 insertions(+), 43 deletions(-) diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/model_base.py index 430bda7b37fc..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/model_base.py @@ -22,7 +22,7 @@ from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder import xml.etree.ElementTree as ET -from collections.abc import MutableMapping # pylint:disable=import-error +from collections.abc import MutableMapping from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,15 +688,29 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - return super().__new__(cls) # pylint:disable=no-value-for-parameter + return super().__new__(cls) def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/dev_requirements.txt index 0e53b6a72db5..396f26f367a1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core -aiohttp \ No newline at end of file +aiohttp +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_assign_deployment_resources_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_assign_deployment_resources_async.py index ed5708bbec45..82ca09eade4d 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_assign_deployment_resources_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_assign_deployment_resources_async.py @@ -29,7 +29,7 @@ # [START text_authoring_assign_deployment_resources_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_authentication_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_authentication_async.py index 5edc28089c30..2a63cb57b53c 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_authentication_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_authentication_async.py @@ -41,11 +41,11 @@ async def sample_authentication_api_key_async(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] - text_client = TextAuthoringClient(endpoint, AzureKeyCredential(key)) + text_client = TextAuthoringClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_text_client_with_key_async] -async def sample_authentication_with_azure_active_directory(): +async def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -56,7 +56,7 @@ async def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() - text_client = TextAuthoringClient(endpoint, credential=credential) + text_client = TextAuthoringClient(endpoint, credential=credential) # pylint:disable=unused-variable async def main(): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_cancel_training_job_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_cancel_training_job_async.py index a83b4c19f4b1..8ea7e96c6821 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_cancel_training_job_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_cancel_training_job_async.py @@ -27,7 +27,7 @@ # [START text_authoring_cancel_training_job_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_create_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_create_project_async.py index e5b9cf3e92ab..afc67fa3b5da 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_create_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_create_project_async.py @@ -29,7 +29,7 @@ # [START text_authoring_create_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( CreateProjectOptions, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_deployment_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_deployment_async.py index 6a79ca7c0f5f..2482950953d3 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_deployment_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_deployment_async.py @@ -27,7 +27,7 @@ # [START text_authoring_delete_deployment_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_project_async.py index 05ab2a747021..a276fd491238 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_project_async.py @@ -26,7 +26,7 @@ # [START text_authoring_delete_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_trained_model_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_trained_model_async.py index 6861eab5656d..78dca69b6500 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_trained_model_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_delete_trained_model_async.py @@ -28,7 +28,7 @@ import os import asyncio from azure.core.exceptions import HttpResponseError -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_deploy_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_deploy_project_async.py index 47acfab22dd9..290c19c97ad8 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_deploy_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_deploy_project_async.py @@ -28,7 +28,7 @@ # [START text_authoring_deploy_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import CreateDeploymentDetails diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_export_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_export_project_async.py index e22c925b5664..3ca406f0af5f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_export_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_export_project_async.py @@ -26,7 +26,7 @@ # [START text_authoring_export_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import StringIndexType diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_deployment_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_deployment_async.py index 1f6063980aa7..b0f30f3483a3 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_deployment_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_deployment_async.py @@ -27,7 +27,7 @@ # [START text_authoring_get_deployment_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_model_evaluation_summary_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_model_evaluation_summary_async.py index 8932b1aac1ea..4a1287eacd31 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_model_evaluation_summary_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_model_evaluation_summary_async.py @@ -1,4 +1,4 @@ -# pylint: disable=line-too-long,useless-suppression +# pylint: disable=name-too-long, line-too-long, useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft. @@ -29,7 +29,7 @@ # [START text_authoring_get_model_evaluation_summary_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( CustomSingleLabelClassificationEvalSummary, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_project_async.py index 594e77895311..3b0da601ad83 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_get_project_async.py @@ -26,7 +26,7 @@ # [START text_authoring_get_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_import_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_import_project_async.py index 121daa9c32e0..40cfd6912cbb 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_import_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_import_project_async.py @@ -30,7 +30,7 @@ # [START text_authoring_import_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_list_model_evaluation_results_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_list_model_evaluation_results_async.py index bc851656acde..08f7db9359d0 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_list_model_evaluation_results_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_list_model_evaluation_results_async.py @@ -1,3 +1,4 @@ +# pylint: disable=name-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft. @@ -28,7 +29,7 @@ # [START text_authoring_get_model_evaluation_results_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( CustomSingleLabelClassificationDocumentEvalResult, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_load_snapshot_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_load_snapshot_async.py index 81b491d68db6..cdfb7859323d 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_load_snapshot_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_load_snapshot_async.py @@ -27,7 +27,7 @@ # [START text_authoring_load_snapshot_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_swap_deployments_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_swap_deployments_async.py index 30affb7dcd70..5597d5ebefde 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_swap_deployments_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_swap_deployments_async.py @@ -28,7 +28,7 @@ # [START text_authoring_swap_deployments_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import SwapDeploymentsDetails diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_train_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_train_project_async.py index bbf1b379728e..e737acdbaae9 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_train_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_train_project_async.py @@ -28,7 +28,7 @@ # [START text_authoring_train_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_unassign_deployment_resources_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_unassign_deployment_resources_async.py index 3b9a46c32a9c..81f19f5a0444 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_unassign_deployment_resources_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/async/sample_unassign_deployment_resources_async.py @@ -1,3 +1,4 @@ +# pylint: disable=name-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. @@ -27,7 +28,7 @@ # [START text_authoring_unassign_deployment_resources_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient from azure.ai.textanalytics.authoring.models import ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/sample_authentication.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/sample_authentication.py index e51396386310..686dc6e764c7 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/sample_authentication.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/samples/sample_authentication.py @@ -41,11 +41,11 @@ def sample_authentication_api_key(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] - text_client = TextAuthoringClient(endpoint, AzureKeyCredential(key)) + text_client = TextAuthoringClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_text_client_with_key] -def sample_authentication_with_azure_active_directory(): +def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -56,7 +56,7 @@ def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() - text_client = TextAuthoringClient(endpoint, credential=credential) + text_client = TextAuthoringClient(endpoint, credential=credential) # pylint:disable=unused-variable def main(): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job.py index 52c2fa358707..82a85340695a 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job.py @@ -4,7 +4,6 @@ from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics.authoring import TextAuthoringClient -from azure.ai.textanalytics.authoring.models import TrainingJobResult ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job_async.py index c1f3585aecec..3fdf918c0099 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_cancel_training_job_async.py @@ -1,6 +1,5 @@ # pylint: disable=line-too-long,useless-suppression import functools -import json import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment.py index e7c85f9951c2..1b849919d85e 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment.py @@ -5,7 +5,6 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring import TextAuthoringClient -from azure.ai.textanalytics.authoring.models import DeploymentState ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment_async.py index 0abd75fd2d12..8dc263e4855f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_delete_deployment_async.py @@ -7,7 +7,6 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient -from azure.ai.textanalytics.authoring.models import DeploymentState ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project.py index 677008c5e89a..2fbc29a31b57 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project.py @@ -5,7 +5,7 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring import TextAuthoringClient -from azure.ai.textanalytics.authoring.models import CreateDeploymentDetails, DeploymentState +from azure.ai.textanalytics.authoring.models import CreateDeploymentDetails ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project_async.py index 5ae4cee1409f..94f04dde6973 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tests/test_deploy_project_async.py @@ -7,7 +7,7 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.textanalytics.authoring.aio import TextAuthoringClient -from azure.ai.textanalytics.authoring.models import CreateDeploymentDetails, DeploymentState +from azure.ai.textanalytics.authoring.models import CreateDeploymentDetails ConversationsPreparer = functools.partial( EnvironmentVariableLoader, From fe83d910e69a1a8c6ece0e0df04a033d6db64a1a Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Tue, 3 Feb 2026 10:29:08 -0800 Subject: [PATCH 29/84] Bump cspell from 9.4.0 to 9.6.2 in /eng/common/spelling (#44978) Bumps [cspell](https://github.com/streetsidesoftware/cspell/tree/HEAD/packages/cspell) from 9.4.0 to 9.6.2. - [Release notes](https://github.com/streetsidesoftware/cspell/releases) - [Changelog](https://github.com/streetsidesoftware/cspell/blob/main/packages/cspell/CHANGELOG.md) - [Commits](https://github.com/streetsidesoftware/cspell/commits/v9.6.2/packages/cspell) Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- eng/common/spelling/package-lock.json | 645 ++++++++++++++------------ eng/common/spelling/package.json | 2 +- 2 files changed, 362 insertions(+), 285 deletions(-) diff --git a/eng/common/spelling/package-lock.json b/eng/common/spelling/package-lock.json index 5421518f2cf0..a0199b95496a 100644 --- a/eng/common/spelling/package-lock.json +++ b/eng/common/spelling/package-lock.json @@ -8,13 +8,13 @@ "name": "cspell-version-pin", "version": "1.0.0", "dependencies": { - "cspell": "^9.6.0" + "cspell": "^9.6.3" } }, "node_modules/@cspell/cspell-bundled-dicts": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.6.0.tgz", - "integrity": "sha512-gLNe9bB+5gMsTEhR9YPE0Wt122HR2EV+Q1j9W+MbwbeBJmpTWrgAP1ZdpvHOg+6LF6x/bD/EC9HfWdd/om8wXA==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.6.3.tgz", + "integrity": "sha512-0Ibx+ynlSd8wMAoUmc2Ck4SDN27eJheM45aCmCvCA8saROwkDh7j8zBz7aTTUTtFN+pcotJoNxr71LLD+KXhgQ==", "dependencies": { "@cspell/dict-ada": "^4.1.1", "@cspell/dict-al": "^1.1.1", @@ -31,16 +31,16 @@ "@cspell/dict-docker": "^1.1.17", "@cspell/dict-dotnet": "^5.0.11", "@cspell/dict-elixir": "^4.0.8", - "@cspell/dict-en_us": "^4.4.27", - "@cspell/dict-en-common-misspellings": "^2.1.11", - "@cspell/dict-en-gb-mit": "^3.1.16", + "@cspell/dict-en_us": "^4.4.28", + "@cspell/dict-en-common-misspellings": "^2.1.12", + "@cspell/dict-en-gb-mit": "^3.1.17", "@cspell/dict-filetypes": "^3.0.15", "@cspell/dict-flutter": "^1.1.1", "@cspell/dict-fonts": "^4.0.5", "@cspell/dict-fsharp": "^1.1.1", - "@cspell/dict-fullstack": "^3.2.7", + "@cspell/dict-fullstack": "^3.2.8", "@cspell/dict-gaming-terms": "^1.1.2", - "@cspell/dict-git": "^3.0.7", + "@cspell/dict-git": "^3.1.0", "@cspell/dict-golang": "^6.0.26", "@cspell/dict-google": "^1.0.9", "@cspell/dict-haskell": "^4.0.6", @@ -50,21 +50,21 @@ "@cspell/dict-julia": "^1.1.1", "@cspell/dict-k8s": "^1.0.12", "@cspell/dict-kotlin": "^1.1.1", - "@cspell/dict-latex": "^4.0.4", + "@cspell/dict-latex": "^5.0.0", "@cspell/dict-lorem-ipsum": "^4.0.5", "@cspell/dict-lua": "^4.0.8", "@cspell/dict-makefile": "^1.0.5", "@cspell/dict-markdown": "^2.0.14", "@cspell/dict-monkeyc": "^1.0.12", - "@cspell/dict-node": "^5.0.8", - "@cspell/dict-npm": "^5.2.29", + "@cspell/dict-node": "^5.0.9", + "@cspell/dict-npm": "^5.2.32", "@cspell/dict-php": "^4.1.1", "@cspell/dict-powershell": "^5.0.15", "@cspell/dict-public-licenses": "^2.0.15", "@cspell/dict-python": "^4.2.25", "@cspell/dict-r": "^2.1.1", "@cspell/dict-ruby": "^5.1.0", - "@cspell/dict-rust": "^4.1.1", + "@cspell/dict-rust": "^4.1.2", "@cspell/dict-scala": "^5.0.9", "@cspell/dict-shell": "^1.1.2", "@cspell/dict-software-terms": "^5.1.20", @@ -81,28 +81,36 @@ } }, "node_modules/@cspell/cspell-json-reporter": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.6.0.tgz", - "integrity": "sha512-5sY1lgAXS5xEOsjT5rREMADj7pHIt56XOL7xR80nNl0TwlpZbeBHhoB2aH5sirVTeodJFN5iraXNbVOYPPupPw==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.6.3.tgz", + "integrity": "sha512-4jhqXKGCFAQXomtk4/Ldy/GiGEocC61v8GISiUgn1mH+HPgEvkJijyxKRNFYvzXOoJr4y0KrkGBoKk5FI7cipw==", "dependencies": { - "@cspell/cspell-types": "9.6.0" + "@cspell/cspell-types": "9.6.3" }, "engines": { "node": ">=20" } }, + "node_modules/@cspell/cspell-performance-monitor": { + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-performance-monitor/-/cspell-performance-monitor-9.6.3.tgz", + "integrity": "sha512-Y1I0wg7MUTouubREyPeTJe2dKNbBZPBnd6kDNcVet5DRZ3Cck2udS9m1a6DhJO2sGQgHTBULPDBEUU5tcAZ+nQ==", + "engines": { + "node": ">=20.18" + } + }, "node_modules/@cspell/cspell-pipe": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.6.0.tgz", - "integrity": "sha512-YNuY8NNXfE+8Qzknm2ps6QbrZLZu6rSZTZr3dYW3K6TK7+IFVlJ6e2Z9iKJTqp6aZ4AGU/r9QYGmNX4Oq4gZ0A==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.6.3.tgz", + "integrity": "sha512-Q0M58JbgHWOOOYvSyBodEysXLP5t8Q58Ff08msj2/XxRFpowR4iIUyfg3k+/d06uyOy89l+RD5AmyTEa5410xg==", "engines": { "node": ">=20" } }, "node_modules/@cspell/cspell-resolver": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.6.0.tgz", - "integrity": "sha512-Gb2UWNmRpTOQGpYL4Q/LMw+b50KcRZcf/wJg6w0Yl3IT+F/uDNhNh1f5rHuTyGsbMsMxHJhsb2AoP+73GlbIfw==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.6.3.tgz", + "integrity": "sha512-yUMTC8vl+LeRcIeXRrxn0GXL+rurf4OR3uyqZbG6bbtuttvq/Icleeibv9Wts+n700HLp+sVXJ7BrCn0Ehobsw==", "dependencies": { "global-directory": "^4.0.1" }, @@ -111,21 +119,32 @@ } }, "node_modules/@cspell/cspell-service-bus": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.6.0.tgz", - "integrity": "sha512-DCuKKkySTEB8MPLTdoPMdmakYcx7XCsHz1YEMbzOcLqJCxXsRlRZg4qE9kRBee/2QY7eYA2kaYNgn/TDMooa4g==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.6.3.tgz", + "integrity": "sha512-gDUDq0PcMcdSG/5HwaQzkptn29E0zCWJUqmP0W/4scSC80AVh/8hgws4tuqv1GWvr4MiBZhIbUEO4f3Pc58OYQ==", "engines": { "node": ">=20" } }, "node_modules/@cspell/cspell-types": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.6.0.tgz", - "integrity": "sha512-JTqrD47tV+rWc1y2W8T0NTfWLQMlSWX4OF64/Jf3WbsOD+4UXVIfjRlzPry7+1Zekm6pa38+23jkDBytYpu8yw==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.6.3.tgz", + "integrity": "sha512-oDTzZ2kG/jJk3TaupESUckDraGJbBpRBEW1xgTrWyIU+uGwdmMXPcGr9XZq9dRS5Zxm01nTgLwxpVM/3BVTvWQ==", "engines": { "node": ">=20" } }, + "node_modules/@cspell/cspell-worker": { + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-worker/-/cspell-worker-9.6.3.tgz", + "integrity": "sha512-zZccf1jLSrqIvlYAqwnnBi4RrLVfSEfWT4eYpiyIzHXHMzWnkUXEstQCG6LFK4L9A44M/w9s8szi7R4DLBzKsA==", + "dependencies": { + "cspell-lib": "9.6.3" + }, + "engines": { + "node": ">=20.18" + } + }, "node_modules/@cspell/dict-ada": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/@cspell/dict-ada/-/dict-ada-4.1.1.tgz", @@ -205,19 +224,19 @@ "integrity": "sha512-CyfphrbMyl4Ms55Vzuj+mNmd693HjBFr9hvU+B2YbFEZprE5AG+EXLYTMRWrXbpds4AuZcvN3deM2XVB80BN/Q==" }, "node_modules/@cspell/dict-en_us": { - "version": "4.4.27", - "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.27.tgz", - "integrity": "sha512-0y4vH2i5cFmi8sxkc4OlD2IlnqDznOtKczm4h6jA288g5VVrm3bhkYK6vcB8b0CoRKtYWKet4VEmHBP1yI+Qfw==" + "version": "4.4.28", + "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.28.tgz", + "integrity": "sha512-/rzhbZaZDsDWmXbc9Fmmr4/ngmaNcG2b+TGT+ZjGqpOXVQYI75yZ9+XduyI43xJ5O38QcX3QIbJY5GWaJqxPEg==" }, "node_modules/@cspell/dict-en-common-misspellings": { - "version": "2.1.11", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.11.tgz", - "integrity": "sha512-2jcY494If1udvzd7MT2z/QH/RACUo/I02vIY4ttNdZhgYvUmRKhg8OBdrbzYo0lJOcc7XUb8rhIFQRHzxOSVeA==" + "version": "2.1.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.12.tgz", + "integrity": "sha512-14Eu6QGqyksqOd4fYPuRb58lK1Va7FQK9XxFsRKnZU8LhL3N+kj7YKDW+7aIaAN/0WGEqslGP6lGbQzNti8Akw==" }, "node_modules/@cspell/dict-en-gb-mit": { - "version": "3.1.16", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.16.tgz", - "integrity": "sha512-4PPdapCJslytxAVJu35Mv97qDyGmAQxtDE790T2bWNhcqN6gvRVAc/eTRaXkUIf21q1xCxxNNqpH4VfMup69rQ==" + "version": "3.1.17", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.17.tgz", + "integrity": "sha512-MLx+3XN9rj+EGwLIFmh0gpEDNalCyQqjcszp+WkedCHcvTCzQgWXQMZK6cPuhO/OKYyW9GOwsx4t0wjU5tRVNg==" }, "node_modules/@cspell/dict-filetypes": { "version": "3.0.15", @@ -240,9 +259,9 @@ "integrity": "sha512-imhs0u87wEA4/cYjgzS0tAyaJpwG7vwtC8UyMFbwpmtw+/bgss+osNfyqhYRyS/ehVCWL17Ewx2UPkexjKyaBA==" }, "node_modules/@cspell/dict-fullstack": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.7.tgz", - "integrity": "sha512-IxEk2YAwAJKYCUEgEeOg3QvTL4XLlyArJElFuMQevU1dPgHgzWElFevN5lsTFnvMFA1riYsVinqJJX0BanCFEg==" + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.8.tgz", + "integrity": "sha512-J6EeoeThvx/DFrcA2rJiCA6vfqwJMbkG0IcXhlsmRZmasIpanmxgt90OEaUazbZahFiuJT8wrhgQ1QgD1MsqBw==" }, "node_modules/@cspell/dict-gaming-terms": { "version": "1.1.2", @@ -250,9 +269,9 @@ "integrity": "sha512-9XnOvaoTBscq0xuD6KTEIkk9hhdfBkkvJAIsvw3JMcnp1214OCGW8+kako5RqQ2vTZR3Tnf3pc57o7VgkM0q1Q==" }, "node_modules/@cspell/dict-git": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.0.7.tgz", - "integrity": "sha512-odOwVKgfxCQfiSb+nblQZc4ErXmnWEnv8XwkaI4sNJ7cNmojnvogYVeMqkXPjvfrgEcizEEA4URRD2Ms5PDk1w==" + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.1.0.tgz", + "integrity": "sha512-KEt9zGkxqGy2q1nwH4CbyqTSv5nadpn8BAlDnzlRcnL0Xb3LX9xTgSGShKvzb0bw35lHoYyLWN2ZKAqbC4pgGQ==" }, "node_modules/@cspell/dict-golang": { "version": "6.0.26", @@ -300,9 +319,9 @@ "integrity": "sha512-J3NzzfgmxRvEeOe3qUXnSJQCd38i/dpF9/t3quuWh6gXM+krsAXP75dY1CzDmS8mrJAlBdVBeAW5eAZTD8g86Q==" }, "node_modules/@cspell/dict-latex": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-4.0.4.tgz", - "integrity": "sha512-YdTQhnTINEEm/LZgTzr9Voz4mzdOXH7YX+bSFs3hnkUHCUUtX/mhKgf1CFvZ0YNM2afjhQcmLaR9bDQVyYBvpA==" + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-5.0.0.tgz", + "integrity": "sha512-HUrIqUVohM6P0+5b7BsdAdb0STIv0aaFBvguI7pLcreljlcX3FSPUxea7ticzNlCNeVrEaiEn/ws9m6rYUeuNw==" }, "node_modules/@cspell/dict-lorem-ipsum": { "version": "4.0.5", @@ -336,14 +355,14 @@ "integrity": "sha512-MN7Vs11TdP5mbdNFQP5x2Ac8zOBm97ARg6zM5Sb53YQt/eMvXOMvrep7+/+8NJXs0jkp70bBzjqU4APcqBFNAw==" }, "node_modules/@cspell/dict-node": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.8.tgz", - "integrity": "sha512-AirZcN2i84ynev3p2/1NCPEhnNsHKMz9zciTngGoqpdItUb2bDt1nJBjwlsrFI78GZRph/VaqTVFwYikmncpXg==" + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.9.tgz", + "integrity": "sha512-hO+ga+uYZ/WA4OtiMEyKt5rDUlUyu3nXMf8KVEeqq2msYvAPdldKBGH7lGONg6R/rPhv53Rb+0Y1SLdoK1+7wQ==" }, "node_modules/@cspell/dict-npm": { - "version": "5.2.29", - "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.29.tgz", - "integrity": "sha512-ZAef8JpYmbuHFT1zekj/YyImLPvZevjECw663EmG5GPePyNo4AfH8Dd2fFhaOyQ3P5I5LrkAhGwypnOfUxcssw==" + "version": "5.2.32", + "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.32.tgz", + "integrity": "sha512-H0XD0eg4d96vevle8VUKVoPhsgsw003ByJ47XzipyiMKoQTZ2IAUW+VTkQq8wU1floarNjmThQJOoKL9J4UYuw==" }, "node_modules/@cspell/dict-php": { "version": "4.1.1", @@ -379,9 +398,9 @@ "integrity": "sha512-9PJQB3cfkBULrMLp5kSAcFPpzf8oz9vFN+QYZABhQwWkGbuzCIXSorHrmWSASlx4yejt3brjaWS57zZ/YL5ZQQ==" }, "node_modules/@cspell/dict-rust": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.1.1.tgz", - "integrity": "sha512-fXiXnZH0wOaEVTKFRNaz6TsUGhuB8dAT0ubYkDNzRQCaV5JGSOebGb1v2x5ZrOSVp+moxWM/vdBfiNU6KOEaFQ==" + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.1.2.tgz", + "integrity": "sha512-O1FHrumYcO+HZti3dHfBPUdnDFkI+nbYK3pxYmiM1sr+G0ebOd6qchmswS0Wsc6ZdEVNiPYJY/gZQR6jfW3uOg==" }, "node_modules/@cspell/dict-scala": { "version": "5.0.9", @@ -434,11 +453,11 @@ "integrity": "sha512-XibBIxBlVosU06+M6uHWkFeT0/pW5WajDRYdXG2CgHnq85b0TI/Ks0FuBJykmsgi2CAD3Qtx8UHFEtl/DSFnAQ==" }, "node_modules/@cspell/dynamic-import": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.6.0.tgz", - "integrity": "sha512-Lkn82wyGj2ltxeYfH2bEjshdes1fx3ouYUZxeW5i6SBBvEVJoSmr43AygI8A317UMIQxVj59qVBorrtGYcRI1w==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.6.3.tgz", + "integrity": "sha512-J2RArbv02H0fZCZxfGe2RjhEBFrcBlWgEESh2kDdF3CyoXBoPneevS5L3X4dk2XpOR0LU6bCJEsVIuzJqoFDbw==", "dependencies": { - "@cspell/url": "9.6.0", + "@cspell/url": "9.6.3", "import-meta-resolve": "^4.2.0" }, "engines": { @@ -446,25 +465,33 @@ } }, "node_modules/@cspell/filetypes": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.6.0.tgz", - "integrity": "sha512-CaWyk5j20H6sr+HCArtUY95jUQb7A/6W0GC4B4umnqoWvgqwR72duowLFa+w1K2C7tZg3GoV4Wf2cUn9jjt5FA==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.6.3.tgz", + "integrity": "sha512-FocAActFpUanhQblokOQYlsV3yt3xC6FNMnziGURG9f1a5LYPGwmb6v40qkkhsTwK8L9L7Ai1KRtPJ3zyowNCA==", "engines": { "node": ">=20" } }, + "node_modules/@cspell/rpc": { + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/rpc/-/rpc-9.6.3.tgz", + "integrity": "sha512-D8ouhYPOZR11CI66GKsFu/05sSTSjxwfyUsTZ0m7lQOcILxkJ0P/y4DJ9HffFT6uY62mEbxDeibvlfCLBzWO4w==", + "engines": { + "node": ">=20.18" + } + }, "node_modules/@cspell/strong-weak-map": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.6.0.tgz", - "integrity": "sha512-9g8LCLv/2RrprGeGnFAaBETWq7ESnBcoMbvgNu+vZE58iF+pbFvP0qGgKvVeKEEpc2LZhNuHLsUH37MUS6DOQg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.6.3.tgz", + "integrity": "sha512-2OmE4RCSJG1mAfVsZqEvThJaQY//rYjDBycHfb1pfLb3KlV+O5jNKlYrI6E/+JpiTb1cI9MnzIRw6uzTPgCN1g==", "engines": { "node": ">=20" } }, "node_modules/@cspell/url": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.6.0.tgz", - "integrity": "sha512-257WOxh9vOYHAVgBNXRCdLEd+ldzlVbzcc9u+6DYoCDCNGe0OvOWOGsAfnUbMc9xEw48XgBlDYgOlPbjWGLOTg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.6.3.tgz", + "integrity": "sha512-k+o5Dp8Hp8mjex8Lpe9m9B4LsrMoEzAaaYfvagUPQW1BKPwi3ugkH9YkC7uUOvzD6hOWq77WJZ2t946zY2NDSg==", "engines": { "node": ">=20" } @@ -536,9 +563,9 @@ } }, "node_modules/commander": { - "version": "14.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", - "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", "engines": { "node": ">=20" } @@ -562,25 +589,27 @@ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, "node_modules/cspell": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.6.0.tgz", - "integrity": "sha512-Mpf0oT2KAHTIb3YPAXWhW64/4CZKW5Lka4j1YxCLK3jM3nenmIsY/ocrJvqCMF4+1eejRF0N55sT3XmrijI5YQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.6.3.tgz", + "integrity": "sha512-eGfq/qCJXDNLtqvwo3RFOJ8ECQD45NSEqlEdxJPdMlu/MA7YXSm4QptkJTybdodZmQpIGNpAz8UtVjKwhseqZg==", "dependencies": { - "@cspell/cspell-json-reporter": "9.6.0", - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-types": "9.6.0", - "@cspell/dynamic-import": "9.6.0", - "@cspell/url": "9.6.0", + "@cspell/cspell-json-reporter": "9.6.3", + "@cspell/cspell-performance-monitor": "9.6.3", + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-types": "9.6.3", + "@cspell/cspell-worker": "9.6.3", + "@cspell/dynamic-import": "9.6.3", + "@cspell/url": "9.6.3", "ansi-regex": "^6.2.2", "chalk": "^5.6.2", "chalk-template": "^1.1.2", - "commander": "^14.0.2", - "cspell-config-lib": "9.6.0", - "cspell-dictionary": "9.6.0", - "cspell-gitignore": "9.6.0", - "cspell-glob": "9.6.0", - "cspell-io": "9.6.0", - "cspell-lib": "9.6.0", + "commander": "^14.0.3", + "cspell-config-lib": "9.6.3", + "cspell-dictionary": "9.6.3", + "cspell-gitignore": "9.6.3", + "cspell-glob": "9.6.3", + "cspell-io": "9.6.3", + "cspell-lib": "9.6.3", "fast-json-stable-stringify": "^2.1.0", "flatted": "^3.3.3", "semver": "^7.7.3", @@ -591,18 +620,18 @@ "cspell-esm": "bin.mjs" }, "engines": { - "node": ">=20" + "node": ">=20.18" }, "funding": { "url": "https://github.com/streetsidesoftware/cspell?sponsor=1" } }, "node_modules/cspell-config-lib": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.6.0.tgz", - "integrity": "sha512-5ztvheawkmFXNHGN82iOOntU3T5mmlQBP/plgoKdBZ6+lSYrOJLkOyqxYyi7MrUBDtWrXPzFllkBrPNRDlbX/A==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.6.3.tgz", + "integrity": "sha512-gQnpAzyf7rPaIb2hjVDtkvfhNc+7hAeHjK+RFAHj7fXiMfdPOWMxnl5IZBOdd9aYHZzVbxYkeyvJbLwF4M3YSg==", "dependencies": { - "@cspell/cspell-types": "9.6.0", + "@cspell/cspell-types": "9.6.3", "comment-json": "^4.5.1", "smol-toml": "^1.6.0", "yaml": "^2.8.2" @@ -612,13 +641,14 @@ } }, "node_modules/cspell-dictionary": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.6.0.tgz", - "integrity": "sha512-wW0m1kLrbK6bRY/GrLUGKUUJ1Z4ZUgIb8LD4zNaECcvGviv9V7VcR3mEwUip3ZjoHa3ClzEoWgQ9gXrtac80Wg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.6.3.tgz", + "integrity": "sha512-y5te3Wu89WIdUYPYqMKUliviFxSu7xImuEacct6f2XFQd2c4G9vNduRMJjHKJT49cwkRM/fZKtOzJyPy8jzQ4g==", "dependencies": { - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-types": "9.6.0", - "cspell-trie-lib": "9.6.0", + "@cspell/cspell-performance-monitor": "9.6.3", + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-types": "9.6.3", + "cspell-trie-lib": "9.6.3", "fast-equals": "^6.0.0" }, "engines": { @@ -626,13 +656,13 @@ } }, "node_modules/cspell-gitignore": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.6.0.tgz", - "integrity": "sha512-8GfmJuRBBvibyPHnNE2wYJAiQ/ceDYLD1X1sUQaCyj6hPMR7ChJiVhFPtS11hMqkjZ46OBMYTMGWqO792L9fEQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.6.3.tgz", + "integrity": "sha512-S6XAddSjGEP7opCfEkhWaTnNVCI8ypdyZWgOW/gUW3VMpq8zK7OJ/ddyOLUCIMW1Qwtkx7X4Mf06xJSBWEjKjQ==", "dependencies": { - "@cspell/url": "9.6.0", - "cspell-glob": "9.6.0", - "cspell-io": "9.6.0" + "@cspell/url": "9.6.3", + "cspell-glob": "9.6.3", + "cspell-io": "9.6.3" }, "bin": { "cspell-gitignore": "bin.mjs" @@ -642,11 +672,11 @@ } }, "node_modules/cspell-glob": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.6.0.tgz", - "integrity": "sha512-KmEbKN0qdEamsEYbkFu7zjLYfw3hMmn9kmeh94IHr2kq6vWq5vNP5l1BuqmrUeFZlbNd07vj08IKAZHYsoGheQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.6.3.tgz", + "integrity": "sha512-tcyQP0LXoAEExVzWZMxW4afyo7w/8nea0wskoWQ4G+k36Gk6P52CARARFymHCH4IZLbbybZuLoVDxQ6OgIm3fQ==", "dependencies": { - "@cspell/url": "9.6.0", + "@cspell/url": "9.6.3", "picomatch": "^4.0.3" }, "engines": { @@ -654,12 +684,12 @@ } }, "node_modules/cspell-grammar": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.6.0.tgz", - "integrity": "sha512-jZVIM5/3eB9rWURDq+VXdYip+DmPuFzO+bqaRtzqT8w6YoOIGYbiIxdwvyyA9xdH7SmW8uqHJP5x4pzZju1lNQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.6.3.tgz", + "integrity": "sha512-26Pn/zo9hY3/5hGkM4tpV/Nnn4Op1J0DGnA34vA/lDBGtDOFexUEcUHZOieuNtCvZO735ltZPrP3zVxts1CwRg==", "dependencies": { - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-types": "9.6.0" + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-types": "9.6.3" }, "bin": { "cspell-grammar": "bin.mjs" @@ -669,38 +699,40 @@ } }, "node_modules/cspell-io": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.6.0.tgz", - "integrity": "sha512-wZuZzKOYIb698kVEINYjGaNFQu+AFZ945TORM3hapmPjez+vsHwl8m/pPpCHeGMpQtHMEDkX84AbQ7R55MRIwg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.6.3.tgz", + "integrity": "sha512-dZYowJVTWPEjik3y/UrJnX/3PG20N1jgnP//lwX6cLGtHjv05W89lnHxsh5Suzxf3mkN/YZ1JUgmxdjj9HduNw==", "dependencies": { - "@cspell/cspell-service-bus": "9.6.0", - "@cspell/url": "9.6.0" + "@cspell/cspell-service-bus": "9.6.3", + "@cspell/url": "9.6.3" }, "engines": { "node": ">=20" } }, "node_modules/cspell-lib": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.6.0.tgz", - "integrity": "sha512-m9rIv8hkQ3Dio4s80HQbM9cdxENcd6pS8j2AHWL50OSjJf3Xhw6/wMrIAGbwLHP15K6QZVU2eJ/abCzIJwjA4w==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.6.3.tgz", + "integrity": "sha512-LFZsCWJX5EjcD0EzF/tb9Sx1d/nKEW6436EDqqb5u/Vxr86LxgX9RbhwkHI7e0XyX3YV64QzPrYGvEkXEuGsCQ==", "dependencies": { - "@cspell/cspell-bundled-dicts": "9.6.0", - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-resolver": "9.6.0", - "@cspell/cspell-types": "9.6.0", - "@cspell/dynamic-import": "9.6.0", - "@cspell/filetypes": "9.6.0", - "@cspell/strong-weak-map": "9.6.0", - "@cspell/url": "9.6.0", + "@cspell/cspell-bundled-dicts": "9.6.3", + "@cspell/cspell-performance-monitor": "9.6.3", + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-resolver": "9.6.3", + "@cspell/cspell-types": "9.6.3", + "@cspell/dynamic-import": "9.6.3", + "@cspell/filetypes": "9.6.3", + "@cspell/rpc": "9.6.3", + "@cspell/strong-weak-map": "9.6.3", + "@cspell/url": "9.6.3", "clear-module": "^4.1.2", - "cspell-config-lib": "9.6.0", - "cspell-dictionary": "9.6.0", - "cspell-glob": "9.6.0", - "cspell-grammar": "9.6.0", - "cspell-io": "9.6.0", - "cspell-trie-lib": "9.6.0", - "env-paths": "^3.0.0", + "cspell-config-lib": "9.6.3", + "cspell-dictionary": "9.6.3", + "cspell-glob": "9.6.3", + "cspell-grammar": "9.6.3", + "cspell-io": "9.6.3", + "cspell-trie-lib": "9.6.3", + "env-paths": "^4.0.0", "gensequence": "^8.0.8", "import-fresh": "^3.3.1", "resolve-from": "^5.0.0", @@ -713,22 +745,25 @@ } }, "node_modules/cspell-trie-lib": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.6.0.tgz", - "integrity": "sha512-L7GSff5F9cF60QT78WsebVlb3sppi6jbvTHwsw7WF1jUN/ioAo7OzBYtYB7xkYeejcdVEpqfvf/ZOXPDp8x2Wg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.6.3.tgz", + "integrity": "sha512-bTlL3UjcBJyQXx67RMFcgHh0AXKd2w6Zw8iZkAcU7KVgAgRpGwCiF3LJLHignnMm+Pn8D3Xrx0raENaMh4uGaQ==", "engines": { "node": ">=20" }, "peerDependencies": { - "@cspell/cspell-types": "9.6.0" + "@cspell/cspell-types": "9.6.3" } }, "node_modules/env-paths": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", - "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-4.0.0.tgz", + "integrity": "sha512-pxP8eL2SwwaTRi/KHYwLYXinDs7gL3jxFcBYmEdYfZmZXbaVDvdppd0XBU8qVz03rDfKZMXg1omHCbsJjZrMsw==", + "dependencies": { + "is-safe-filename": "^0.1.0" + }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -855,6 +890,17 @@ "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, + "node_modules/is-safe-filename": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-safe-filename/-/is-safe-filename-0.1.1.tgz", + "integrity": "sha512-4SrR7AdnY11LHfDKTZY1u6Ga3RuxZdl3YKWWShO5iyuG5h8QS4GD2tOb04peBJ5I7pXbR+CGBNEhTcwK+FzN3g==", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/parent-module": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-2.0.0.tgz", @@ -963,9 +1009,9 @@ }, "dependencies": { "@cspell/cspell-bundled-dicts": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.6.0.tgz", - "integrity": "sha512-gLNe9bB+5gMsTEhR9YPE0Wt122HR2EV+Q1j9W+MbwbeBJmpTWrgAP1ZdpvHOg+6LF6x/bD/EC9HfWdd/om8wXA==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.6.3.tgz", + "integrity": "sha512-0Ibx+ynlSd8wMAoUmc2Ck4SDN27eJheM45aCmCvCA8saROwkDh7j8zBz7aTTUTtFN+pcotJoNxr71LLD+KXhgQ==", "requires": { "@cspell/dict-ada": "^4.1.1", "@cspell/dict-al": "^1.1.1", @@ -982,16 +1028,16 @@ "@cspell/dict-docker": "^1.1.17", "@cspell/dict-dotnet": "^5.0.11", "@cspell/dict-elixir": "^4.0.8", - "@cspell/dict-en_us": "^4.4.27", - "@cspell/dict-en-common-misspellings": "^2.1.11", - "@cspell/dict-en-gb-mit": "^3.1.16", + "@cspell/dict-en_us": "^4.4.28", + "@cspell/dict-en-common-misspellings": "^2.1.12", + "@cspell/dict-en-gb-mit": "^3.1.17", "@cspell/dict-filetypes": "^3.0.15", "@cspell/dict-flutter": "^1.1.1", "@cspell/dict-fonts": "^4.0.5", "@cspell/dict-fsharp": "^1.1.1", - "@cspell/dict-fullstack": "^3.2.7", + "@cspell/dict-fullstack": "^3.2.8", "@cspell/dict-gaming-terms": "^1.1.2", - "@cspell/dict-git": "^3.0.7", + "@cspell/dict-git": "^3.1.0", "@cspell/dict-golang": "^6.0.26", "@cspell/dict-google": "^1.0.9", "@cspell/dict-haskell": "^4.0.6", @@ -1001,21 +1047,21 @@ "@cspell/dict-julia": "^1.1.1", "@cspell/dict-k8s": "^1.0.12", "@cspell/dict-kotlin": "^1.1.1", - "@cspell/dict-latex": "^4.0.4", + "@cspell/dict-latex": "^5.0.0", "@cspell/dict-lorem-ipsum": "^4.0.5", "@cspell/dict-lua": "^4.0.8", "@cspell/dict-makefile": "^1.0.5", "@cspell/dict-markdown": "^2.0.14", "@cspell/dict-monkeyc": "^1.0.12", - "@cspell/dict-node": "^5.0.8", - "@cspell/dict-npm": "^5.2.29", + "@cspell/dict-node": "^5.0.9", + "@cspell/dict-npm": "^5.2.32", "@cspell/dict-php": "^4.1.1", "@cspell/dict-powershell": "^5.0.15", "@cspell/dict-public-licenses": "^2.0.15", "@cspell/dict-python": "^4.2.25", "@cspell/dict-r": "^2.1.1", "@cspell/dict-ruby": "^5.1.0", - "@cspell/dict-rust": "^4.1.1", + "@cspell/dict-rust": "^4.1.2", "@cspell/dict-scala": "^5.0.9", "@cspell/dict-shell": "^1.1.2", "@cspell/dict-software-terms": "^5.1.20", @@ -1029,35 +1075,48 @@ } }, "@cspell/cspell-json-reporter": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.6.0.tgz", - "integrity": "sha512-5sY1lgAXS5xEOsjT5rREMADj7pHIt56XOL7xR80nNl0TwlpZbeBHhoB2aH5sirVTeodJFN5iraXNbVOYPPupPw==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.6.3.tgz", + "integrity": "sha512-4jhqXKGCFAQXomtk4/Ldy/GiGEocC61v8GISiUgn1mH+HPgEvkJijyxKRNFYvzXOoJr4y0KrkGBoKk5FI7cipw==", "requires": { - "@cspell/cspell-types": "9.6.0" + "@cspell/cspell-types": "9.6.3" } }, + "@cspell/cspell-performance-monitor": { + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-performance-monitor/-/cspell-performance-monitor-9.6.3.tgz", + "integrity": "sha512-Y1I0wg7MUTouubREyPeTJe2dKNbBZPBnd6kDNcVet5DRZ3Cck2udS9m1a6DhJO2sGQgHTBULPDBEUU5tcAZ+nQ==" + }, "@cspell/cspell-pipe": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.6.0.tgz", - "integrity": "sha512-YNuY8NNXfE+8Qzknm2ps6QbrZLZu6rSZTZr3dYW3K6TK7+IFVlJ6e2Z9iKJTqp6aZ4AGU/r9QYGmNX4Oq4gZ0A==" + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.6.3.tgz", + "integrity": "sha512-Q0M58JbgHWOOOYvSyBodEysXLP5t8Q58Ff08msj2/XxRFpowR4iIUyfg3k+/d06uyOy89l+RD5AmyTEa5410xg==" }, "@cspell/cspell-resolver": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.6.0.tgz", - "integrity": "sha512-Gb2UWNmRpTOQGpYL4Q/LMw+b50KcRZcf/wJg6w0Yl3IT+F/uDNhNh1f5rHuTyGsbMsMxHJhsb2AoP+73GlbIfw==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.6.3.tgz", + "integrity": "sha512-yUMTC8vl+LeRcIeXRrxn0GXL+rurf4OR3uyqZbG6bbtuttvq/Icleeibv9Wts+n700HLp+sVXJ7BrCn0Ehobsw==", "requires": { "global-directory": "^4.0.1" } }, "@cspell/cspell-service-bus": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.6.0.tgz", - "integrity": "sha512-DCuKKkySTEB8MPLTdoPMdmakYcx7XCsHz1YEMbzOcLqJCxXsRlRZg4qE9kRBee/2QY7eYA2kaYNgn/TDMooa4g==" + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.6.3.tgz", + "integrity": "sha512-gDUDq0PcMcdSG/5HwaQzkptn29E0zCWJUqmP0W/4scSC80AVh/8hgws4tuqv1GWvr4MiBZhIbUEO4f3Pc58OYQ==" }, "@cspell/cspell-types": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.6.0.tgz", - "integrity": "sha512-JTqrD47tV+rWc1y2W8T0NTfWLQMlSWX4OF64/Jf3WbsOD+4UXVIfjRlzPry7+1Zekm6pa38+23jkDBytYpu8yw==" + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.6.3.tgz", + "integrity": "sha512-oDTzZ2kG/jJk3TaupESUckDraGJbBpRBEW1xgTrWyIU+uGwdmMXPcGr9XZq9dRS5Zxm01nTgLwxpVM/3BVTvWQ==" + }, + "@cspell/cspell-worker": { + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/cspell-worker/-/cspell-worker-9.6.3.tgz", + "integrity": "sha512-zZccf1jLSrqIvlYAqwnnBi4RrLVfSEfWT4eYpiyIzHXHMzWnkUXEstQCG6LFK4L9A44M/w9s8szi7R4DLBzKsA==", + "requires": { + "cspell-lib": "9.6.3" + } }, "@cspell/dict-ada": { "version": "4.1.1", @@ -1138,19 +1197,19 @@ "integrity": "sha512-CyfphrbMyl4Ms55Vzuj+mNmd693HjBFr9hvU+B2YbFEZprE5AG+EXLYTMRWrXbpds4AuZcvN3deM2XVB80BN/Q==" }, "@cspell/dict-en_us": { - "version": "4.4.27", - "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.27.tgz", - "integrity": "sha512-0y4vH2i5cFmi8sxkc4OlD2IlnqDznOtKczm4h6jA288g5VVrm3bhkYK6vcB8b0CoRKtYWKet4VEmHBP1yI+Qfw==" + "version": "4.4.28", + "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.28.tgz", + "integrity": "sha512-/rzhbZaZDsDWmXbc9Fmmr4/ngmaNcG2b+TGT+ZjGqpOXVQYI75yZ9+XduyI43xJ5O38QcX3QIbJY5GWaJqxPEg==" }, "@cspell/dict-en-common-misspellings": { - "version": "2.1.11", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.11.tgz", - "integrity": "sha512-2jcY494If1udvzd7MT2z/QH/RACUo/I02vIY4ttNdZhgYvUmRKhg8OBdrbzYo0lJOcc7XUb8rhIFQRHzxOSVeA==" + "version": "2.1.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.12.tgz", + "integrity": "sha512-14Eu6QGqyksqOd4fYPuRb58lK1Va7FQK9XxFsRKnZU8LhL3N+kj7YKDW+7aIaAN/0WGEqslGP6lGbQzNti8Akw==" }, "@cspell/dict-en-gb-mit": { - "version": "3.1.16", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.16.tgz", - "integrity": "sha512-4PPdapCJslytxAVJu35Mv97qDyGmAQxtDE790T2bWNhcqN6gvRVAc/eTRaXkUIf21q1xCxxNNqpH4VfMup69rQ==" + "version": "3.1.17", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.17.tgz", + "integrity": "sha512-MLx+3XN9rj+EGwLIFmh0gpEDNalCyQqjcszp+WkedCHcvTCzQgWXQMZK6cPuhO/OKYyW9GOwsx4t0wjU5tRVNg==" }, "@cspell/dict-filetypes": { "version": "3.0.15", @@ -1173,9 +1232,9 @@ "integrity": "sha512-imhs0u87wEA4/cYjgzS0tAyaJpwG7vwtC8UyMFbwpmtw+/bgss+osNfyqhYRyS/ehVCWL17Ewx2UPkexjKyaBA==" }, "@cspell/dict-fullstack": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.7.tgz", - "integrity": "sha512-IxEk2YAwAJKYCUEgEeOg3QvTL4XLlyArJElFuMQevU1dPgHgzWElFevN5lsTFnvMFA1riYsVinqJJX0BanCFEg==" + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.8.tgz", + "integrity": "sha512-J6EeoeThvx/DFrcA2rJiCA6vfqwJMbkG0IcXhlsmRZmasIpanmxgt90OEaUazbZahFiuJT8wrhgQ1QgD1MsqBw==" }, "@cspell/dict-gaming-terms": { "version": "1.1.2", @@ -1183,9 +1242,9 @@ "integrity": "sha512-9XnOvaoTBscq0xuD6KTEIkk9hhdfBkkvJAIsvw3JMcnp1214OCGW8+kako5RqQ2vTZR3Tnf3pc57o7VgkM0q1Q==" }, "@cspell/dict-git": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.0.7.tgz", - "integrity": "sha512-odOwVKgfxCQfiSb+nblQZc4ErXmnWEnv8XwkaI4sNJ7cNmojnvogYVeMqkXPjvfrgEcizEEA4URRD2Ms5PDk1w==" + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.1.0.tgz", + "integrity": "sha512-KEt9zGkxqGy2q1nwH4CbyqTSv5nadpn8BAlDnzlRcnL0Xb3LX9xTgSGShKvzb0bw35lHoYyLWN2ZKAqbC4pgGQ==" }, "@cspell/dict-golang": { "version": "6.0.26", @@ -1233,9 +1292,9 @@ "integrity": "sha512-J3NzzfgmxRvEeOe3qUXnSJQCd38i/dpF9/t3quuWh6gXM+krsAXP75dY1CzDmS8mrJAlBdVBeAW5eAZTD8g86Q==" }, "@cspell/dict-latex": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-4.0.4.tgz", - "integrity": "sha512-YdTQhnTINEEm/LZgTzr9Voz4mzdOXH7YX+bSFs3hnkUHCUUtX/mhKgf1CFvZ0YNM2afjhQcmLaR9bDQVyYBvpA==" + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-5.0.0.tgz", + "integrity": "sha512-HUrIqUVohM6P0+5b7BsdAdb0STIv0aaFBvguI7pLcreljlcX3FSPUxea7ticzNlCNeVrEaiEn/ws9m6rYUeuNw==" }, "@cspell/dict-lorem-ipsum": { "version": "4.0.5", @@ -1264,14 +1323,14 @@ "integrity": "sha512-MN7Vs11TdP5mbdNFQP5x2Ac8zOBm97ARg6zM5Sb53YQt/eMvXOMvrep7+/+8NJXs0jkp70bBzjqU4APcqBFNAw==" }, "@cspell/dict-node": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.8.tgz", - "integrity": "sha512-AirZcN2i84ynev3p2/1NCPEhnNsHKMz9zciTngGoqpdItUb2bDt1nJBjwlsrFI78GZRph/VaqTVFwYikmncpXg==" + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.9.tgz", + "integrity": "sha512-hO+ga+uYZ/WA4OtiMEyKt5rDUlUyu3nXMf8KVEeqq2msYvAPdldKBGH7lGONg6R/rPhv53Rb+0Y1SLdoK1+7wQ==" }, "@cspell/dict-npm": { - "version": "5.2.29", - "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.29.tgz", - "integrity": "sha512-ZAef8JpYmbuHFT1zekj/YyImLPvZevjECw663EmG5GPePyNo4AfH8Dd2fFhaOyQ3P5I5LrkAhGwypnOfUxcssw==" + "version": "5.2.32", + "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.32.tgz", + "integrity": "sha512-H0XD0eg4d96vevle8VUKVoPhsgsw003ByJ47XzipyiMKoQTZ2IAUW+VTkQq8wU1floarNjmThQJOoKL9J4UYuw==" }, "@cspell/dict-php": { "version": "4.1.1", @@ -1307,9 +1366,9 @@ "integrity": "sha512-9PJQB3cfkBULrMLp5kSAcFPpzf8oz9vFN+QYZABhQwWkGbuzCIXSorHrmWSASlx4yejt3brjaWS57zZ/YL5ZQQ==" }, "@cspell/dict-rust": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.1.1.tgz", - "integrity": "sha512-fXiXnZH0wOaEVTKFRNaz6TsUGhuB8dAT0ubYkDNzRQCaV5JGSOebGb1v2x5ZrOSVp+moxWM/vdBfiNU6KOEaFQ==" + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.1.2.tgz", + "integrity": "sha512-O1FHrumYcO+HZti3dHfBPUdnDFkI+nbYK3pxYmiM1sr+G0ebOd6qchmswS0Wsc6ZdEVNiPYJY/gZQR6jfW3uOg==" }, "@cspell/dict-scala": { "version": "5.0.9", @@ -1362,28 +1421,33 @@ "integrity": "sha512-XibBIxBlVosU06+M6uHWkFeT0/pW5WajDRYdXG2CgHnq85b0TI/Ks0FuBJykmsgi2CAD3Qtx8UHFEtl/DSFnAQ==" }, "@cspell/dynamic-import": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.6.0.tgz", - "integrity": "sha512-Lkn82wyGj2ltxeYfH2bEjshdes1fx3ouYUZxeW5i6SBBvEVJoSmr43AygI8A317UMIQxVj59qVBorrtGYcRI1w==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.6.3.tgz", + "integrity": "sha512-J2RArbv02H0fZCZxfGe2RjhEBFrcBlWgEESh2kDdF3CyoXBoPneevS5L3X4dk2XpOR0LU6bCJEsVIuzJqoFDbw==", "requires": { - "@cspell/url": "9.6.0", + "@cspell/url": "9.6.3", "import-meta-resolve": "^4.2.0" } }, "@cspell/filetypes": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.6.0.tgz", - "integrity": "sha512-CaWyk5j20H6sr+HCArtUY95jUQb7A/6W0GC4B4umnqoWvgqwR72duowLFa+w1K2C7tZg3GoV4Wf2cUn9jjt5FA==" + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.6.3.tgz", + "integrity": "sha512-FocAActFpUanhQblokOQYlsV3yt3xC6FNMnziGURG9f1a5LYPGwmb6v40qkkhsTwK8L9L7Ai1KRtPJ3zyowNCA==" + }, + "@cspell/rpc": { + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/rpc/-/rpc-9.6.3.tgz", + "integrity": "sha512-D8ouhYPOZR11CI66GKsFu/05sSTSjxwfyUsTZ0m7lQOcILxkJ0P/y4DJ9HffFT6uY62mEbxDeibvlfCLBzWO4w==" }, "@cspell/strong-weak-map": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.6.0.tgz", - "integrity": "sha512-9g8LCLv/2RrprGeGnFAaBETWq7ESnBcoMbvgNu+vZE58iF+pbFvP0qGgKvVeKEEpc2LZhNuHLsUH37MUS6DOQg==" + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.6.3.tgz", + "integrity": "sha512-2OmE4RCSJG1mAfVsZqEvThJaQY//rYjDBycHfb1pfLb3KlV+O5jNKlYrI6E/+JpiTb1cI9MnzIRw6uzTPgCN1g==" }, "@cspell/url": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.6.0.tgz", - "integrity": "sha512-257WOxh9vOYHAVgBNXRCdLEd+ldzlVbzcc9u+6DYoCDCNGe0OvOWOGsAfnUbMc9xEw48XgBlDYgOlPbjWGLOTg==" + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.6.3.tgz", + "integrity": "sha512-k+o5Dp8Hp8mjex8Lpe9m9B4LsrMoEzAaaYfvagUPQW1BKPwi3ugkH9YkC7uUOvzD6hOWq77WJZ2t946zY2NDSg==" }, "ansi-regex": { "version": "6.2.2", @@ -1423,9 +1487,9 @@ } }, "commander": { - "version": "14.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", - "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==" + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==" }, "comment-json": { "version": "4.5.1", @@ -1443,25 +1507,27 @@ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, "cspell": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.6.0.tgz", - "integrity": "sha512-Mpf0oT2KAHTIb3YPAXWhW64/4CZKW5Lka4j1YxCLK3jM3nenmIsY/ocrJvqCMF4+1eejRF0N55sT3XmrijI5YQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.6.3.tgz", + "integrity": "sha512-eGfq/qCJXDNLtqvwo3RFOJ8ECQD45NSEqlEdxJPdMlu/MA7YXSm4QptkJTybdodZmQpIGNpAz8UtVjKwhseqZg==", "requires": { - "@cspell/cspell-json-reporter": "9.6.0", - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-types": "9.6.0", - "@cspell/dynamic-import": "9.6.0", - "@cspell/url": "9.6.0", + "@cspell/cspell-json-reporter": "9.6.3", + "@cspell/cspell-performance-monitor": "9.6.3", + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-types": "9.6.3", + "@cspell/cspell-worker": "9.6.3", + "@cspell/dynamic-import": "9.6.3", + "@cspell/url": "9.6.3", "ansi-regex": "^6.2.2", "chalk": "^5.6.2", "chalk-template": "^1.1.2", - "commander": "^14.0.2", - "cspell-config-lib": "9.6.0", - "cspell-dictionary": "9.6.0", - "cspell-gitignore": "9.6.0", - "cspell-glob": "9.6.0", - "cspell-io": "9.6.0", - "cspell-lib": "9.6.0", + "commander": "^14.0.3", + "cspell-config-lib": "9.6.3", + "cspell-dictionary": "9.6.3", + "cspell-gitignore": "9.6.3", + "cspell-glob": "9.6.3", + "cspell-io": "9.6.3", + "cspell-lib": "9.6.3", "fast-json-stable-stringify": "^2.1.0", "flatted": "^3.3.3", "semver": "^7.7.3", @@ -1469,85 +1535,88 @@ } }, "cspell-config-lib": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.6.0.tgz", - "integrity": "sha512-5ztvheawkmFXNHGN82iOOntU3T5mmlQBP/plgoKdBZ6+lSYrOJLkOyqxYyi7MrUBDtWrXPzFllkBrPNRDlbX/A==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.6.3.tgz", + "integrity": "sha512-gQnpAzyf7rPaIb2hjVDtkvfhNc+7hAeHjK+RFAHj7fXiMfdPOWMxnl5IZBOdd9aYHZzVbxYkeyvJbLwF4M3YSg==", "requires": { - "@cspell/cspell-types": "9.6.0", + "@cspell/cspell-types": "9.6.3", "comment-json": "^4.5.1", "smol-toml": "^1.6.0", "yaml": "^2.8.2" } }, "cspell-dictionary": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.6.0.tgz", - "integrity": "sha512-wW0m1kLrbK6bRY/GrLUGKUUJ1Z4ZUgIb8LD4zNaECcvGviv9V7VcR3mEwUip3ZjoHa3ClzEoWgQ9gXrtac80Wg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.6.3.tgz", + "integrity": "sha512-y5te3Wu89WIdUYPYqMKUliviFxSu7xImuEacct6f2XFQd2c4G9vNduRMJjHKJT49cwkRM/fZKtOzJyPy8jzQ4g==", "requires": { - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-types": "9.6.0", - "cspell-trie-lib": "9.6.0", + "@cspell/cspell-performance-monitor": "9.6.3", + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-types": "9.6.3", + "cspell-trie-lib": "9.6.3", "fast-equals": "^6.0.0" } }, "cspell-gitignore": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.6.0.tgz", - "integrity": "sha512-8GfmJuRBBvibyPHnNE2wYJAiQ/ceDYLD1X1sUQaCyj6hPMR7ChJiVhFPtS11hMqkjZ46OBMYTMGWqO792L9fEQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.6.3.tgz", + "integrity": "sha512-S6XAddSjGEP7opCfEkhWaTnNVCI8ypdyZWgOW/gUW3VMpq8zK7OJ/ddyOLUCIMW1Qwtkx7X4Mf06xJSBWEjKjQ==", "requires": { - "@cspell/url": "9.6.0", - "cspell-glob": "9.6.0", - "cspell-io": "9.6.0" + "@cspell/url": "9.6.3", + "cspell-glob": "9.6.3", + "cspell-io": "9.6.3" } }, "cspell-glob": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.6.0.tgz", - "integrity": "sha512-KmEbKN0qdEamsEYbkFu7zjLYfw3hMmn9kmeh94IHr2kq6vWq5vNP5l1BuqmrUeFZlbNd07vj08IKAZHYsoGheQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.6.3.tgz", + "integrity": "sha512-tcyQP0LXoAEExVzWZMxW4afyo7w/8nea0wskoWQ4G+k36Gk6P52CARARFymHCH4IZLbbybZuLoVDxQ6OgIm3fQ==", "requires": { - "@cspell/url": "9.6.0", + "@cspell/url": "9.6.3", "picomatch": "^4.0.3" } }, "cspell-grammar": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.6.0.tgz", - "integrity": "sha512-jZVIM5/3eB9rWURDq+VXdYip+DmPuFzO+bqaRtzqT8w6YoOIGYbiIxdwvyyA9xdH7SmW8uqHJP5x4pzZju1lNQ==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.6.3.tgz", + "integrity": "sha512-26Pn/zo9hY3/5hGkM4tpV/Nnn4Op1J0DGnA34vA/lDBGtDOFexUEcUHZOieuNtCvZO735ltZPrP3zVxts1CwRg==", "requires": { - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-types": "9.6.0" + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-types": "9.6.3" } }, "cspell-io": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.6.0.tgz", - "integrity": "sha512-wZuZzKOYIb698kVEINYjGaNFQu+AFZ945TORM3hapmPjez+vsHwl8m/pPpCHeGMpQtHMEDkX84AbQ7R55MRIwg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.6.3.tgz", + "integrity": "sha512-dZYowJVTWPEjik3y/UrJnX/3PG20N1jgnP//lwX6cLGtHjv05W89lnHxsh5Suzxf3mkN/YZ1JUgmxdjj9HduNw==", "requires": { - "@cspell/cspell-service-bus": "9.6.0", - "@cspell/url": "9.6.0" + "@cspell/cspell-service-bus": "9.6.3", + "@cspell/url": "9.6.3" } }, "cspell-lib": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.6.0.tgz", - "integrity": "sha512-m9rIv8hkQ3Dio4s80HQbM9cdxENcd6pS8j2AHWL50OSjJf3Xhw6/wMrIAGbwLHP15K6QZVU2eJ/abCzIJwjA4w==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.6.3.tgz", + "integrity": "sha512-LFZsCWJX5EjcD0EzF/tb9Sx1d/nKEW6436EDqqb5u/Vxr86LxgX9RbhwkHI7e0XyX3YV64QzPrYGvEkXEuGsCQ==", "requires": { - "@cspell/cspell-bundled-dicts": "9.6.0", - "@cspell/cspell-pipe": "9.6.0", - "@cspell/cspell-resolver": "9.6.0", - "@cspell/cspell-types": "9.6.0", - "@cspell/dynamic-import": "9.6.0", - "@cspell/filetypes": "9.6.0", - "@cspell/strong-weak-map": "9.6.0", - "@cspell/url": "9.6.0", + "@cspell/cspell-bundled-dicts": "9.6.3", + "@cspell/cspell-performance-monitor": "9.6.3", + "@cspell/cspell-pipe": "9.6.3", + "@cspell/cspell-resolver": "9.6.3", + "@cspell/cspell-types": "9.6.3", + "@cspell/dynamic-import": "9.6.3", + "@cspell/filetypes": "9.6.3", + "@cspell/rpc": "9.6.3", + "@cspell/strong-weak-map": "9.6.3", + "@cspell/url": "9.6.3", "clear-module": "^4.1.2", - "cspell-config-lib": "9.6.0", - "cspell-dictionary": "9.6.0", - "cspell-glob": "9.6.0", - "cspell-grammar": "9.6.0", - "cspell-io": "9.6.0", - "cspell-trie-lib": "9.6.0", - "env-paths": "^3.0.0", + "cspell-config-lib": "9.6.3", + "cspell-dictionary": "9.6.3", + "cspell-glob": "9.6.3", + "cspell-grammar": "9.6.3", + "cspell-io": "9.6.3", + "cspell-trie-lib": "9.6.3", + "env-paths": "^4.0.0", "gensequence": "^8.0.8", "import-fresh": "^3.3.1", "resolve-from": "^5.0.0", @@ -1557,15 +1626,18 @@ } }, "cspell-trie-lib": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.6.0.tgz", - "integrity": "sha512-L7GSff5F9cF60QT78WsebVlb3sppi6jbvTHwsw7WF1jUN/ioAo7OzBYtYB7xkYeejcdVEpqfvf/ZOXPDp8x2Wg==", + "version": "9.6.3", + "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.6.3.tgz", + "integrity": "sha512-bTlL3UjcBJyQXx67RMFcgHh0AXKd2w6Zw8iZkAcU7KVgAgRpGwCiF3LJLHignnMm+Pn8D3Xrx0raENaMh4uGaQ==", "requires": {} }, "env-paths": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", - "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==" + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-4.0.0.tgz", + "integrity": "sha512-pxP8eL2SwwaTRi/KHYwLYXinDs7gL3jxFcBYmEdYfZmZXbaVDvdppd0XBU8qVz03rDfKZMXg1omHCbsJjZrMsw==", + "requires": { + "is-safe-filename": "^0.1.0" + } }, "esprima": { "version": "4.0.1", @@ -1640,6 +1712,11 @@ "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==" }, + "is-safe-filename": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-safe-filename/-/is-safe-filename-0.1.1.tgz", + "integrity": "sha512-4SrR7AdnY11LHfDKTZY1u6Ga3RuxZdl3YKWWShO5iyuG5h8QS4GD2tOb04peBJ5I7pXbR+CGBNEhTcwK+FzN3g==" + }, "parent-module": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-2.0.0.tgz", diff --git a/eng/common/spelling/package.json b/eng/common/spelling/package.json index 93b0dbaa3deb..11e19df811cc 100644 --- a/eng/common/spelling/package.json +++ b/eng/common/spelling/package.json @@ -2,6 +2,6 @@ "name": "cspell-version-pin", "version": "1.0.0", "dependencies": { - "cspell": "^9.6.0" + "cspell": "^9.6.3" } } From f4a59d46e400ca36b84ffeab0ae19796cd774bce Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Tue, 3 Feb 2026 10:29:38 -0800 Subject: [PATCH 30/84] Change default sampler to Rate Limited Sampler (#44925) * Change default sampler to Rate Limited Sampler * Add CHANGELOG * Modified CHANGELOG * Add period * Retrigger CI/CD pipeline * Address feedback * Retrigger CI/CD pipeline * Retrigger CI/CD pipeline --- .../azure-monitor-opentelemetry/CHANGELOG.md | 2 ++ .../azure-monitor-opentelemetry/README.md | 8 +++-- .../azure/monitor/opentelemetry/_configure.py | 10 +++--- .../opentelemetry/_utils/configurations.py | 17 +++++----- .../tracing/sampling_configurations.py | 32 +++++++++++++------ .../tests/utils/test_configurations.py | 10 +++--- 6 files changed, 49 insertions(+), 30 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md index c323344495e6..9c6f6a521016 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md @@ -8,6 +8,8 @@ ([#44902](https://github.com/Azure/azure-sdk-for-python/pull/44902)) ### Breaking Changes +- The default sampling behavior has been changed from ApplicationInsightsSampler with 100% sampling (all traces sampled) to RateLimitedSampler with 5.0 traces per second. This change significantly reduces telemetry volume for high-traffic applications and provides better cost optimization out of the box. Impact: Applications with more than 5 requests per second will see fewer traces exported by default. + ([#44925](https://github.com/Azure/azure-sdk-for-python/pull/44925)) ### Bugs Fixed diff --git a/sdk/monitor/azure-monitor-opentelemetry/README.md b/sdk/monitor/azure-monitor-opentelemetry/README.md index 2373227a08cf..6a660db22034 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/README.md +++ b/sdk/monitor/azure-monitor-opentelemetry/README.md @@ -70,7 +70,8 @@ You can use `configure_azure_monitor` to set up instrumentation for your app to | `views` | A list of [views][ot_view] that will be used to customize metrics exported by the SDK. | `N/A` | | `log_record_processors` | A list of [log record processors][ot_log_record_processor] that will process log records before they are exported. | `N/A` | | `metric_readers` | A list of [metric reader][ot_metric_reader] that will process metric readers before they are exported | `N/A` | -| `traces_per_second` | Configures the Rate Limited sampler by specifying the maximum number of traces to sample per second. When set, this automatically enables the rate-limited sampler. Alternatively, you can configure sampling using the `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG` environment variables as described in the table below. Please note that the sampling configuration via environment variables will have precedence over the sampling exporter/distro options. | `N/A` +| `sampling_ratio` | Configures the Application Insights Sampler specifying the percentage of traces to be sampled. Has to be a value between 0 and 1. For example, 0.1 sampling ratio would mean sampling 10% of all the traces. Defaults to 1.0 i.e 100% sampling rate. **Please note that the sampling configuration via environment variables will have precedence over the sampling exporter/distro options.** | `N/A` +| `traces_per_second` | Configures the Rate Limited Sampler by specifying the maximum number of traces to sample per second. When set, this automatically enables the rate-limited sampler. Alternatively, you can configure sampling using the `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG` environment variables as described in the table below. To switch back to fixed percentage sampler, set the sampling_ratio to the desired value, ex. 1.0. Please refer to [sampling_configurations] sample file for more clarity on sampler configuration. **Please note that the sampling configuration via environment variables will have precedence over the sampling exporter/distro options.** | `N/A` You can configure further with [OpenTelemetry environment variables][ot_env_vars]. @@ -82,8 +83,8 @@ You can configure further with [OpenTelemetry environment variables][ot_env_vars | `OTEL_TRACES_EXPORTER` | If set to `None`, disables collection and export of distributed tracing telemetry. | | `OTEL_BLRP_SCHEDULE_DELAY` | Specifies the logging export interval in milliseconds. Defaults to 5000. | | `OTEL_BSP_SCHEDULE_DELAY` | Specifies the distributed tracing export interval in milliseconds. Defaults to 5000. | -| `OTEL_TRACES_SAMPLER` | Specifies the sampler to be used for traces. Supports `always_on`, `always_off`, `trace_id_ratio`, `parentbased_always_on`, `parentbased_always_off`, `parentbased_trace_id_ratio`, [application_insights_sampling] and [rate_limited_sampling]. Use `microsoft.fixed_percentage` for the Application Insights sampler or `microsoft.rate_limited` for the Rate Limited sampler. | -| `OTEL_TRACES_SAMPLER_ARG` | Specifies the sampling parameter for the configured sampler. For the standard OpenTelemetry samplers `trace_id_ratio` and `parentbased_trace_id_ratio`, this is the sampling ratio in the range [0.0, 1.0]. Not needed to be specified for `always_on`, `always_off`, `parentbased_always_on`, or `parentbased_always_off` samplers. For the Application Insights sampler, this sets the ratio of distributed tracing telemetry to be [sampled][application_insights_sampling] with accepted values in the range [0,1]. Defaults to 1.0 (no sampling). For the Rate Limited sampler, this sets the maximum traces per second to be [sampled][rate_limited_sampler]. For example, 0.5 means one trace every two seconds, while 5.0 means five traces per second. | +| `OTEL_TRACES_SAMPLER` | Specifies the sampler to be used for traces. Supports `always_on`, `always_off`, `trace_id_ratio`, `parentbased_always_on`, `parentbased_always_off`, `parentbased_trace_id_ratio`, [application_insights_sampling] and [rate_limited_sampling]. Use `microsoft.fixed_percentage` for the Application Insights sampler or `microsoft.rate_limited` for the Rate Limited sampler. **The default sampler is `Rate Limited Sampler` with the default value of 5.0 traces per second**| +| `OTEL_TRACES_SAMPLER_ARG` | Specifies the sampling parameter for the configured sampler. For the standard OpenTelemetry samplers `trace_id_ratio` and `parentbased_trace_id_ratio`, this is the sampling ratio in the range [0.0, 1.0]. Not needed to be specified for `always_on`, `always_off`, `parentbased_always_on`, or `parentbased_always_off` samplers. For the Application Insights sampler, this sets the ratio of distributed tracing telemetry to be [sampled][application_insights_sampling] with accepted values in the range [0,1]. For the Rate Limited sampler, this sets the maximum traces per second to be [sampled][rate_limited_sampler]. Defaults to 5.0 traces per second. For example, 0.5 means one trace every two seconds, while 5.0 means five traces per second. | | `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS` | Specifies which of the supported instrumentations to disable. Disabled instrumentations will not be instrumented as part of `configure_azure_monitor`. However, they can still be manually instrumented with `instrument()` directly. Accepts a comma-separated list of lowercase [Library Names](#officially-supported-instrumentations). For example, set to `"psycopg2,fastapi"` to disable the Psycopg2 and FastAPI instrumentations. Defaults to an empty list, enabling all supported instrumentations. | | `OTEL_EXPERIMENTAL_RESOURCE_DETECTORS` | An experimental OpenTelemetry environment variable used to specify Resource Detectors to be used to generate Resource Attributes. This is an experimental feature and the name of this variable and its behavior can change in a non-backwards compatible way. Defaults to "azure_app_service,azure_vm" to enable the [Azure Resource Detectors][ot_resource_detector_azure] for Azure App Service and Azure VM. To add or remove specific resource detectors, set the environment variable accordingly. See the [OpenTelemetry Python Resource Detector Documentation][ot_python_resource_detectors] for more. | @@ -268,4 +269,5 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio [python_logging_formatter]: https://docs.python.org/3/library/logging.html#formatter-objects [python_logging_level]: https://docs.python.org/3/library/logging.html#levels [samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-opentelemetry/samples +[sampling_configurations]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py [samples_manual]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py index af8988a6b891..04f9224d14b1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py @@ -166,15 +166,15 @@ def _setup_tracing(configurations: Dict[str, ConfigurationValue]): sampler_type = configurations[SAMPLER_TYPE] sampler = _get_sampler_from_name(sampler_type, sampler_arg) tracer_provider = TracerProvider(sampler=sampler, resource=resource) - elif SAMPLING_TRACES_PER_SECOND_ARG in configurations: - traces_per_second = configurations[SAMPLING_TRACES_PER_SECOND_ARG] + elif SAMPLING_RATIO_ARG in configurations: + sampling_ratio = configurations[SAMPLING_RATIO_ARG] tracer_provider = TracerProvider( - sampler=RateLimitedSampler(target_spans_per_second_limit=cast(float, traces_per_second)), resource=resource + sampler=ApplicationInsightsSampler(sampling_ratio=cast(float, sampling_ratio)), resource=resource ) else: - sampling_ratio = configurations[SAMPLING_RATIO_ARG] + traces_per_second = configurations[SAMPLING_TRACES_PER_SECOND_ARG] tracer_provider = TracerProvider( - sampler=ApplicationInsightsSampler(sampling_ratio=cast(float, sampling_ratio)), resource=resource + sampler=RateLimitedSampler(target_spans_per_second_limit=cast(float, traces_per_second)), resource=resource ) for span_processor in configurations[SPAN_PROCESSORS_ARG]: # type: ignore diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py index 183017cd5d91..bda7524f118f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/configurations.py @@ -168,16 +168,17 @@ def _default_resource(configurations): # pylint: disable=too-many-statements,too-many-branches def _default_sampling_ratio(configurations): default_value = 1.0 + default_value_for_rate_limited_sampler = 5.0 sampler_type = environ.get(OTEL_TRACES_SAMPLER) sampler_arg = environ.get(OTEL_TRACES_SAMPLER_ARG) # Handle rate-limited sampler if sampler_type == RATE_LIMITED_SAMPLER: try: - sampler_value = float(sampler_arg) if sampler_arg is not None else default_value + sampler_value = float(sampler_arg) if sampler_arg is not None else default_value_for_rate_limited_sampler if sampler_value < 0.0: _logger.error("Invalid value for OTEL_TRACES_SAMPLER_ARG. It should be a non-negative number.") - sampler_value = default_value + sampler_value = default_value_for_rate_limited_sampler else: _logger.info("Using rate limited sampler: %s traces per second", sampler_value) configurations[SAMPLING_TRACES_PER_SECOND_ARG] = sampler_value @@ -185,10 +186,10 @@ def _default_sampling_ratio(configurations): _logger.error( # pylint: disable=C _INVALID_TRACES_PER_SECOND_MESSAGE, OTEL_TRACES_SAMPLER_ARG, - default_value, + default_value_for_rate_limited_sampler, e, ) - configurations[SAMPLING_TRACES_PER_SECOND_ARG] = default_value + configurations[SAMPLING_TRACES_PER_SECOND_ARG] = default_value_for_rate_limited_sampler # Handle fixed percentage sampler elif sampler_type in (FIXED_PERCENTAGE_SAMPLER, "microsoft.fixed.percentage"): # to support older string @@ -271,15 +272,15 @@ def _default_sampling_ratio(configurations): # Handle all other cases (no sampler type specified or unsupported sampler type) else: - if configurations.get(SAMPLING_RATIO_ARG) is None: - configurations[SAMPLING_RATIO_ARG] = default_value + if configurations.get(SAMPLING_TRACES_PER_SECOND_ARG) is None: + configurations[SAMPLING_TRACES_PER_SECOND_ARG] = default_value_for_rate_limited_sampler if sampler_type is not None: _logger.error( # pylint: disable=C "Invalid argument for the sampler to be used for tracing. " "Supported values are %s. Defaulting to %s: %s", SUPPORTED_OTEL_SAMPLERS, - FIXED_PERCENTAGE_SAMPLER, - configurations[SAMPLING_RATIO_ARG], + RATE_LIMITED_SAMPLER, + configurations[SAMPLING_TRACES_PER_SECOND_ARG], ) diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py index 747b34312e22..55370292dece 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py @@ -17,8 +17,8 @@ # Using trace_id_ratio sampler # Set the OTEL_TRACES_SAMPLER environment variable to "trace_id_ratio" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.1, it has to be a number between 0 and 1, else it will throw an error and default to 1.0 -# The sampling rate is 0.1 means approximately 10% of your traces are sent +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.1; it must be a number between 0 and 1 or it defaults to 1.0. +# A sampling rate of 0.1 means approximately 10% of your traces are sent. # Using parentbased_always_on sampler # Set the OTEL_TRACES_SAMPLER environment variable to "parentbased_always_on" @@ -30,26 +30,40 @@ # Using parentbased_trace_id_ratio sampler # Set the OTEL_TRACES_SAMPLER environment variable to "parentbased_trace_id_ratio" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.45, it has to be a number between 0 and 1, else it will throw an error and default to 1.0 -# The sampling rate is 0.45 means approximately 45% of your traces are sent +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.45; it must be a number between 0 and 1 or it defaults to 1.0. +# A sampling rate of 0.45 means approximately 45% of your traces are sent. -# Using rate limited sampler +# Using rate limited sampler (this is the default sampler) # Set the OTEL_TRACES_SAMPLER environment variable to "microsoft.rate_limited" # Set the OTEL_TRACES_SAMPLER_ARG environment variable to the desired rate limit (e.g., 0.5 means one trace every two seconds, while 5.0 means five traces per second) +# You can also configure the rate limited sampler by passing the `traces_per_second` argument to `configure_azure_monitor`. + +""" + configure_azure_monitor ( + traces_per_second: 0.5, + ) +""" # Using fixed percentage sampler # Set the OTEL_TRACES_SAMPLER environment variable to "microsoft.fixed_percentage" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.2, it has to be a number between 0 and 1, else it will throw an error and default to 1.0 +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.2; it must be a number between 0 and 1 or it defaults to 1.0. +# When configuring sampling via `configure_azure_monitor`, the default sampler is rate limited. To use the classic Application Insights sampler instead, set `sampling_ratio` to 1.0. # pylint: disable=line-too-long + +""" + configure_azure_monitor ( + sampling_ratio: 1.0, + ) +""" # Using trace_based_sampling configuration # cspell: ignore unsampled # Determines whether the logger should drop log records associated with unsampled traces. -# Passing the enable_trace_based_sampling_for_logs=True argument to configure_azure_monitor ensure that log records associated with unsampled traces are dropped by the `Logger`. +# Passing the enable_trace_based_sampling_for_logs=True argument to configure_azure_monitor ensures that log records associated with unsampled traces are dropped by the logger. # A log record is considered associated with an unsampled trace if it has a valid `SpanId` and its `TraceFlags` indicate that the trace is unsampled. -# The value of this config is False by default +# The value of this config is False by default. """ configure_azure_monitor ( - "enable_trace_based_sampling_for_logs": True, + enable_trace_based_sampling_for_logs: True, ) """ diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py index 7684db635893..e4bdc34f5a5c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py @@ -151,7 +151,7 @@ def test_get_configurations_defaults(self, resource_create_mock): self.assertEqual(configurations["resource"].attributes, TEST_DEFAULT_RESOURCE.attributes) self.assertEqual(environ[OTEL_EXPERIMENTAL_RESOURCE_DETECTORS], "azure_app_service,azure_vm") resource_create_mock.assert_called_once_with() - self.assertEqual(configurations["sampling_ratio"], 1.0) + self.assertEqual(configurations["traces_per_second"], 5.0) self.assertTrue("credential" not in configurations) self.assertTrue("storage_directory" not in configurations) self.assertEqual(configurations["enable_live_metrics"], True) @@ -199,7 +199,7 @@ def test_get_configurations_env_vars(self, resource_create_mock): self.assertEqual(configurations["resource"].attributes, TEST_DEFAULT_RESOURCE.attributes) self.assertEqual(environ[OTEL_EXPERIMENTAL_RESOURCE_DETECTORS], "custom_resource_detector") resource_create_mock.assert_called_once_with() - self.assertEqual(configurations["sampling_ratio"], 1.0) + self.assertEqual(configurations["traces_per_second"], 5.0) @patch.dict( "os.environ", @@ -527,7 +527,7 @@ def test_get_configurations_env_vars_no_preference(self, resource_create_mock): self.assertEqual(configurations["resource"].attributes, TEST_DEFAULT_RESOURCE.attributes) self.assertEqual(environ[OTEL_EXPERIMENTAL_RESOURCE_DETECTORS], "custom_resource_detector") resource_create_mock.assert_called_once_with() - self.assertEqual(configurations["sampling_ratio"], 1.0) + self.assertEqual(configurations["traces_per_second"], 5.0) @patch.dict( "os.environ", @@ -565,7 +565,7 @@ def test_get_configurations_env_vars_check_default(self, resource_create_mock): self.assertEqual(configurations["resource"].attributes, TEST_DEFAULT_RESOURCE.attributes) self.assertEqual(environ[OTEL_EXPERIMENTAL_RESOURCE_DETECTORS], "custom_resource_detector") resource_create_mock.assert_called_once_with() - self.assertEqual(configurations["sampling_ratio"], 1.0) + self.assertEqual(configurations["traces_per_second"], 5.0) @patch.dict( "os.environ", @@ -854,7 +854,7 @@ def test_get_configurations_env_vars_no_sampling_env_set(self, resource_create_m self.assertTrue("connection_string" not in configurations) self.assertEqual(configurations["resource"].attributes, TEST_DEFAULT_RESOURCE.attributes) - self.assertEqual(configurations["sampling_ratio"], 1.0) + self.assertEqual(configurations["traces_per_second"], 5.0) # Tests for the _get_sampler_from_name function def test_get_sampler_from_name_always_on_off(self): From aaae5dd354cff433a31aca8cdab72e3745d6ec60 Mon Sep 17 00:00:00 2001 From: amber-Chen-86 Date: Tue, 3 Feb 2026 10:36:17 -0800 Subject: [PATCH 31/84] [Conversation authoring] fix pylint/pyright for next version (#44876) * updated serialization * updated model base * updated dev requirements * updated tests * updated samples * fix mypy * Updated. * udpated. * udpated --------- Co-authored-by: Rajarshi Sarkar <73562869+sarkar-rajarshi@users.noreply.github.com> --- .../authoring/_utils/model_base.py | 133 ++++++++++++++++-- .../authoring/_utils/serialization.py | 17 ++- .../dev_requirements.txt | 3 +- .../async/sample_authentication_async.py | 6 +- ..._delete_deployment_from_resources_async.py | 4 +- .../async/sample_delete_project_async.py | 2 +- .../sample_delete_trained_model_async.py | 2 +- .../async/sample_deploy_project_async.py | 4 +- .../async/sample_export_project_async.py | 2 +- ...t_assign_project_resources_status_async.py | 6 +- ...ment_delete_from_resources_status_async.py | 5 +- ...mple_get_model_evaluation_results_async.py | 6 +- ...mple_get_model_evaluation_summary_async.py | 6 +- ...unassign_project_resources_status_async.py | 5 +- .../async/sample_import_project_async.py | 2 +- ...ist_assigned_resource_deployments_async.py | 9 +- .../sample_list_project_resources_async.py | 1 - .../async/sample_load_snapshot_async.py | 2 +- .../async/sample_swap_deployments_async.py | 2 +- .../samples/async/sample_train_async.py | 2 +- .../samples/sample_authentication.py | 6 +- .../samples/sample_deploy_project.py | 4 +- ...ple_get_assign_project_resources_status.py | 5 +- ...deployment_delete_from_resources_status.py | 5 +- ...e_get_unassign_project_resources_status.py | 5 +- ...mple_list_assigned_resource_deployments.py | 5 +- .../samples/sample_list_project_resources.py | 1 - .../tests/test_cancel_training_job.py | 1 - .../tests/test_cancel_training_job_async.py | 1 - .../tests/test_create_project_async.py | 5 +- .../tests/test_delete_deployment.py | 1 - .../tests/test_delete_deployment_async.py | 1 - .../tests/test_delete_project.py | 2 - .../tests/test_export_project.py | 1 - .../test_get_model_evaluation_results.py | 2 - ...test_get_model_evaluation_results_async.py | 1 - .../test_get_model_evaluation_summary.py | 1 - .../tests/test_import_project.py | 1 - ...test_list_assigned_resource_deployments.py | 1 - ...ist_assigned_resource_deployments_async.py | 3 +- .../tests/test_list_project_resources.py | 1 - .../tests/test_load_snapshot.py | 1 - .../tests/test_load_snapshot_async.py | 1 - .../tests/test_swap_deployments_async.py | 2 +- 44 files changed, 181 insertions(+), 95 deletions(-) diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/model_base.py index 430bda7b37fc..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/model_base.py @@ -22,7 +22,7 @@ from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder import xml.etree.ElementTree as ET -from collections.abc import MutableMapping # pylint:disable=import-error +from collections.abc import MutableMapping from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,15 +688,29 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - return super().__new__(cls) # pylint:disable=no-value-for-parameter + return super().__new__(cls) def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/serialization.py index 45a3e44e45cb..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/azure/ai/language/conversations/authoring/_utils/serialization.py @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/dev_requirements.txt index 0e53b6a72db5..396f26f367a1 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core -aiohttp \ No newline at end of file +aiohttp +../../identity/azure-identity \ No newline at end of file diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_authentication_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_authentication_async.py index 622cd2b53d60..c7af98dd8e1f 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_authentication_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_authentication_async.py @@ -48,11 +48,11 @@ async def sample_authentication_api_key_async(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] key = os.environ["AZURE_CONVERSATIONS_KEY"] - clu_client = ConversationAuthoringClient(endpoint, AzureKeyCredential(key)) + clu_client = ConversationAuthoringClient(endpoint, AzureKeyCredential(key)) # pylint: disable=unused-variable # [END create_clu_client_with_key_async] -async def sample_authentication_with_azure_active_directory(): +async def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -63,7 +63,7 @@ async def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - clu_client = ConversationAuthoringClient(endpoint, credential=credential) + clu_client = ConversationAuthoringClient(endpoint, credential=credential) # pylint: disable=unused-variable async def main(): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_deployment_from_resources_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_deployment_from_resources_async.py index fd1833eca5ec..0569ec3d03ee 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_deployment_from_resources_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_deployment_from_resources_async.py @@ -38,7 +38,7 @@ from azure.ai.language.conversations.authoring.models import ProjectResourceIds -async def sample_delete_deployment_from_resources_async(): +async def sample_delete_deployment_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] @@ -73,7 +73,7 @@ async def sample_delete_deployment_from_resources_async(): async def main(): - await sample_delete_deployment_from_resources_async() + await sample_delete_deployment_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_project_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_project_async.py index 8b2c4d4218b8..46147750551e 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_project_async.py @@ -29,7 +29,7 @@ # [START conversation_authoring_delete_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_trained_model_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_trained_model_async.py index 7efe692f5ad0..9491ff57fb76 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_trained_model_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_delete_trained_model_async.py @@ -30,7 +30,7 @@ # [START conversation_authoring_delete_trained_model_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_deploy_project_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_deploy_project_async.py index 8879f1625a6c..5fa50cef9e5d 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_deploy_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_deploy_project_async.py @@ -40,13 +40,11 @@ # [START conversation_authoring_deploy_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import ( CreateDeploymentDetails, - AssignedProjectResource, - # DataGenerationConnectionInfo, # uncomment if you need AOAI data generation settings ) diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_export_project_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_export_project_async.py index 1276a3791417..8e6d58cb9225 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_export_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_export_project_async.py @@ -29,7 +29,7 @@ # [START conversation_authoring_export_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import ExportedProjectFormat diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_assign_project_resources_status_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_assign_project_resources_status_async.py index c4874c9cb75a..d0f3e7aefb42 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_assign_project_resources_status_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_assign_project_resources_status_async.py @@ -34,10 +34,8 @@ from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import ProjectResourcesState - -async def sample_get_assign_project_resources_status_async(): +async def sample_assign_project_res_status_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -66,7 +64,7 @@ async def sample_get_assign_project_resources_status_async(): async def main(): - await sample_get_assign_project_resources_status_async() + await sample_assign_project_res_status_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_deployment_delete_from_resources_status_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_deployment_delete_from_resources_status_async.py index af434372ecb2..021da7691df0 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_deployment_delete_from_resources_status_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_deployment_delete_from_resources_status_async.py @@ -34,10 +34,9 @@ from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import DeploymentDeleteFromResourcesState -async def sample_get_deployment_delete_from_resources_status_async(): +async def sample_deployment_delete_status_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -69,7 +68,7 @@ async def sample_get_deployment_delete_from_resources_status_async(): async def main(): - await sample_get_deployment_delete_from_resources_status_async() + await sample_deployment_delete_status_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_results_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_results_async.py index 5112ada9d5ac..b14a8205e4f2 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_results_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_results_async.py @@ -31,11 +31,11 @@ # [START conversation_authoring_get_model_evaluation_results_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -async def sample_get_model_evaluation_results_async(): +async def sample_model_eval_results_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -83,7 +83,7 @@ async def sample_get_model_evaluation_results_async(): async def main(): - await sample_get_model_evaluation_results_async() + await sample_model_eval_results_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_summary_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_summary_async.py index 1c6cd354bda6..d11889e6958d 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_summary_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_model_evaluation_summary_async.py @@ -32,11 +32,11 @@ # [START conversation_authoring_get_model_evaluation_summary_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -async def sample_get_model_evaluation_summary_async(): +async def sample_get_model_eval_summary_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -114,7 +114,7 @@ async def sample_get_model_evaluation_summary_async(): async def main(): - await sample_get_model_evaluation_summary_async() + await sample_get_model_eval_summary_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_unassign_project_resources_status_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_unassign_project_resources_status_async.py index bea05a59ad1c..6528c06009c1 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_unassign_project_resources_status_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_get_unassign_project_resources_status_async.py @@ -34,10 +34,9 @@ from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import ProjectResourcesState -async def sample_get_unassign_project_resources_status_async(): +async def sample_unassign_project_res_status_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -67,7 +66,7 @@ async def sample_get_unassign_project_resources_status_async(): async def main(): - await sample_get_unassign_project_resources_status_async() + await sample_unassign_project_res_status_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_import_project_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_import_project_async.py index 6a7140876791..c7ebd923bf44 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_import_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_import_project_async.py @@ -29,7 +29,7 @@ # [START conversation_authoring_import_project_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import ( diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_assigned_resource_deployments_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_assigned_resource_deployments_async.py index eb8686ec2fb7..521c4c89643d 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_assigned_resource_deployments_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_assigned_resource_deployments_async.py @@ -27,17 +27,12 @@ # [START conversation_authoring_list_assigned_resource_deployments_async] import os import asyncio -from datetime import date, datetime from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import ( - AssignedProjectDeploymentsMetadata, - AssignedProjectDeploymentMetadata, -) -async def sample_list_assigned_resource_deployments_async(): +async def sample_list_assigned_deployments_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] @@ -62,7 +57,7 @@ async def sample_list_assigned_resource_deployments_async(): async def main(): - await sample_list_assigned_resource_deployments_async() + await sample_list_assigned_deployments_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_project_resources_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_project_resources_async.py index 5b65324f6ea6..656c708d1fce 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_project_resources_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_list_project_resources_async.py @@ -33,7 +33,6 @@ from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import AssignedProjectResource async def sample_list_project_resources_async(): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_load_snapshot_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_load_snapshot_async.py index ad06737aef7d..9a671648b8a6 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_load_snapshot_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_load_snapshot_async.py @@ -30,7 +30,7 @@ # [START conversation_authoring_load_snapshot_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_swap_deployments_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_swap_deployments_async.py index b46fba1e3824..9e9c89df4150 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_swap_deployments_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_swap_deployments_async.py @@ -31,7 +31,7 @@ # [START conversation_authoring_swap_deployments_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import SwapDeploymentsDetails diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_train_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_train_async.py index 65a8c734b840..3be762f33916 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_train_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/async/sample_train_async.py @@ -30,7 +30,7 @@ # [START conversation_authoring_train_async] import os import asyncio -from azure.identity import DefaultAzureCredential +from azure.identity.aio import DefaultAzureCredential from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import ( TrainingJobDetails, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_authentication.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_authentication.py index 409869b7560e..14a009a25527 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_authentication.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_authentication.py @@ -48,11 +48,11 @@ def sample_authentication_api_key(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] key = os.environ["AZURE_CONVERSATIONS_KEY"] - clu_client = ConversationAuthoringClient(endpoint, AzureKeyCredential(key)) + clu_client = ConversationAuthoringClient(endpoint, AzureKeyCredential(key)) # pylint: disable=unused-variable # [END create_clu_client_with_key] -def sample_authentication_with_azure_active_directory(): +def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -63,7 +63,7 @@ def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - clu_client = ConversationAuthoringClient(endpoint, credential=credential) + clu_client = ConversationAuthoringClient(endpoint, credential=credential) # pylint: disable=unused-variable def main(): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_deploy_project.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_deploy_project.py index 467eaf93746b..5ccf6fcdf752 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_deploy_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_deploy_project.py @@ -44,8 +44,6 @@ from azure.ai.language.conversations.authoring import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import ( CreateDeploymentDetails, - AssignedProjectResource, - # DataGenerationConnectionInfo, # uncomment if you need AOAI data generation settings ) @@ -136,4 +134,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_assign_project_resources_status.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_assign_project_resources_status.py index 27f884d05261..4c796762091b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_assign_project_resources_status.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_assign_project_resources_status.py @@ -33,10 +33,9 @@ from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import ProjectResourcesState -def sample_get_assign_project_resources_status(): +def sample_assign_project_resources_status(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -65,7 +64,7 @@ def sample_get_assign_project_resources_status(): def main(): - sample_get_assign_project_resources_status() + sample_assign_project_resources_status() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_deployment_delete_from_resources_status.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_deployment_delete_from_resources_status.py index f2fe27a9b181..180fe0942155 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_deployment_delete_from_resources_status.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_deployment_delete_from_resources_status.py @@ -33,10 +33,9 @@ from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import DeploymentDeleteFromResourcesState -def sample_get_deployment_delete_from_resources_status(): +def sample_deployment_delete_status(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -68,7 +67,7 @@ def sample_get_deployment_delete_from_resources_status(): def main(): - sample_get_deployment_delete_from_resources_status() + sample_deployment_delete_status() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_unassign_project_resources_status.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_unassign_project_resources_status.py index ca2c390ebefc..c6b4dc24fbfc 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_unassign_project_resources_status.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_get_unassign_project_resources_status.py @@ -33,10 +33,9 @@ from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import ProjectResourcesState -def sample_get_unassign_project_resources_status(): +def sample_unassign_project_resources_status(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -66,7 +65,7 @@ def sample_get_unassign_project_resources_status(): def main(): - sample_get_unassign_project_resources_status() + sample_unassign_project_resources_status() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_assigned_resource_deployments.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_assigned_resource_deployments.py index b1bb9f414c69..8f4d232308f0 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_assigned_resource_deployments.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_assigned_resource_deployments.py @@ -26,13 +26,12 @@ # [START conversation_authoring_list_assigned_resource_deployments] import os -from datetime import date, datetime from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -def sample_list_assigned_resource_deployments(): +def sample_list_assigned_deployments(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_AUTHORING_ENDPOINT"] @@ -59,7 +58,7 @@ def sample_list_assigned_resource_deployments(): def main(): - sample_list_assigned_resource_deployments() + sample_list_assigned_deployments() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_project_resources.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_project_resources.py index bec0c10550e6..889adc0cc47f 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_project_resources.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/samples/sample_list_project_resources.py @@ -32,7 +32,6 @@ from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import AssignedProjectResource def sample_list_project_resources(): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job.py index 76b212e75e00..944724a3c417 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job.py @@ -4,7 +4,6 @@ from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import TrainingJobResult ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job_async.py index e6b1e912bfcc..9319e8e324a3 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_cancel_training_job_async.py @@ -6,7 +6,6 @@ from devtools_testutils.aio import recorded_by_proxy_async from azure.core.credentials import AzureKeyCredential from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import TrainingJobResult ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_create_project_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_create_project_async.py index 60fbce0ffead..0e6af24ed461 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_create_project_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_create_project_async.py @@ -2,15 +2,14 @@ import functools import pytest -from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy +from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader +from devtools_testutils.aio import recorded_by_proxy_async from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient from azure.ai.language.conversations.authoring.models import ( CreateProjectOptions, ProjectDetails, ProjectKind, ) -from devtools_testutils.aio import recorded_by_proxy_async - from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment.py index fc38f4a9a8b6..4f8bcdf30ef3 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment.py @@ -5,7 +5,6 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import DeploymentState ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment_async.py index d345f504bace..fd6cc8ae2c66 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_deployment_async.py @@ -7,7 +7,6 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import DeploymentState ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_project.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_project.py index 3ae39d8aee9b..b37cd16eceab 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_delete_project.py @@ -1,13 +1,11 @@ # ---------- SYNC ---------- import functools -import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import ProjectDeletionState # optional (type hint only) ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_export_project.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_export_project.py index 3b9abfa48634..807ffca99a22 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_export_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_export_project.py @@ -1,6 +1,5 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results.py index be3901d2472d..76601a9af079 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results.py @@ -1,11 +1,9 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import StringIndexType ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results_async.py index 9cdaf8062b22..c1abe588f7cc 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_results_async.py @@ -6,7 +6,6 @@ from devtools_testutils.aio import recorded_by_proxy_async from azure.core.credentials import AzureKeyCredential from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import StringIndexType ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_summary.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_summary.py index cc628e43be1c..929731387b5d 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_summary.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_get_model_evaluation_summary.py @@ -1,6 +1,5 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_import_project.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_import_project.py index f2b3c75e7f7a..f9d7d9d7ebfa 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_import_project.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_import_project.py @@ -1,6 +1,5 @@ # pylint: disable=line-too-long,useless-suppression import functools -import json from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments.py index fd14ba858011..6c3ea79fde45 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments.py @@ -1,7 +1,6 @@ # pylint: disable=line-too-long,useless-suppression from datetime import date, datetime import functools -from importlib import resources from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments_async.py index 365b09991f22..f5ec0a10f9c3 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_assigned_resource_deployments_async.py @@ -1,6 +1,7 @@ import functools -import pytest from datetime import date, datetime +import pytest + from devtools_testutils import EnvironmentVariableLoader, AzureRecordedTestCase from devtools_testutils.aio import recorded_by_proxy_async diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_project_resources.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_project_resources.py index 0820a8c9cd08..9556d6e4fa88 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_project_resources.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_list_project_resources.py @@ -1,6 +1,5 @@ # pylint: disable=line-too-long,useless-suppression import functools -from importlib import resources from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot.py index 0ce0c2f210e2..1ef8216a8946 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot.py @@ -4,7 +4,6 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import LoadSnapshotState ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot_async.py index e46349d87a29..9aec4fbb2aee 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_load_snapshot_async.py @@ -6,7 +6,6 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import LoadSnapshotState ConversationsPreparer = functools.partial( EnvironmentVariableLoader, diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_swap_deployments_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_swap_deployments_async.py index 329a88db390f..de6b5a084c5d 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_swap_deployments_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations-authoring/tests/test_swap_deployments_async.py @@ -7,7 +7,7 @@ from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError from azure.ai.language.conversations.authoring.aio import ConversationAuthoringClient -from azure.ai.language.conversations.authoring.models import SwapDeploymentsDetails, SwapDeploymentsState +from azure.ai.language.conversations.authoring.models import SwapDeploymentsDetails ConversationsPreparer = functools.partial( EnvironmentVariableLoader, From c2cbafc183622aedb6c0ad2468cb71f5d6e842f8 Mon Sep 17 00:00:00 2001 From: amber-Chen-86 Date: Tue, 3 Feb 2026 10:39:27 -0800 Subject: [PATCH 32/84] [Conversation Inference] fix pylint/pyright for next version (#44854) * updated serialization * updated model base * updated configuration * updated all tests * updated samples * updated samples * updated tests * update * update snippets * updated. --- .../azure-ai-language-conversations/README.md | 2 +- .../conversations/_utils/model_base.py | 133 ++++++++++++++++-- .../conversations/_utils/serialization.py | 17 ++- .../dev_requirements.txt | 2 +- .../async/sample_authentication_async.py | 10 +- ...onversation_multi_turn_prediction_async.py | 32 +---- .../async/sample_conversation_pii_async.py | 9 -- ...on_pii_with_character_mask_policy_async.py | 21 +-- ...ation_pii_with_entity_mask_policy_async.py | 32 +---- ...versation_pii_with_no_mask_policy_async.py | 21 +-- ...ersation_prediction_with_language_async.py | 4 +- ...versation_prediction_with_options_async.py | 4 +- .../samples/sample_authentication.py | 6 +- ...mple_conversation_multi_turn_prediction.py | 28 +--- .../samples/sample_conversation_pii.py | 12 +- ...ersation_pii_with_character_mask_policy.py | 7 +- ...onversation_pii_with_entity_mask_policy.py | 32 +---- ...le_conversation_pii_with_no_mask_policy.py | 20 +-- ...e_conversation_prediction_with_language.py | 4 +- ...le_conversation_prediction_with_options.py | 4 +- .../sample_conversation_summarization.py | 2 +- ...test_conversation_multi_turn_prediction.py | 31 +--- ...onversation_multi_turn_prediction_async.py | 35 +---- .../tests/test_conversation_pii.py | 9 +- .../tests/test_conversation_pii_async.py | 16 +-- ...ersation_pii_with_character_mask_policy.py | 11 +- ...on_pii_with_character_mask_policy_async.py | 4 +- ...onversation_pii_with_entity_mask_policy.py | 13 +- ...ation_pii_with_entity_mask_policy_async.py | 6 +- ...st_conversation_pii_with_no_mask_policy.py | 10 +- ...versation_pii_with_no_mask_policy_async.py | 4 +- .../tests/test_conversation_prediction.py | 3 +- .../test_conversation_prediction_async.py | 11 +- ...t_conversation_prediction_with_language.py | 7 +- ...ersation_prediction_with_language_async.py | 12 +- ...st_conversation_prediction_with_options.py | 7 +- ...versation_prediction_with_options_async.py | 13 +- .../tests/test_conversation_summarization.py | 7 +- .../test_conversation_summarization_async.py | 3 +- .../tests/test_orchestration_prediction.py | 3 +- .../test_orchestration_prediction_async.py | 6 +- 41 files changed, 235 insertions(+), 378 deletions(-) diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/README.md b/sdk/cognitivelanguage/azure-ai-language-conversations/README.md index f26509543b01..d71c0046fb19 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/README.md +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/README.md @@ -357,7 +357,7 @@ def sample_conversation_summarization(): print(f"Display Name: {d.get('display_name')}") # Iterate results - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint: disable=too-many-nested-blocks print( f"Completed: {actions_page.completed}, " f"In Progress: {actions_page.in_progress}, " diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/model_base.py index 430bda7b37fc..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/model_base.py @@ -22,7 +22,7 @@ from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder import xml.etree.ElementTree as ET -from collections.abc import MutableMapping # pylint:disable=import-error +from collections.abc import MutableMapping from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,15 +688,29 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - return super().__new__(cls) # pylint:disable=no-value-for-parameter + return super().__new__(cls) def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/serialization.py index 45a3e44e45cb..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/azure/ai/language/conversations/_utils/serialization.py @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt index 9b07154dfb12..008b87008289 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/dev_requirements.txt @@ -1,4 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core +aiohttp ../../identity/azure-identity -aiohttp>=3.0 diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_authentication_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_authentication_async.py index 0da8e2993fb9..0960f3a7b06c 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_authentication_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_authentication_async.py @@ -39,27 +39,27 @@ async def sample_authentication_api_key_async(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] key = os.environ["AZURE_CONVERSATIONS_KEY"] - clu_client = ConversationAnalysisClient(endpoint, AzureKeyCredential(key)) + clu_client = ConversationAnalysisClient(endpoint, AzureKeyCredential(key)) #pylint:disable=unused-variable # [END create_clu_client_with_key_async] -async def sample_authentication_with_azure_active_directory(): +async def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ - print("\n.. authentication_with_azure_active_directory") + print("\n.. authentication_with_aad") from azure.ai.language.conversations.aio import ConversationAnalysisClient from azure.identity.aio import DefaultAzureCredential endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - clu_client = ConversationAnalysisClient(endpoint, credential=credential) + clu_client = ConversationAnalysisClient(endpoint, credential=credential) #pylint:disable=unused-variable async def main(): await sample_authentication_api_key_async() - await sample_authentication_with_azure_active_directory() + await sample_authentication_with_aad() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_multi_turn_prediction_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_multi_turn_prediction_async.py index 3e00228b12ce..2f702ff53aa1 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_multi_turn_prediction_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_multi_turn_prediction_async.py @@ -46,17 +46,10 @@ # Response/result discriminators ConversationalAITaskResult, ConversationalAIResult, - ConversationalAIAnalysis, - ConversationalAIIntent, - ConversationalAIEntity, - ConversationItemRange, - DateTimeResolution, - EntitySubtype, - EntityTag, ) -async def sample_conversation_multi_turn_prediction_async(): +async def sample_conv_multi_turn_prediction_async(): # get settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"] @@ -124,21 +117,6 @@ async def sample_conversation_multi_turn_prediction_async(): f" Conversation Item ID: {ent.conversation_item_id}, " f"Index: {ent.conversation_item_index}" ) - - # Date/time resolutions - for res in ent.resolutions or []: - if isinstance(res, DateTimeResolution): - print( - f" - [DateTimeResolution] SubKind: {res.date_time_sub_kind}, " - f"Timex: {res.timex}, Value: {res.value}" - ) - - # Extra information (entity subtype + tags) - for extra in ent.extra_information or []: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") print() # Global entities @@ -151,12 +129,6 @@ async def sample_conversation_multi_turn_prediction_async(): print( f" Conversation Item ID: {ent.conversation_item_id}, " f"Index: {ent.conversation_item_index}" ) - - for extra in ent.extra_information or []: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") print("-" * 40) else: print("No Conversational AI result returned.") @@ -166,7 +138,7 @@ async def sample_conversation_multi_turn_prediction_async(): async def main(): - await sample_conversation_multi_turn_prediction_async() + await sample_conv_multi_turn_prediction_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_async.py index 5c06268a4239..f1a7260f67d0 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_async.py @@ -39,10 +39,7 @@ AnalyzeConversationOperationInput, PiiOperationAction, ConversationPiiActionContent, - AnalyzeConversationOperationResult, ConversationPiiOperationResult, - InputWarning, - ConversationError, ) @@ -144,12 +141,6 @@ async def sample_conversation_pii_async(): print(f" Confidence score: {entity.confidence_score}\n") entities_detected.append(entity) - if conversation.warnings: - print("Warnings:") - for warning in conversation.warnings: - if isinstance(warning, InputWarning): - print(f" Code: {warning.code}") - print(f" Message: {warning.message}") print() else: print(" [No supported results to display for this action type]") diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_character_mask_policy_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_character_mask_policy_async.py index a0c16bb330fa..3fa3d1138f2c 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_character_mask_policy_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_character_mask_policy_async.py @@ -45,19 +45,16 @@ CharacterMaskPolicyType, RedactionCharacter, ConversationPiiOperationResult, - ConversationError, ) -async def sample_conversation_pii_with_character_mask_policy_async(): +async def sample_conv_pii_char_mask_policy_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] # AAD credential credential = DefaultAzureCredential() - redacted_verified: list[str] = [] - async with ConversationAnalysisClient(endpoint, credential=credential) as client: # build input ml_input = MultiLanguageConversationInput( @@ -124,26 +121,14 @@ async def sample_conversation_pii_with_character_mask_policy_async(): for conversation in action_result.results.conversations or []: for item in conversation.conversation_items or []: redacted_text = (item.redacted_content.text or "").strip() - if not redacted_text: - continue - - if item.entities: - for entity in item.entities: - ent_text = entity.text or "" - if ent_text in redacted_text: - print( - f"WARNING: Expected '{ent_text}' to be redacted but found in: {redacted_text}" - ) - - if "*" in redacted_text: - redacted_verified.append(redacted_text) + print(f"Redacted text: '{redacted_text}'") # [END conversation_pii_with_character_mask_policy_async] async def main(): - await sample_conversation_pii_with_character_mask_policy_async() + await sample_conv_pii_char_mask_policy_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_entity_mask_policy_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_entity_mask_policy_async.py index 0ca73229c488..23745b7393b9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_entity_mask_policy_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_entity_mask_policy_async.py @@ -30,7 +30,6 @@ # [START conversation_pii_with_entity_mask_policy_async] import os -import re import asyncio from azure.identity.aio import DefaultAzureCredential @@ -45,17 +44,14 @@ ConversationPiiActionContent, EntityMaskTypePolicyType, ConversationPiiOperationResult, - ConversationError, ) -async def sample_conversation_pii_with_entity_mask_policy_async(): +async def sample_conv_pii_entity_mask_policy_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - redacted_verified = [] - async with ConversationAnalysisClient(endpoint, credential=credential) as client: # build input ml_input = MultiLanguageConversationInput( @@ -122,36 +118,14 @@ async def sample_conversation_pii_with_entity_mask_policy_async(): for conversation in action_result.results.conversations or []: for item in conversation.conversation_items or []: redacted_text = (item.redacted_content.text or "").strip() - if not redacted_text: - continue - if item.entities and redacted_text: - all_ok = True - for entity in item.entities: - original_text = entity.text or "" - # 1) original PII must be removed - if original_text and original_text in redacted_text: - print( - f"WARNING: Expected entity '{original_text}' to be redacted " - f"but found in: {redacted_text}" - ) - all_ok = False - # 2) mask should appear like [Person] or [Person-1] - expected_mask_pattern = rf"\[{re.escape(entity.category)}-?\d*\]" - if not re.search(expected_mask_pattern, redacted_text, flags=re.IGNORECASE): - print( - f"WARNING: Expected entity mask similar to " - f"'[{entity.category}]' but got: {redacted_text}" - ) - all_ok = False - if all_ok: - redacted_verified.append(redacted_text) + print(f"Redacted text: '{redacted_text}'") # [END conversation_pii_with_entity_mask_policy_async] async def main(): - await sample_conversation_pii_with_entity_mask_policy_async() + await sample_conv_pii_entity_mask_policy_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_no_mask_policy_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_no_mask_policy_async.py index 20c20060fa0f..97ca6741e89e 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_no_mask_policy_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_pii_with_no_mask_policy_async.py @@ -42,22 +42,15 @@ PiiOperationAction, ConversationPiiActionContent, NoMaskPolicyType, - AnalyzeConversationOperationResult, ConversationPiiOperationResult, - ConversationalPiiResult, - ConversationPiiItemResult, - NamedEntity, - ConversationError, ) -async def sample_conversation_pii_with_no_mask_policy_async(): +async def sample_conv_pii_no_mask_policy_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - detected_entities = [] - async with ConversationAnalysisClient(endpoint, credential=credential) as client: # build input ml_input = MultiLanguageConversationInput( @@ -124,22 +117,14 @@ async def sample_conversation_pii_with_no_mask_policy_async(): for item in conversation.conversation_items or []: # NoMaskPolicyType returns original text (no redaction) returned_text = (item.redacted_content.text or "").strip() - if not returned_text: - continue - - if item.entities: - for entity in item.entities: - ent_text = entity.text or "" - detected_entities.append(ent_text) - if ent_text not in returned_text: - print(f"WARNING: Expected entity '{ent_text}' in returned text but not found.") + print(f"Returned text: '{returned_text}'") # [END conversation_pii_with_no_mask_policy_async] async def main(): - await sample_conversation_pii_with_no_mask_policy_async() + await sample_conv_pii_no_mask_policy_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_language_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_language_async.py index d138299b0674..9be3eaaa65b6 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_language_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_language_async.py @@ -46,7 +46,7 @@ ) -async def sample_conversation_prediction_with_language_async(): +async def sample_conv_prediction_language_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"] @@ -113,7 +113,7 @@ async def sample_conversation_prediction_with_language_async(): async def main(): - await sample_conversation_prediction_with_language_async() + await sample_conv_prediction_language_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_options_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_options_async.py index bf4a05ec1f0b..817aba324d4a 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_options_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_conversation_prediction_with_options_async.py @@ -46,7 +46,7 @@ ) -async def sample_conversation_prediction_with_options_async(): +async def sample_conv_prediction_options_async(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"] @@ -112,7 +112,7 @@ async def sample_conversation_prediction_with_options_async(): async def main(): - await sample_conversation_prediction_with_options_async() + await sample_conv_prediction_options_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_authentication.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_authentication.py index 1c494e8f03ba..ba5c134b6480 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_authentication.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_authentication.py @@ -39,11 +39,11 @@ def sample_authentication_api_key(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] key = os.environ["AZURE_CONVERSATIONS_KEY"] - clu_client = ConversationAnalysisClient(endpoint, AzureKeyCredential(key)) + clu_client = ConversationAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_clu_client_with_key] -def sample_authentication_with_azure_active_directory(): +def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -54,7 +54,7 @@ def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - clu_client = ConversationAnalysisClient(endpoint, credential=credential) + clu_client = ConversationAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable def main(): diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_multi_turn_prediction.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_multi_turn_prediction.py index d0ddfeea9404..44bce24c34b3 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_multi_turn_prediction.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_multi_turn_prediction.py @@ -42,13 +42,10 @@ TextConversationItem, StringIndexType, ConversationalAITaskResult, - DateTimeResolution, - EntitySubtype, - EntityTag, ) -def sample_conversation_multi_turn_prediction(): +def sample_conv_multi_turn_prediction(): # get settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"] @@ -117,21 +114,6 @@ def sample_conversation_multi_turn_prediction(): f" Conversation Item ID: {ent.conversation_item_id}, " f"Index: {ent.conversation_item_index}" ) - - # Date/time resolutions - for res in ent.resolutions or []: - if isinstance(res, DateTimeResolution): - print( - f" - [DateTimeResolution] SubKind: {res.date_time_sub_kind}, " - f"Timex: {res.timex}, Value: {res.value}" - ) - - # Extra information (entity subtype + tags) - for extra in ent.extra_information or []: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") print() # Global entities @@ -144,12 +126,6 @@ def sample_conversation_multi_turn_prediction(): print( f" Conversation Item ID: {ent.conversation_item_id}, " f"Index: {ent.conversation_item_index}" ) - - for extra in ent.extra_information or []: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") print("-" * 40) else: print("No Conversational AI result returned.") @@ -159,7 +135,7 @@ def sample_conversation_multi_turn_prediction(): def main(): - sample_conversation_multi_turn_prediction() + sample_conv_multi_turn_prediction() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii.py index 0a2ee2448ecd..dfab28acff99 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii.py @@ -38,10 +38,7 @@ AnalyzeConversationOperationInput, PiiOperationAction, ConversationPiiActionContent, - AnalyzeConversationOperationResult, ConversationPiiOperationResult, - InputWarning, - ConversationError, ) @@ -116,7 +113,7 @@ def sample_conversation_pii(): print(f"Display Name: {d.get('display_name')}") # iterate results (sync pageable) - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint:disable=too-many-nested-blocks print( f"Completed: {actions_page.completed}, " f"In Progress: {actions_page.in_progress}, " @@ -143,13 +140,6 @@ def sample_conversation_pii(): print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}\n") entities_detected.append(entity) - - if conversation.warnings: - print("Warnings:") - for warning in conversation.warnings: - if isinstance(warning, InputWarning): - print(f" Code: {warning.code}") - print(f" Message: {warning.message}") print() else: print(" [No supported results to display for this action type]") diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_character_mask_policy.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_character_mask_policy.py index 174bf4d8ad63..63ceebe778ef 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_character_mask_policy.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_character_mask_policy.py @@ -43,11 +43,10 @@ CharacterMaskPolicyType, RedactionCharacter, ConversationPiiOperationResult, - ConversationError, ) -def sample_conversation_pii_with_character_mask_policy(): +def sample_conv_pii_char_mask_policy(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] @@ -117,7 +116,7 @@ def sample_conversation_pii_with_character_mask_policy(): print(f" Code: {err.code} - {err.message}") # iterate results and verify redaction - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint:disable=too-many-nested-blocks for action_result in actions_page.task_results or []: if isinstance(action_result, ConversationPiiOperationResult): for conversation in action_result.results.conversations or []: @@ -142,7 +141,7 @@ def sample_conversation_pii_with_character_mask_policy(): def main(): - sample_conversation_pii_with_character_mask_policy() + sample_conv_pii_char_mask_policy() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_entity_mask_policy.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_entity_mask_policy.py index 683b4bfe4323..80ad9c08c493 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_entity_mask_policy.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_entity_mask_policy.py @@ -30,7 +30,6 @@ # [START conversation_pii_with_entity_mask_policy] import os -import re from azure.identity import DefaultAzureCredential from azure.ai.language.conversations import ConversationAnalysisClient @@ -44,17 +43,14 @@ ConversationPiiActionContent, EntityMaskTypePolicyType, ConversationPiiOperationResult, - ConversationError, ) -def sample_conversation_pii_with_entity_mask_policy(): +def sample_conv_pii_entity_mask_policy(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - redacted_verified = [] - client = ConversationAnalysisClient(endpoint, credential=credential) # build input @@ -122,36 +118,14 @@ def sample_conversation_pii_with_entity_mask_policy(): for conversation in action_result.results.conversations or []: for item in conversation.conversation_items or []: redacted_text = (item.redacted_content.text or "").strip() - if not redacted_text: - continue - if item.entities and redacted_text: - all_ok = True - for entity in item.entities: - original_text = entity.text or "" - # 1) original PII must be removed - if original_text and original_text in redacted_text: - print( - f"WARNING: Expected entity '{original_text}' to be redacted " - f"but found in: {redacted_text}" - ) - all_ok = False - # 2) mask should appear like [Person] or [Person-1] - expected_mask_pattern = rf"\[{re.escape(entity.category)}-?\d*\]" - if not re.search(expected_mask_pattern, redacted_text, flags=re.IGNORECASE): - print( - f"WARNING: Expected entity mask similar to " - f"'[{entity.category}]' but got: {redacted_text}" - ) - all_ok = False - if all_ok: - redacted_verified.append(redacted_text) + print(f"Redacted text: '{redacted_text}'") # [END conversation_pii_with_entity_mask_policy] def main(): - sample_conversation_pii_with_entity_mask_policy() + sample_conv_pii_entity_mask_policy() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_no_mask_policy.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_no_mask_policy.py index 9f8a94c6bad2..6844463474a0 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_no_mask_policy.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_pii_with_no_mask_policy.py @@ -42,19 +42,14 @@ ConversationPiiActionContent, NoMaskPolicyType, ConversationPiiOperationResult, - ConversationalPiiResult, - NamedEntity, - ConversationError, ) -def sample_conversation_pii_with_no_mask_policy(): +def sample_conv_pii_no_mask_policy(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] credential = DefaultAzureCredential() - detected_entities = [] - client = ConversationAnalysisClient(endpoint, credential=credential) # build input @@ -122,22 +117,13 @@ def sample_conversation_pii_with_no_mask_policy(): for item in conversation.conversation_items or []: # NoMaskPolicyType returns original text (no redaction) returned_text = (item.redacted_content.text or "").strip() - if not returned_text: - continue - - if item.entities: - for entity in item.entities: - ent_text = entity.text or "" - detected_entities.append(ent_text) - if ent_text not in returned_text: - print(f"WARNING: Expected entity '{ent_text}' in returned text but not found.") - + print(f"Returned text: '{returned_text}'") # [END conversation_pii_with_no_mask_policy] def main(): - sample_conversation_pii_with_no_mask_policy() + sample_conv_pii_no_mask_policy() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_language.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_language.py index b43e27874c44..123e0720bd60 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_language.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_language.py @@ -45,7 +45,7 @@ ) -def sample_conversation_prediction_with_language(): +def sample_conv_prediction_language(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"] @@ -112,7 +112,7 @@ def sample_conversation_prediction_with_language(): def main(): - sample_conversation_prediction_with_language() + sample_conv_prediction_language() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_options.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_options.py index ddb054b6f92f..345492749049 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_options.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_prediction_with_options.py @@ -45,7 +45,7 @@ ) -def sample_conversation_prediction_with_options(): +def sample_conv_prediction_options(): # settings endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"] project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"] @@ -111,7 +111,7 @@ def sample_conversation_prediction_with_options(): def main(): - sample_conversation_prediction_with_options() + sample_conv_prediction_options() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_summarization.py b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_summarization.py index 09edb2215257..c34099cb1c7b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_summarization.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_conversation_summarization.py @@ -112,7 +112,7 @@ def sample_conversation_summarization(): print(f"Display Name: {d.get('display_name')}") # Iterate results - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint: disable=too-many-nested-blocks print( f"Completed: {actions_page.completed}, " f"In Progress: {actions_page.in_progress}, " diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction.py index 73a0ef6d991e..76e51ad7b4b9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction.py @@ -1,6 +1,6 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest +from typing import cast from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient @@ -18,11 +18,7 @@ ConversationalAIIntent, ConversationalAIEntity, ConversationItemRange, - DateTimeResolution, - EntitySubtype, - EntityTag, ) -from typing import cast from azure.core.credentials import AzureKeyCredential @@ -116,24 +112,6 @@ def test_conversation_multi_turn_prediction(self, conversations_endpoint, conver print(f" Offset: {ent.offset}, Length: {ent.length}") print(f" Conversation Item ID: {ent.conversation_item_id}, Index: {ent.conversation_item_index}") - # Date/time resolutions - if ent.resolutions: - for res in ent.resolutions: - if isinstance(res, DateTimeResolution): - print( - f" - [DateTimeResolution] SubKind: {getattr(res, 'date_time_sub_kind', None)}, " - f"Timex: {res.timex}, Value: {res.value}" - ) - - # Extra information (entity subtype + tags) - if ent.extra_information: - for extra in ent.extra_information: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - tag = cast(EntityTag, tag) - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") - print() print() @@ -148,13 +126,6 @@ def test_conversation_multi_turn_prediction(self, conversations_endpoint, conver print(f" Offset: {ent.offset}, Length: {ent.length}") print(f" Conversation Item ID: {ent.conversation_item_id}, Index: {ent.conversation_item_index}") - if ent.extra_information: - for extra in ent.extra_information: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - tag = cast(EntityTag, tag) - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") print() print("-" * 40) diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction_async.py index 1b0988f34dbd..8253f61578df 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_multi_turn_prediction_async.py @@ -1,8 +1,10 @@ # pylint: disable=line-too-long,useless-suppression import functools +from typing import cast import pytest -from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy +from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader +from devtools_testutils.aio import recorded_by_proxy_async from azure.ai.language.conversations.aio import ConversationAnalysisClient from azure.ai.language.conversations.models import ( ConversationalAITask, @@ -18,13 +20,7 @@ ConversationalAIIntent, ConversationalAIEntity, ConversationItemRange, - DateTimeResolution, - EntitySubtype, - EntityTag, ) -from typing import cast -from devtools_testutils.aio import recorded_by_proxy_async -from azure.core.async_paging import AsyncItemPaged from azure.core.credentials import AzureKeyCredential @@ -123,24 +119,6 @@ async def test_conversation_multi_turn_prediction_async(self, conversations_endp f"Index: {ent.conversation_item_index}" ) - # Date/time resolutions - if ent.resolutions: - for res in ent.resolutions: - if isinstance(res, DateTimeResolution): - print( - f" - [DateTimeResolution] SubKind: {getattr(res, 'date_time_sub_kind', None)}, " - f"Timex: {res.timex}, Value: {res.value}" - ) - - # Extra information (entity subtype + tags) - if ent.extra_information: - for extra in ent.extra_information: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - tag = cast(EntityTag, tag) - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") - print() # Global entities @@ -155,13 +133,6 @@ async def test_conversation_multi_turn_prediction_async(self, conversations_endp f" Conversation Item ID: {ent.conversation_item_id}, " f"Index: {ent.conversation_item_index}" ) - if ent.extra_information: - for extra in ent.extra_information: - if isinstance(extra, EntitySubtype): - print(f" - [EntitySubtype] Value: {extra.value}") - for tag in extra.tags or []: - tag = cast(EntityTag, tag) - print(f" • Tag: {tag.name}, Confidence: {tag.confidence_score}") print("-" * 40) finally: await client.close() diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii.py index cc0e75c3f644..d0b2a644a881 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii.py @@ -1,5 +1,5 @@ import functools -import pytest +from typing import cast, List from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient, AnalyzeConversationLROPoller @@ -18,11 +18,10 @@ ConversationalPiiResult, ConversationPiiItemResult, NamedEntity, - InputWarning, ConversationError, AnalyzeConversationOperationAction, + InputWarning, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential @@ -48,7 +47,7 @@ def create_client(self, endpoint, key): class TestConversationsCase(TestConversations): @ConversationsPreparer() @recorded_by_proxy - def test_conversation_pii(self, conversations_endpoint, conversations_key): + def test_conversation_pii(self, conversations_endpoint, conversations_key): # pylint: disable=too-many-statements client = self.create_client(conversations_endpoint, conversations_key) entities_detected: List[NamedEntity] = [] @@ -106,7 +105,7 @@ def test_conversation_pii(self, conversations_endpoint, conversations_key): print(f"Display Name: {d.get('display_name')}") # ---- Iterate pages and action results -------------------------------- - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint: disable=too-many-nested-blocks print( f"Completed: {actions_page.completed}, " f"In Progress: {actions_page.in_progress}, " diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_async.py index 7fb8c7036fb0..2fc58aa4778f 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_async.py @@ -1,5 +1,6 @@ # pylint: disable=line-too-long,useless-suppression import functools +from typing import cast, List import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader @@ -8,6 +9,7 @@ from azure.ai.language.conversations.aio import ConversationAnalysisClient, AnalyzeConversationAsyncLROPoller from azure.ai.language.conversations.models import ( AnalyzeConversationOperationInput, + ConversationPiiOperationResult, MultiLanguageConversationInput, TextConversation, TextConversationItem, @@ -15,15 +17,13 @@ PiiOperationAction, ConversationPiiActionContent, ConversationActions, + NamedEntity, + ConversationError, AnalyzeConversationOperationResult, - ConversationPiiOperationResult, ConversationalPiiResult, ConversationPiiItemResult, - NamedEntity, InputWarning, - ConversationError, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( @@ -49,7 +49,7 @@ class TestConversationsCase(TestConversations): @ConversationsPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_conversation_pii_async(self, conversations_endpoint, conversations_key): + async def test_conversation_pii_async(self, conversations_endpoint, conversations_key): # pylint: disable=too-many-statements client = await self.create_client(conversations_endpoint, conversations_key) try: @@ -116,8 +116,7 @@ async def test_conversation_pii_async(self, conversations_endpoint, conversation f"Failed: {actions_page.failed}, " f"Total: {actions_page.total}" ) - - for action_result in actions_page.task_results or []: + for action_result in actions_page.task_results or []: # pylint: disable=too-many-nested-blocks ar = cast(AnalyzeConversationOperationResult, action_result) print(f"\nAction Name: {getattr(ar, 'name', None)}") print(f"Action Status: {getattr(ar, 'status', None)}") @@ -151,13 +150,14 @@ async def test_conversation_pii_async(self, conversations_endpoint, conversation print(" [No supported results to display for this action type]") # ---- Print errors (from final-state metadata) --------------------- + # Print errors if d.get("errors"): print("\nErrors:") for err in d["errors"]: err = cast(ConversationError, err) print(f" Code: {err.code} - {err.message}") - # ---- Assertions --------------------------------------------------- + # Assertions assert len(entities_detected) > 0, "Expected at least one PII entity." assert (d.get("status") or "").lower() in {"succeeded", "partiallysucceeded"} finally: diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy.py index 583524816119..ff77de632776 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy.py @@ -1,5 +1,5 @@ import functools -import pytest +from typing import cast, List from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient, AnalyzeConversationLROPoller @@ -8,6 +8,7 @@ # request models AnalyzeConversationOperationInput, MultiLanguageConversationInput, + NamedEntity, TextConversation, TextConversationItem, PiiOperationAction, @@ -17,14 +18,10 @@ ConversationPiiOperationResult, ConversationalPiiResult, ConversationPiiItemResult, - NamedEntity, - InputWarning, - ConversationError, AnalyzeConversationOperationAction, CharacterMaskPolicyType, RedactionCharacter, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential @@ -104,7 +101,7 @@ def test_conversation_pii_with_character_mask_policy(self, conversations_endpoin print(f"Status: {d.get('status')}") # ---- Iterate results and verify redaction ---------------------------- - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint: disable=too-many-nested-blocks for action_result in actions_page.task_results or []: ar = cast(AnalyzeConversationOperationResult, action_result) if isinstance(ar, ConversationPiiOperationResult): @@ -129,6 +126,6 @@ def test_conversation_pii_with_character_mask_policy(self, conversations_endpoin ), f"Expected redacted text to contain '*', got: {redacted_text}" redacted_verified.append(redacted_text) - # ---- Assertions ------------------------------------------------------- + # Assertions assert (d.get("status") or "").lower() in {"succeeded", "partiallysucceeded"} assert len(redacted_verified) > 0, "Expected at least one redacted line to be verified." diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy_async.py index 2f8888d3f66e..26b11f730f61 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_character_mask_policy_async.py @@ -1,5 +1,7 @@ # pylint: disable=line-too-long,useless-suppression import functools +from typing import cast, List + import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader @@ -20,12 +22,10 @@ ConversationalPiiResult, ConversationPiiItemResult, NamedEntity, - InputWarning, ConversationError, CharacterMaskPolicyType, RedactionCharacter, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy.py index 0356c86322c4..f309e8c96f1f 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy.py @@ -1,6 +1,7 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest +from typing import cast, List +import re from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient, AnalyzeConversationLROPoller @@ -9,6 +10,7 @@ # request models AnalyzeConversationOperationInput, MultiLanguageConversationInput, + NamedEntity, TextConversation, TextConversationItem, PiiOperationAction, @@ -18,16 +20,10 @@ ConversationPiiOperationResult, ConversationalPiiResult, ConversationPiiItemResult, - NamedEntity, - InputWarning, ConversationError, AnalyzeConversationOperationAction, - CharacterMaskPolicyType, - RedactionCharacter, EntityMaskTypePolicyType, ) -from typing import cast, List -import re from azure.core.credentials import AzureKeyCredential @@ -114,7 +110,7 @@ def test_conversation_pii_with_entity_mask_policy(self, conversations_endpoint, print(f" Code: {err.code} - {err.message}") # ---- Iterate results and validate redaction -------------------------- - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint: disable=too-many-nested-blocks for action_result in actions_page.task_results or []: ar = cast(AnalyzeConversationOperationResult, action_result) print(f"\nAction Name: {getattr(ar, 'name', None)}") @@ -128,7 +124,6 @@ def test_conversation_pii_with_entity_mask_policy(self, conversations_endpoint, item = cast(ConversationPiiItemResult, item) redacted_text = (getattr(item.redacted_content, "text", None) or "").strip() print(f"Redacted Text: {redacted_text}") - # Only verify when there are detected entities in the original item if item.entities and redacted_text: for entity in item.entities: diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy_async.py index 1725f1a8be96..c113a03191a7 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_entity_mask_policy_async.py @@ -1,5 +1,8 @@ # pylint: disable=line-too-long,useless-suppression import functools +import re +from typing import cast, List + import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader @@ -23,8 +26,7 @@ ConversationError, EntityMaskTypePolicyType, ) -import re -from typing import cast, List + from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy.py index 5820bb175ede..b5fb0464d0b0 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy.py @@ -1,6 +1,6 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest +from typing import cast, List from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient, AnalyzeConversationLROPoller @@ -9,6 +9,7 @@ # request models AnalyzeConversationOperationInput, MultiLanguageConversationInput, + NamedEntity, TextConversation, TextConversationItem, PiiOperationAction, @@ -18,13 +19,10 @@ ConversationPiiOperationResult, ConversationalPiiResult, ConversationPiiItemResult, - NamedEntity, ConversationError, AnalyzeConversationOperationAction, NoMaskPolicyType, ) -from typing import cast, List -import re from azure.core.credentials import AzureKeyCredential @@ -110,7 +108,7 @@ def test_conversation_pii_with_no_mask_policy(self, conversations_endpoint, conv print(f" Code: {err.code} - {err.message}") # ---- Iterate results and validate: PII present in returned text ------- - for actions_page in paged_actions: + for actions_page in paged_actions: # pylint: disable=too-many-nested-blocks for action_result in actions_page.task_results or []: ar = cast(AnalyzeConversationOperationResult, action_result) if isinstance(ar, ConversationPiiOperationResult): @@ -130,6 +128,6 @@ def test_conversation_pii_with_no_mask_policy(self, conversations_endpoint, conv ent_text in returned_text ), f"Expected entity '{ent_text}' to be present but was not found in: {returned_text}" - # ---- Assertions ------------------------------------------------------- + # ---- Assertions ------------------------ assert len(detected_entities) > 0, "Expected at least one detected PII entity." assert (d.get("status") or "").lower() in {"succeeded", "partiallysucceeded"} diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy_async.py index d0a7a1d9ea48..9ffa7d06a432 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_pii_with_no_mask_policy_async.py @@ -1,5 +1,6 @@ # pylint: disable=line-too-long,useless-suppression import functools +from typing import cast, List import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader @@ -20,12 +21,9 @@ ConversationalPiiResult, ConversationPiiItemResult, NamedEntity, - InputWarning, ConversationError, NoMaskPolicyType, ) -import re -from typing import cast, List from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction.py index 3bed1c8091d5..d0697b50ef70 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction.py @@ -1,5 +1,5 @@ import functools -import pytest +from typing import cast from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient @@ -13,7 +13,6 @@ DateTimeResolution, ConversationLanguageUnderstandingInput, ) -from typing import cast from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_async.py index ca6ce29260ca..f3aa7df720c8 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_async.py @@ -1,24 +1,21 @@ import functools -import pytest +from typing import cast -from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader from azure.ai.language.conversations.aio import ConversationAnalysisClient from azure.ai.language.conversations.models import ( ConversationLanguageUnderstandingInput, ConversationAnalysisInput, TextConversationItem, ConversationActionContent, - AnalyzeConversationActionResult, StringIndexType, ConversationActionResult, ConversationPrediction, DateTimeResolution, ) -from typing import cast -from devtools_testutils.aio import recorded_by_proxy_async -from azure.core.async_paging import AsyncItemPaged - from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language.py index fd44423ce2f8..f54d29a24397 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language.py @@ -1,24 +1,19 @@ import functools -import pytest +from typing import cast from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient from azure.ai.language.conversations.models import ( - AnalyzeConversationOperationInput, ConversationActionContent, ConversationAnalysisInput, TextConversationItem, ConversationActionResult, ConversationPrediction, - ConversationIntent, - ConversationEntity, StringIndexType, - ResolutionBase, DateTimeResolution, AnalyzeConversationActionResult, ConversationLanguageUnderstandingInput, ) -from typing import cast from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language_async.py index 1215a665b576..17517f0e413e 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_language_async.py @@ -1,26 +1,22 @@ import functools +from typing import cast + import pytest -from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy +from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader +from devtools_testutils.aio import recorded_by_proxy_async from azure.ai.language.conversations.aio import ConversationAnalysisClient from azure.ai.language.conversations.models import ( - AnalyzeConversationOperationInput, ConversationActionContent, ConversationAnalysisInput, TextConversationItem, ConversationActionResult, ConversationPrediction, - ConversationIntent, - ConversationEntity, StringIndexType, - ResolutionBase, DateTimeResolution, ConversationLanguageUnderstandingInput, AnalyzeConversationActionResult, ) -from typing import cast -from devtools_testutils.aio import recorded_by_proxy_async -from azure.core.async_paging import AsyncItemPaged from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options.py index 7a5670cb6407..3f1ef395fa52 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options.py @@ -1,23 +1,18 @@ import functools -import pytest +from typing import cast from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient from azure.ai.language.conversations.models import ( - AnalyzeConversationOperationInput, ConversationActionContent, ConversationAnalysisInput, TextConversationItem, ConversationActionResult, ConversationPrediction, - ConversationIntent, - ConversationEntity, StringIndexType, - ResolutionBase, DateTimeResolution, ConversationLanguageUnderstandingInput, ) -from typing import cast from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options_async.py index 4023696eea93..2d99f7148ee9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_prediction_with_options_async.py @@ -1,25 +1,22 @@ import functools +from typing import cast + import pytest -from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy +from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader +from devtools_testutils.aio import recorded_by_proxy_async + from azure.ai.language.conversations.aio import ConversationAnalysisClient from azure.ai.language.conversations.models import ( - AnalyzeConversationOperationInput, ConversationActionContent, ConversationAnalysisInput, TextConversationItem, ConversationActionResult, ConversationPrediction, - ConversationIntent, - ConversationEntity, StringIndexType, - ResolutionBase, DateTimeResolution, ConversationLanguageUnderstandingInput, ) -from typing import cast -from devtools_testutils.aio import recorded_by_proxy_async -from azure.core.async_paging import AsyncItemPaged from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization.py index 3a67236a4a63..bcc3647e5253 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization.py @@ -1,6 +1,6 @@ # pylint: disable=line-too-long,useless-suppression import functools -import pytest +from typing import cast, List from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient, AnalyzeConversationLROPoller @@ -18,7 +18,6 @@ SummarizationOperationResult, ConversationActions, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( @@ -129,10 +128,6 @@ def test_conversation_summarization(self, conversations_endpoint, conversations_ for summary in conversation.summaries: print(f" Aspect: {summary.aspect}") print(f" Text: {summary.text}") - if conversation.warnings: - print(" Warnings:") - for warning in conversation.warnings: - print(f" Code: {warning.code}, Message: {warning.message}") else: print(" [No supported results to display for this action type]") diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization_async.py index dcfea1c2c16e..263ae25f8687 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_conversation_summarization_async.py @@ -1,5 +1,7 @@ # pylint: disable=line-too-long,useless-suppression import functools +from typing import cast, List + import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader @@ -19,7 +21,6 @@ SummarizationOperationResult, ConversationActions, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction.py index 25c1cb5d5aa4..78455ddf7dfe 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction.py @@ -1,5 +1,5 @@ import functools -import pytest +from typing import cast from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.ai.language.conversations import ConversationAnalysisClient @@ -14,7 +14,6 @@ QuestionAnsweringTargetIntentResult, ConversationActionResult, ) -from typing import cast from azure.core.credentials import AzureKeyCredential diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction_async.py b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction_async.py index 720119563d08..02e9d155b95e 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/tests/test_orchestration_prediction_async.py @@ -1,11 +1,12 @@ # pylint: disable=line-too-long,useless-suppression import functools +from typing import cast + import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader from devtools_testutils.aio import recorded_by_proxy_async -from azure.core.async_paging import AsyncItemPaged -from azure.ai.language.conversations.aio import ConversationAnalysisClient, AnalyzeConversationAsyncLROPoller +from azure.ai.language.conversations.aio import ConversationAnalysisClient from azure.ai.language.conversations.models import ( AnalyzeConversationActionResult, ConversationActionContent, @@ -17,7 +18,6 @@ QuestionAnsweringTargetIntentResult, ConversationActionResult, ) -from typing import cast, List from azure.core.credentials import AzureKeyCredential ConversationsPreparer = functools.partial( From e582f4d172c21e5c7e45c04b7497f9c1df508c84 Mon Sep 17 00:00:00 2001 From: amber-Chen-86 Date: Tue, 3 Feb 2026 10:54:49 -0800 Subject: [PATCH 33/84] [Qna] fix pylint/pyright for next version (#44887) * updated serialization * updated model base * updated tests * updated test * updated tests * update * add recorded_test * update * update csspell * updated * updated. --- .vscode/cspell.json | 2 +- .../questionanswering/_utils/model_base.py | 129 ++++++++++++++++-- .../tests/test_query_knowledgebase.py | 19 ++- .../tests/test_query_knowledgebase_async.py | 13 +- .../tests/test_query_text.py | 15 +- .../tests/test_query_text_async.py | 9 +- .../tests/testcase.py | 2 +- 7 files changed, 147 insertions(+), 42 deletions(-) diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 405956c66227..62a0ca562da0 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -915,7 +915,7 @@ }, { "filename": "sdk/cognitivelanguage/azure-ai-language-questionanswering/**", - "words": [ "qnas", "qnamaker", "ADTO", "tfidf", "ngram" ], + "words": [ "qnas", "qnamaker", "ADTO", "tfidf", "ngram", "kwoa" ], "caseSensitive": false }, { diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/model_base.py index 12926fa98dcf..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/model_base.py @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,6 +688,10 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -647,6 +701,16 @@ def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py index 6ac76a9a16d7..62fbcad45a80 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py @@ -5,6 +5,7 @@ # ------------------------------------------------------------------------- import pytest +from testcase import QuestionAnsweringTestCase from azure.ai.language.questionanswering import QuestionAnsweringClient from azure.ai.language.questionanswering.models import ( AnswersOptions, @@ -16,11 +17,9 @@ ) from azure.core.credentials import AzureKeyCredential -from testcase import QuestionAnsweringTestCase - class TestQnAKnowledgeBase(QuestionAnsweringTestCase): - def test_query_knowledgebase(self, recorded_test, qna_creds): # standard model usage + def test_query_knowledgebase(self, recorded_test, qna_creds): # standard model usage # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) query_params = AnswersOptions( question="Ports and connectors", @@ -36,7 +35,7 @@ def test_query_knowledgebase(self, recorded_test, qna_creds): # standard model assert answer.qna_id is not None assert answer.source - def test_query_knowledgebase_with_answerspan(self, recorded_test, qna_creds): + def test_query_knowledgebase_with_answerspan(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) query_params = AnswersOptions( question="Ports and connectors", @@ -53,7 +52,7 @@ def test_query_knowledgebase_with_answerspan(self, recorded_test, qna_creds): assert answer.short_answer.text assert answer.short_answer.confidence is not None - def test_query_knowledgebase_filter(self, recorded_test, qna_creds): + def test_query_knowledgebase_filter(self, recorded_test, qna_creds): # pylint: disable=unused-argument filters = QueryFilters( metadata_filter=MetadataFilter( metadata=[ @@ -76,7 +75,7 @@ def test_query_knowledgebase_filter(self, recorded_test, qna_creds): ) assert response.answers - def test_query_knowledgebase_only_id(self, recorded_test, qna_creds): + def test_query_knowledgebase_only_id(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) with client: query_params = AnswersOptions(qna_id=19) @@ -88,11 +87,11 @@ def test_query_knowledgebase_overload_errors(self): # negative tests independen with QuestionAnsweringClient("http://fake.com", AzureKeyCredential("123")) as client: # These calls intentionally violate the method signature to ensure TypeError is raised. with pytest.raises(TypeError): - client.get_answers("positional_one", "positional_two") # type: ignore + client.get_answers("positional_one", "positional_two") # type: ignore # pylint: disable=too-many-function-args, missing-kwoa with pytest.raises(TypeError): - client.get_answers("positional_options_bag", options="options bag by name") # type: ignore + client.get_answers("positional_options_bag", options="options bag by name") # type: ignore # pylint: disable=missing-kwoa with pytest.raises(TypeError): - client.get_answers(options={"qnaId": 15}, project_name="hello", deployment_name="test") # type: ignore + client.get_answers(options={"qnaId": 15}, project_name="hello", deployment_name="test") # type: ignore # pylint: disable=no-value-for-parameter with pytest.raises(TypeError): client.get_answers({"qnaId": 15}, question="Why?", project_name="hello", deployment_name="test") # type: ignore @@ -102,4 +101,4 @@ def test_query_knowledgebase_question_or_qna_id(self): with pytest.raises(TypeError): client.get_answers(options, project_name="hello", deployment_name="test") with pytest.raises(TypeError): - client.get_answers(project_name="hello", deployment_name="test") + client.get_answers(project_name="hello", deployment_name="test") # pylint: disable=no-value-for-parameter diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py index 72b11cddd0e8..b8e38dd7134f 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py @@ -5,6 +5,7 @@ # ------------------------------------------------------------------------- import pytest +from testcase import QuestionAnsweringTestCase from azure.ai.language.questionanswering.aio import QuestionAnsweringClient from azure.ai.language.questionanswering.models import ( AnswersOptions, @@ -16,12 +17,10 @@ ) from azure.core.credentials import AzureKeyCredential -from testcase import QuestionAnsweringTestCase - class TestQueryKnowledgeBaseAsync(QuestionAnsweringTestCase): @pytest.mark.asyncio - async def test_query_knowledgebase_basic(self, recorded_test, qna_creds): + async def test_query_knowledgebase_basic(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) params = AnswersOptions( question="Ports and connectors", @@ -39,7 +38,7 @@ async def test_query_knowledgebase_basic(self, recorded_test, qna_creds): assert answer.metadata is not None @pytest.mark.asyncio - async def test_query_knowledgebase_with_short_answer(self, recorded_test, qna_creds): + async def test_query_knowledgebase_with_short_answer(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) params = AnswersOptions( question="Ports and connectors", @@ -56,7 +55,7 @@ async def test_query_knowledgebase_with_short_answer(self, recorded_test, qna_cr assert answer.short_answer.confidence is not None @pytest.mark.asyncio - async def test_query_knowledgebase_filter(self, recorded_test, qna_creds): + async def test_query_knowledgebase_filter(self, recorded_test, qna_creds): # pylint: disable=unused-argument filters = QueryFilters( metadata_filter=MetadataFilter( metadata=[ @@ -80,14 +79,14 @@ async def test_query_knowledgebase_filter(self, recorded_test, qna_creds): deployment_name="production", ) assert response.answers - assert any( + assert any( # pylint: disable=use-a-generator [ a for a in response.answers if (a.metadata or {}).get("explicitlytaggedheading") == "check the battery level" ] ) - assert any( + assert any( # pylint: disable=use-a-generator [ a for a in response.answers diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py index 8a9a55f98e8c..872f90610de2 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py @@ -4,16 +4,15 @@ # Runtime tests: text records querying (authoring removed) # ------------------------------------------------------------------------- import pytest +from testcase import QuestionAnsweringTestCase from azure.ai.language.questionanswering import QuestionAnsweringClient from azure.ai.language.questionanswering.models import AnswersFromTextOptions, TextDocument from azure.core.credentials import AzureKeyCredential -from testcase import QuestionAnsweringTestCase - class TestQueryText(QuestionAnsweringTestCase): - def test_query_text_basic(self, recorded_test, qna_creds): + def test_query_text_basic(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) params = AnswersFromTextOptions( question="What is the meaning of life?", @@ -33,7 +32,7 @@ def test_query_text_basic(self, recorded_test, qna_creds): if answer.short_answer: assert answer.short_answer.text - def test_query_text_with_str_records(self, recorded_test, qna_creds): + def test_query_text_with_str_records(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) params = { "question": "How long it takes to charge surface?", @@ -57,7 +56,7 @@ def test_query_text_with_str_records(self, recorded_test, qna_creds): def test_query_text_overload_errors(self): # negative client-side parameter validation with QuestionAnsweringClient("http://fake.com", AzureKeyCredential("123")) as client: with pytest.raises(TypeError): - client.get_answers_from_text("positional_one", "positional_two") # type: ignore[arg-type] + client.get_answers_from_text("positional_one", "positional_two") # type: ignore[arg-type] # pylint: disable=too-many-function-args with pytest.raises(TypeError): client.get_answers_from_text("positional_options_bag", options="options bag by name") # type: ignore[arg-type] params = AnswersFromTextOptions( @@ -65,13 +64,13 @@ def test_query_text_overload_errors(self): # negative client-side parameter val text_documents=[TextDocument(text="foo", id="doc1"), TextDocument(text="bar", id="doc2")], ) with pytest.raises(TypeError): - client.get_answers_from_text(options=params) # type: ignore[arg-type] + client.get_answers_from_text(options=params) # type: ignore[arg-type] # pylint: disable=no-value-for-parameter with pytest.raises(TypeError): - client.get_answers_from_text(question="why?", text_documents=["foo", "bar"], options=params) # type: ignore[arg-type] + client.get_answers_from_text(question="why?", text_documents=["foo", "bar"], options=params) # type: ignore[arg-type] # pylint: disable=no-value-for-parameter with pytest.raises(TypeError): client.get_answers_from_text(params, question="Why?") # type: ignore[arg-type] - def test_query_text_default_lang_override(self, recorded_test, qna_creds): + def test_query_text_default_lang_override(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient( qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"]), default_language="es" ) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py index 7eec7b126fe8..bc297504f87d 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py @@ -4,17 +4,16 @@ # Inference async tests: text records querying (authoring removed) # ------------------------------------------------------------------------- import pytest +from testcase import QuestionAnsweringTestCase from azure.ai.language.questionanswering.aio import QuestionAnsweringClient from azure.ai.language.questionanswering.models import AnswersFromTextOptions, TextDocument from azure.core.credentials import AzureKeyCredential -from testcase import QuestionAnsweringTestCase - class TestQueryTextAsync(QuestionAnsweringTestCase): @pytest.mark.asyncio - async def test_query_text_basic(self, recorded_test, qna_creds): + async def test_query_text_basic(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) params = AnswersFromTextOptions( question="What is the meaning of life?", @@ -33,7 +32,7 @@ async def test_query_text_basic(self, recorded_test, qna_creds): assert answer.id is not None @pytest.mark.asyncio - async def test_query_text_with_str_records(self, recorded_test, qna_creds): + async def test_query_text_with_str_records(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient(qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"])) params = { "question": "How long it takes to charge surface?", @@ -73,7 +72,7 @@ async def test_query_text_overload_errors(self): # negative parameter validatio await client.get_answers_from_text(params, question="Why?") # type: ignore[arg-type] @pytest.mark.asyncio - async def test_query_text_default_lang_override(self, recorded_test, qna_creds): + async def test_query_text_default_lang_override(self, recorded_test, qna_creds): # pylint: disable=unused-argument client = QuestionAnsweringClient( qna_creds["qna_endpoint"], AzureKeyCredential(qna_creds["qna_key"]), default_language="es" ) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py index 965f9e721089..dd87faa210c9 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py @@ -8,6 +8,6 @@ class QuestionAnsweringTestCase(AzureRecordedTestCase): @property def kwargs_for_polling(self): - if self.is_playback: + if self.is_playback: # pylint: disable=using-constant-test return {"polling_interval": 0} return {} From f330aa089222deeb3b948660610b5ceee29ae91d Mon Sep 17 00:00:00 2001 From: Neehar Duvvuri <40341266+needuv@users.noreply.github.com> Date: Tue, 3 Feb 2026 15:38:35 -0500 Subject: [PATCH 34/84] Bump azure-ai-evaluation version to 1.15.0 (#44982) * Bump azure-ai-evaluation version to 1.15.0 * Update CHANGELOG date for version 1.15.0 release Updated the release date for version 1.15.0 and added a bug fix entry. --- sdk/evaluation/azure-ai-evaluation/CHANGELOG.md | 2 +- .../azure-ai-evaluation/azure/ai/evaluation/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md b/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md index 3b63dc81ae57..59f084d9f75f 100644 --- a/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md +++ b/sdk/evaluation/azure-ai-evaluation/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.15.0 (Unreleased) +## 1.15.0 (2026-02-03) ### Bugs Fixed diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_version.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_version.py index a3349e7fc56e..2af67a8bd85a 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_version.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/_version.py @@ -3,4 +3,4 @@ # --------------------------------------------------------- # represents upcoming version -VERSION = "1.14.0" +VERSION = "1.15.0" From 28024b6237c335271edbd5ec63f9bdc32682081e Mon Sep 17 00:00:00 2001 From: aprilk-ms <55356546+aprilk-ms@users.noreply.github.com> Date: Tue, 3 Feb 2026 12:51:48 -0800 Subject: [PATCH 35/84] Update evaluation samples to use inline data and add README index (#44950) - Update sample_evaluations_graders.py to use inline data instead of file upload - Update sample_evaluations_ai_assisted.py to use inline data instead of file upload - Update sample_evaluation_cluster_insight.py to use inline data instead of file upload - Add samples/evaluations/README.md as an index for all evaluation samples - Update test_samples_evaluations.py to test the updated samples - Remove unnecessary inline-data sample duplicates - Update assets.json with new recordings --- sdk/ai/azure-ai-projects/assets.json | 2 +- .../samples/evaluations/README.md | 105 ++++++++++++++++++ .../sample_evaluation_cluster_insight.py | 58 ++++------ .../sample_evaluations_ai_assisted.py | 77 +++++++------ .../evaluations/sample_evaluations_graders.py | 83 ++++++++------ .../tests/samples/test_samples_evaluations.py | 13 ++- 6 files changed, 228 insertions(+), 110 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/samples/evaluations/README.md diff --git a/sdk/ai/azure-ai-projects/assets.json b/sdk/ai/azure-ai-projects/assets.json index cf8a8fe386d2..24777c3b7249 100644 --- a/sdk/ai/azure-ai-projects/assets.json +++ b/sdk/ai/azure-ai-projects/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/ai/azure-ai-projects", - "Tag": "python/ai/azure-ai-projects_7cddb7d06f" + "Tag": "python/ai/azure-ai-projects_212aab4d9b" } diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/README.md b/sdk/ai/azure-ai-projects/samples/evaluations/README.md new file mode 100644 index 000000000000..a5294316b515 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/evaluations/README.md @@ -0,0 +1,105 @@ +# Azure AI Projects - Evaluation Samples + +This folder contains samples demonstrating how to use Azure AI Foundry's evaluation capabilities with the `azure-ai-projects` SDK. + +## Prerequisites + +Before running any sample: + +```bash +pip install "azure-ai-projects>=2.0.0b1" python-dotenv +``` + +Set these environment variables: +- `AZURE_AI_PROJECT_ENDPOINT` - Your Azure AI Project endpoint (e.g., `https://.services.ai.azure.com/api/projects/`) +- `AZURE_AI_MODEL_DEPLOYMENT_NAME` - The model deployment name (e.g., `gpt-4o-mini`) + +## Sample Index + +### Getting Started + +| Sample | Description | +|--------|-------------| +| [sample_evaluations_builtin_with_inline_data.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_inline_data.py) | Basic evaluation with built-in evaluators using inline data | +| [sample_eval_catalog.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog.py) | Browse and use evaluators from the evaluation catalog | + +### Agent Evaluation + +| Sample | Description | +|--------|-------------| +| [sample_agent_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_evaluation.py) | Evaluate an agent's responses | +| [sample_agent_response_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_response_evaluation.py) | Evaluate agent response quality | +| [sample_agent_response_evaluation_with_function_tool.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_response_evaluation_with_function_tool.py) | Evaluate agent with function tools | +| [sample_model_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_model_evaluation.py) | Evaluate model responses directly | + +### Evaluator Types + +| Sample | Description | +|--------|-------------| +| [sample_evaluations_graders.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py) | OpenAI graders: label_model, text_similarity, string_check, score_model | +| [sample_evaluations_ai_assisted.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py) | AI-assisted evaluators: Similarity, ROUGE, METEOR, GLEU, F1, BLEU | +| [sample_eval_catalog_code_based_evaluators.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog_code_based_evaluators.py) | Code-based evaluators from the catalog | +| [sample_eval_catalog_prompt_based_evaluators.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog_prompt_based_evaluators.py) | Prompt-based evaluators from the catalog | + +### Insights & Analysis + +| Sample | Description | +|--------|-------------| +| [sample_evaluation_compare_insight.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_compare_insight.py) | Compare evaluation runs and generate insights | +| [sample_evaluation_cluster_insight.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py) | Generate cluster insights from evaluation runs | + +### Red Team Evaluations + +| Sample | Description | +|--------|-------------| +| [sample_redteam_evaluations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py) | Security and safety evaluations using red team techniques | + +### Agentic Evaluators + +Located in the [agentic_evaluators](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators) subfolder: + +| Sample | Description | +|--------|-------------| +| [sample_coherence.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_coherence.py) | Evaluate response coherence | +| [sample_fluency.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_fluency.py) | Evaluate response fluency | +| [sample_groundedness.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_groundedness.py) | Evaluate response groundedness | +| [sample_relevance.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_relevance.py) | Evaluate response relevance | +| [sample_intent_resolution.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_intent_resolution.py) | Evaluate intent resolution | +| [sample_response_completeness.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_response_completeness.py) | Evaluate response completeness | +| [sample_task_adherence.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_task_adherence.py) | Evaluate task adherence | +| [sample_task_completion.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_task_completion.py) | Evaluate task completion | +| [sample_task_navigation_efficiency.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_task_navigation_efficiency.py) | Evaluate navigation efficiency | +| [sample_tool_call_accuracy.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_tool_call_accuracy.py) | Evaluate tool call accuracy | +| [sample_tool_call_success.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_tool_call_success.py) | Evaluate tool call success | +| [sample_tool_input_accuracy.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_tool_input_accuracy.py) | Evaluate tool input accuracy | +| [sample_tool_output_utilization.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_tool_output_utilization.py) | Evaluate tool output utilization | +| [sample_tool_selection.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_tool_selection.py) | Evaluate tool selection | +| [sample_generic_agentic_evaluator](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_generic_agentic_evaluator) | Generic agentic evaluator example | + +### Advanced Samples + +These samples require additional setup or Azure services: + +| Sample | Description | Requirements | +|--------|-------------|--------------| +| [sample_evaluations_builtin_with_dataset_id.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_dataset_id.py) | Use uploaded dataset for evaluation | Azure Blob Storage | +| [sample_evaluations_builtin_with_traces.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_traces.py) | Evaluate against Application Insights traces | Azure Application Insights | +| [sample_scheduled_evaluations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py) | Schedule recurring evaluations | RBAC setup | +| [sample_continuous_evaluation_rule.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_continuous_evaluation_rule.py) | Set up continuous evaluation rules | Manual RBAC in Azure Portal | +| [sample_evaluations_score_model_grader_with_image.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_score_model_grader_with_image.py) | Evaluate with image data | Image file | +| [sample_evaluations_builtin_with_inline_data_oai.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_inline_data_oai.py) | Use OpenAI client directly | OpenAI SDK | + +## Running a Sample + +```bash +# Set environment variables +export AZURE_AI_PROJECT_ENDPOINT="https://your-account.services.ai.azure.com/api/projects/your-project" +export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" + +# Run a sample +python sample_evaluations_builtin_with_inline_data.py +``` + +## Learn More + +- [Azure AI Foundry Documentation](https://learn.microsoft.com/azure/ai-studio/) diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py b/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py index 98c18dd97d84..d0ff775ca3bf 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py +++ b/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py @@ -29,8 +29,6 @@ import os import time -import json -import tempfile from typing import Union from pprint import pprint from dotenv import load_dotenv @@ -39,7 +37,11 @@ from azure.identity import DefaultAzureCredential from azure.ai.projects import AIProjectClient from openai.types.eval_create_params import DataSourceConfigCustom, TestingCriterionLabelModel -from openai.types.evals.create_eval_jsonl_run_data_source_param import CreateEvalJSONLRunDataSourceParam, SourceFileID +from openai.types.evals.create_eval_jsonl_run_data_source_param import ( + CreateEvalJSONLRunDataSourceParam, + SourceFileContent, + SourceFileContentContent, +) from openai.types.evals.run_create_response import RunCreateResponse from openai.types.evals.run_retrieve_response import RunRetrieveResponse @@ -85,36 +87,23 @@ ) print(f"Evaluation created (id: {eval_object.id}, name: {eval_object.name})") - # Create and upload JSONL data as a dataset - eval_data = [ - {"item": {"query": "I love programming!"}}, - {"item": {"query": "I hate bugs."}}, - {"item": {"query": "The weather is nice today."}}, - {"item": {"query": "This is the worst movie ever."}}, - {"item": {"query": "Python is an amazing language."}}, - ] - - with tempfile.NamedTemporaryFile(mode="w", suffix=".jsonl", delete=False) as f: - for item in eval_data: - f.write(json.dumps(item) + "\n") - temp_file_path = f.name - - dataset = project_client.datasets.upload_file( - name="sentiment-eval-data", - version=str(int(time.time())), - file_path=temp_file_path, - ) - os.unlink(temp_file_path) - print(f"Dataset created (id: {dataset.id}, name: {dataset.name}, version: {dataset.version})") - - if not dataset.id: - raise ValueError("Dataset ID is None") - - # Create an eval run using the uploaded dataset + # Create an eval run using inline data eval_run: Union[RunCreateResponse, RunRetrieveResponse] = openai_client.evals.runs.create( eval_id=eval_object.id, - name="Eval Run", - data_source=CreateEvalJSONLRunDataSourceParam(source=SourceFileID(id=dataset.id, type="file_id"), type="jsonl"), + name="Eval Run with Inline Data", + data_source=CreateEvalJSONLRunDataSourceParam( + type="jsonl", + source=SourceFileContent( + type="file_content", + content=[ + SourceFileContentContent(item={"query": "I love programming!"}), + SourceFileContentContent(item={"query": "I hate bugs."}), + SourceFileContentContent(item={"query": "The weather is nice today."}), + SourceFileContentContent(item={"query": "This is the worst movie ever."}), + SourceFileContentContent(item={"query": "Python is an amazing language."}), + ], + ), + ), ) print(f"Evaluation run created (id: {eval_run.id})") @@ -142,7 +131,7 @@ print(f"Started insight generation (id: {clusterInsight.id})") while clusterInsight.state not in [OperationState.SUCCEEDED, OperationState.FAILED]: - print(f"Waiting for insight to be generated...") + print("Waiting for insight to be generated...") clusterInsight = project_client.insights.get(id=clusterInsight.id) print(f"Insight status: {clusterInsight.state}") time.sleep(5) @@ -150,12 +139,11 @@ if clusterInsight.state == OperationState.SUCCEEDED: print("\n✓ Cluster insights generated successfully!") pprint(clusterInsight) + else: + print("\n✗ Cluster insight generation failed.") else: print("\n✗ Evaluation run failed. Cannot generate cluster insights.") - project_client.datasets.delete(name=dataset.name, version=dataset.version) - print("Dataset deleted") - openai_client.evals.delete(eval_id=eval_object.id) print("Evaluation deleted") diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py b/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py index e14beec50fd5..4312245c1b12 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py +++ b/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py @@ -7,7 +7,8 @@ """ DESCRIPTION: Given an AIProjectClient, this sample demonstrates how to use the synchronous - `openai.evals.*` methods to create, get and list evaluation and and eval runs. + `openai.evals.*` methods to create, get and list evaluation and eval runs + with AI-assisted evaluators (Similarity, ROUGE, METEOR, GLEU, F1, BLEU). USAGE: python sample_evaluations_ai_assisted.py @@ -20,39 +21,27 @@ 1) AZURE_AI_PROJECT_ENDPOINT - Required. The Azure AI Project endpoint, as found in the overview page of your Microsoft Foundry project. It has the form: https://.services.ai.azure.com/api/projects/. 2) AZURE_AI_MODEL_DEPLOYMENT_NAME - Required. The name of the model deployment to use for evaluation. - 3) DATASET_NAME - Optional. The name of the Dataset to create and use in this sample. - 4) DATASET_VERSION - Optional. The version of the Dataset to create and use in this sample. - 5) DATA_FOLDER - Optional. The folder path where the data files for upload are located. """ import os from azure.identity import DefaultAzureCredential from azure.ai.projects import AIProjectClient -from azure.ai.projects.models import ( - DatasetVersion, -) - import time from pprint import pprint -from openai.types.evals.create_eval_jsonl_run_data_source_param import CreateEvalJSONLRunDataSourceParam, SourceFileID +from openai.types.evals.create_eval_jsonl_run_data_source_param import ( + CreateEvalJSONLRunDataSourceParam, + SourceFileContent, + SourceFileContentContent, +) from openai.types.eval_create_params import DataSourceConfigCustom from dotenv import load_dotenv -from datetime import datetime load_dotenv() endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"] - model_deployment_name = os.environ.get("AZURE_AI_MODEL_DEPLOYMENT_NAME", "") -dataset_name = os.environ.get("DATASET_NAME", "") -dataset_version = os.environ.get("DATASET_VERSION", "1") - -# Construct the paths to the data folder and data file used in this sample -script_dir = os.path.dirname(os.path.abspath(__file__)) -data_folder = os.environ.get("DATA_FOLDER", os.path.join(script_dir, "data_folder")) -data_file = os.path.join(data_folder, "sample_data_evaluation.jsonl") with ( DefaultAzureCredential() as credential, @@ -60,14 +49,6 @@ project_client.get_openai_client() as client, ): - print("Upload a single file and create a new Dataset to reference the file.") - dataset: DatasetVersion = project_client.datasets.upload_file( - name=dataset_name or f"eval-data-{datetime.utcnow().strftime('%Y-%m-%d_%H%M%S_UTC')}", - version=dataset_version, - file_path=data_file, - ) - pprint(dataset) - data_source_config = DataSourceConfigCustom( { "type": "custom", @@ -133,9 +114,9 @@ }, ] - print("Creating evaluation") + print("Creating evaluation with AI-assisted evaluators") eval_object = client.evals.create( - name="ai assisted evaluators test", + name="AI assisted evaluators test", data_source_config=data_source_config, testing_criteria=testing_criteria, # type: ignore ) @@ -146,13 +127,42 @@ print("Evaluation Response:") pprint(eval_object_response) - print("Creating evaluation run") + print("Creating evaluation run with inline data") eval_run_object = client.evals.runs.create( eval_id=eval_object.id, - name="dataset", - metadata={"team": "eval-exp", "scenario": "notifications-v1"}, + name="inline_data_ai_assisted_run", + metadata={"team": "eval-exp", "scenario": "ai-assisted-inline-v1"}, data_source=CreateEvalJSONLRunDataSourceParam( - source=SourceFileID(id=dataset.id or "", type="file_id"), type="jsonl" + type="jsonl", + source=SourceFileContent( + type="file_content", + content=[ + SourceFileContentContent( + item={ + "response": "The capital of France is Paris, which is also known as the City of Light.", + "ground_truth": "Paris is the capital of France.", + } + ), + SourceFileContentContent( + item={ + "response": "Python is a high-level programming language known for its simplicity and readability.", + "ground_truth": "Python is a popular programming language that is easy to learn.", + } + ), + SourceFileContentContent( + item={ + "response": "Machine learning is a subset of artificial intelligence that enables systems to learn from data.", + "ground_truth": "Machine learning allows computers to learn from data without being explicitly programmed.", + } + ), + SourceFileContentContent( + item={ + "response": "The sun rises in the east and sets in the west due to Earth's rotation.", + "ground_truth": "The sun appears to rise in the east and set in the west because of Earth's rotation.", + } + ), + ], + ), ), ) print(f"Eval Run created") @@ -174,8 +184,5 @@ time.sleep(5) print("Waiting for evaluation run to complete...") - project_client.datasets.delete(name=dataset.name, version=dataset.version) - print("Dataset deleted") - client.evals.delete(eval_id=eval_object.id) print("Evaluation deleted") diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py b/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py index 806d734330fc..d8c89f72666c 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py +++ b/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py @@ -7,7 +7,8 @@ """ DESCRIPTION: Given an AIProjectClient, this sample demonstrates how to use the synchronous - `openai.evals.*` methods to create, get and list evaluation and and eval runs. + `openai.evals.*` methods to create, get and list evaluation and eval runs + using various grader types (label_model, text_similarity, string_check, score_model). USAGE: python sample_evaluations_graders.py @@ -20,38 +21,27 @@ 1) AZURE_AI_PROJECT_ENDPOINT - Required. The Azure AI Project endpoint, as found in the overview page of your Microsoft Foundry project. It has the form: https://.services.ai.azure.com/api/projects/. 2) AZURE_AI_MODEL_DEPLOYMENT_NAME - Required. The name of the model deployment to use for evaluation. - 3) DATASET_NAME - Optional. The name of the Dataset to create and use in this sample. - 4) DATASET_VERSION - Optional. The version of the Dataset to create and use in this sample. - 5) DATA_FOLDER - Optional. The folder path where the data files for upload are located. """ import os from azure.identity import DefaultAzureCredential from azure.ai.projects import AIProjectClient -from azure.ai.projects.models import ( - DatasetVersion, -) import time from pprint import pprint -from openai.types.evals.create_eval_jsonl_run_data_source_param import CreateEvalJSONLRunDataSourceParam, SourceFileID +from openai.types.evals.create_eval_jsonl_run_data_source_param import ( + CreateEvalJSONLRunDataSourceParam, + SourceFileContent, + SourceFileContentContent, +) from openai.types.eval_create_params import DataSourceConfigCustom from dotenv import load_dotenv -from datetime import datetime load_dotenv() endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"] - model_deployment_name = os.environ.get("AZURE_AI_MODEL_DEPLOYMENT_NAME", "") -dataset_name = os.environ.get("DATASET_NAME", "") -dataset_version = os.environ.get("DATASET_VERSION", "1") - -# Construct the paths to the data folder and data file used in this sample -script_dir = os.path.dirname(os.path.abspath(__file__)) -data_folder = os.environ.get("DATA_FOLDER", os.path.join(script_dir, "data_folder")) -data_file = os.path.join(data_folder, "sample_data_evaluation.jsonl") with ( DefaultAzureCredential() as credential, @@ -59,14 +49,6 @@ project_client.get_openai_client() as client, ): - print("Upload a single file and create a new Dataset to reference the file.") - dataset: DatasetVersion = project_client.datasets.upload_file( - name=dataset_name or f"eval-data-{datetime.utcnow().strftime('%Y-%m-%d_%H%M%S_UTC')}", - version=dataset_version, - file_path=data_file, - ) - pprint(dataset) - data_source_config = DataSourceConfigCustom( { "type": "custom", @@ -130,7 +112,7 @@ }, ] - print("Creating evaluation") + print("Creating evaluation with graders") eval_object = client.evals.create( name="OpenAI graders test", data_source_config=data_source_config, @@ -143,13 +125,50 @@ print("Evaluation Response:") pprint(eval_object_response) - print("Creating Eval Run") + print("Creating Eval Run with inline data") eval_run_object = client.evals.runs.create( eval_id=eval_object.id, - name="dataset", - metadata={"team": "eval-exp", "scenario": "notifications-v1"}, + name="inline_data_graders_run", + metadata={"team": "eval-exp", "scenario": "graders-inline-v1"}, data_source=CreateEvalJSONLRunDataSourceParam( - source=SourceFileID(id=dataset.id or "", type="file_id"), type="jsonl" + type="jsonl", + source=SourceFileContent( + type="file_content", + content=[ + SourceFileContentContent( + item={ + "query": "I love this product! It works great.", + "context": "Product review context", + "ground_truth": "The product is excellent and performs well.", + "response": "The product is amazing and works perfectly.", + } + ), + SourceFileContentContent( + item={ + "query": "The weather is cloudy today.", + "context": "Weather observation", + "ground_truth": "Today's weather is overcast.", + "response": "The sky is covered with clouds today.", + } + ), + SourceFileContentContent( + item={ + "query": "What is the capital of France?", + "context": "Geography question about European capitals", + "ground_truth": "Paris", + "response": "The capital of France is Paris.", + } + ), + SourceFileContentContent( + item={ + "query": "Explain quantum computing", + "context": "Complex scientific concept explanation", + "ground_truth": "Quantum computing uses quantum mechanics principles", + "response": "Quantum computing leverages quantum mechanical phenomena like superposition and entanglement to process information.", + } + ), + ], + ), ), ) print(f"Eval Run created (id: {eval_run_object.id}, name: {eval_run_object.name})") @@ -166,13 +185,9 @@ output_items = list(client.evals.runs.output_items.list(run_id=run.id, eval_id=eval_object.id)) pprint(output_items) print(f"Eval Run Report URL: {run.report_url}") - break time.sleep(5) print("Waiting for eval run to complete...") - project_client.datasets.delete(name=dataset.name, version=dataset.version) - print("Dataset deleted") - client.evals.delete(eval_id=eval_object.id) print("Evaluation deleted") diff --git a/sdk/ai/azure-ai-projects/tests/samples/test_samples_evaluations.py b/sdk/ai/azure-ai-projects/tests/samples/test_samples_evaluations.py index acb3c5c2fd04..d3370ffebb19 100644 --- a/sdk/ai/azure-ai-projects/tests/samples/test_samples_evaluations.py +++ b/sdk/ai/azure-ai-projects/tests/samples/test_samples_evaluations.py @@ -45,9 +45,9 @@ class TestSamplesEvaluations(AzureRecordedTestCase): """ Tests for evaluation samples. - Included samples (25): + Included samples (28): - Main evaluation samples (10): + Main evaluation samples (13): - sample_agent_evaluation.py - sample_model_evaluation.py - sample_agent_response_evaluation.py @@ -58,6 +58,9 @@ class TestSamplesEvaluations(AzureRecordedTestCase): - sample_eval_catalog_prompt_based_evaluators.py - sample_evaluation_compare_insight.py - sample_redteam_evaluations.py + - sample_evaluations_graders.py (OpenAI graders: label_model, text_similarity, string_check, score_model) + - sample_evaluations_ai_assisted.py (AI-assisted evaluators: Similarity, ROUGE, METEOR, GLEU, F1, BLEU) + - sample_evaluation_cluster_insight.py (cluster insights generation) Agentic evaluator samples (15): - sample_coherence.py @@ -81,11 +84,8 @@ class TestSamplesEvaluations(AzureRecordedTestCase): Blob Storage / Dataset Upload (incompatible with test proxy playback): - sample_evaluations_builtin_with_dataset_id.py: Uploads data to Azure Blob Storage before creating the evaluation. - - sample_evaluations_ai_assisted.py: Creates a Dataset with file upload. - - sample_evaluations_graders.py: Creates a Dataset with file upload. - sample_evaluations_score_model_grader_with_image.py: Uses image data which may involve file upload. - - sample_evaluation_cluster_insight.py: Creates a Dataset with file upload. Authentication incompatibility (mock credentials don't work): - sample_evaluations_builtin_with_inline_data_oai.py: Uses OpenAI client directly with @@ -120,6 +120,9 @@ class TestSamplesEvaluations(AzureRecordedTestCase): "sample_evaluation_compare_insight.py", "sample_agent_response_evaluation_with_function_tool.py", "sample_redteam_evaluations.py", + "sample_evaluations_graders.py", + "sample_evaluations_ai_assisted.py", + "sample_evaluation_cluster_insight.py", ], ), ) From 2b7032f497499e2a5cae7be9464863833ba86b9b Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 3 Feb 2026 13:08:21 -0800 Subject: [PATCH 36/84] Add CODEOWNERS for sdk/agentserver/ with "Hosted Agents" service label (#44941) * Initial plan * Add @lusu-msft and @JC-386 as Service Owner CODEOWNERS for sdk/agentserver/ with service label "Hosted Agents" Co-authored-by: ronniegeraghty <28957151+ronniegeraghty@users.noreply.github.com> * Separate CODEOWNERS blocks for sdk/agentserver/ - ServiceOwners/ServiceLabel in one block, PRLabel/path in another Co-authored-by: ronniegeraghty <28957151+ronniegeraghty@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: ronniegeraghty <28957151+ronniegeraghty@users.noreply.github.com> Co-authored-by: Ronnie Geraghty --- .github/CODEOWNERS | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a44c7593cae6..2423b6b285b3 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -45,6 +45,12 @@ # PRLabel: %AgriFood /sdk/agrifood/azure-agrifood-farming/ @bhargav-kansagara +# ServiceOwners: @lusu-msft @JC-386 +# ServiceLabel: %Hosted Agents + +# PRLabel: %Hosted Agents +/sdk/agentserver/ @lusu-msft @JC-386 + # AzureSdkOwners: @xiangyan99 # ServiceLabel: %Azure.Identity # PRLabel: %Azure.Identity From b93908a9ca54486cda8549da8122263c868a3dee Mon Sep 17 00:00:00 2001 From: aprilk-ms <55356546+aprilk-ms@users.noreply.github.com> Date: Tue, 3 Feb 2026 14:13:01 -0800 Subject: [PATCH 37/84] Update evaluation samples to use inline data and add README index (#44950) (#44983) - Update sample_evaluations_graders.py to use inline data instead of file upload - Update sample_evaluations_ai_assisted.py to use inline data instead of file upload - Update sample_evaluation_cluster_insight.py to use inline data instead of file upload - Add samples/evaluations/README.md as an index for all evaluation samples - Update test_samples_evaluations.py to test the updated samples - Remove unnecessary inline-data sample duplicates - Update assets.json with new recordings --- .../samples/evaluations/README.md | 63 +++++++++---------- 1 file changed, 30 insertions(+), 33 deletions(-) diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/README.md b/sdk/ai/azure-ai-projects/samples/evaluations/README.md index a5294316b515..ef774d201eaa 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/README.md +++ b/sdk/ai/azure-ai-projects/samples/evaluations/README.md @@ -21,38 +21,44 @@ Set these environment variables: | Sample | Description | |--------|-------------| | [sample_evaluations_builtin_with_inline_data.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_inline_data.py) | Basic evaluation with built-in evaluators using inline data | +| [sample_evaluations_builtin_with_dataset_id.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_dataset_id.py) | Evaluate using an uploaded dataset | | [sample_eval_catalog.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog.py) | Browse and use evaluators from the evaluation catalog | -### Agent Evaluation +### Agent / Model Evaluation | Sample | Description | |--------|-------------| -| [sample_agent_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_evaluation.py) | Evaluate an agent's responses | -| [sample_agent_response_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_response_evaluation.py) | Evaluate agent response quality | -| [sample_agent_response_evaluation_with_function_tool.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_response_evaluation_with_function_tool.py) | Evaluate agent with function tools | -| [sample_model_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_model_evaluation.py) | Evaluate model responses directly | +| [sample_agent_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_evaluation.py) | Create a response from an agent and evaluate | +| [sample_agent_response_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_response_evaluation.py) | Evaluate given agent responses | +| [sample_agent_response_evaluation_with_function_tool.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_agent_response_evaluation_with_function_tool.py) | Evaluate agent responses with function tools | +| [sample_model_evaluation.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_model_evaluation.py) | Create response from model and evaluate | -### Evaluator Types +### Red Team Evaluations | Sample | Description | |--------|-------------| -| [sample_evaluations_graders.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py) | OpenAI graders: label_model, text_similarity, string_check, score_model | -| [sample_evaluations_ai_assisted.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py) | AI-assisted evaluators: Similarity, ROUGE, METEOR, GLEU, F1, BLEU | -| [sample_eval_catalog_code_based_evaluators.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog_code_based_evaluators.py) | Code-based evaluators from the catalog | -| [sample_eval_catalog_prompt_based_evaluators.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog_prompt_based_evaluators.py) | Prompt-based evaluators from the catalog | +| [sample_redteam_evaluations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py) | Security and safety evaluations using red team techniques | -### Insights & Analysis +### Additional Scenarios -| Sample | Description | -|--------|-------------| -| [sample_evaluation_compare_insight.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_compare_insight.py) | Compare evaluation runs and generate insights | -| [sample_evaluation_cluster_insight.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py) | Generate cluster insights from evaluation runs | +These samples require additional setup or Azure services: -### Red Team Evaluations +| Sample | Description | Requirements | +|--------|-------------|--------------| +| [sample_evaluations_builtin_with_traces.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_traces.py) | Evaluate against Application Insights traces | Connected Application Insights on Foundry Project | +| [sample_scheduled_evaluations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py) | Schedule recurring evaluations | RBAC setup | +| [sample_continuous_evaluation_rule.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_continuous_evaluation_rule.py) | Set up continuous evaluation rules | RBAC Setup | +| [sample_evaluations_score_model_grader_with_image.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_score_model_grader_with_image.py) | Evaluate with image data | Image file | +| [sample_evaluations_builtin_with_inline_data_oai.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_inline_data_oai.py) | Use OpenAI client directly | OpenAI SDK | + +### Evaluator Types | Sample | Description | |--------|-------------| -| [sample_redteam_evaluations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_redteam_evaluations.py) | Security and safety evaluations using red team techniques | +| [sample_evaluations_graders.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_graders.py) | OpenAI graders: label_model, text_similarity, string_check, score_model | +| [sample_evaluations_ai_assisted.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_ai_assisted.py) | AI-assisted and NLP-based evaluators: Similarity, ROUGE, METEOR, GLEU, F1, BLEU | +| [sample_eval_catalog_code_based_evaluators.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog_code_based_evaluators.py) | Custom code-based (python) evaluators | +| [sample_eval_catalog_prompt_based_evaluators.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_eval_catalog_prompt_based_evaluators.py) | Custom prompt-based evaluators | ### Agentic Evaluators @@ -76,30 +82,21 @@ Located in the [agentic_evaluators](https://github.com/Azure/azure-sdk-for-pytho | [sample_tool_selection.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_tool_selection.py) | Evaluate tool selection | | [sample_generic_agentic_evaluator](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/ai/azure-ai-projects/samples/evaluations/agentic_evaluators/sample_generic_agentic_evaluator) | Generic agentic evaluator example | -### Advanced Samples -These samples require additional setup or Azure services: +### Evaluation Result Insights & Analysis -| Sample | Description | Requirements | -|--------|-------------|--------------| -| [sample_evaluations_builtin_with_dataset_id.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_dataset_id.py) | Use uploaded dataset for evaluation | Azure Blob Storage | -| [sample_evaluations_builtin_with_traces.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_traces.py) | Evaluate against Application Insights traces | Azure Application Insights | -| [sample_scheduled_evaluations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py) | Schedule recurring evaluations | RBAC setup | -| [sample_continuous_evaluation_rule.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_continuous_evaluation_rule.py) | Set up continuous evaluation rules | Manual RBAC in Azure Portal | -| [sample_evaluations_score_model_grader_with_image.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_score_model_grader_with_image.py) | Evaluate with image data | Image file | -| [sample_evaluations_builtin_with_inline_data_oai.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluations_builtin_with_inline_data_oai.py) | Use OpenAI client directly | OpenAI SDK | +| Sample | Description | +|--------|-------------| +| [sample_evaluation_compare_insight.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_compare_insight.py) | Compare evaluation runs and generate statistics | +| [sample_evaluation_cluster_insight.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/evaluations/sample_evaluation_cluster_insight.py) | Analyze evaluation runs with cluster insights | ## Running a Sample ```bash # Set environment variables -export AZURE_AI_PROJECT_ENDPOINT="https://your-account.services.ai.azure.com/api/projects/your-project" -export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/" +export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Replace with your model # Run a sample python sample_evaluations_builtin_with_inline_data.py ``` - -## Learn More - -- [Azure AI Foundry Documentation](https://learn.microsoft.com/azure/ai-studio/) From 14028a4655c9055e234fb142a91da64fdd0b82f4 Mon Sep 17 00:00:00 2001 From: Jackson Weber <47067795+JacksonWeber@users.noreply.github.com> Date: Tue, 3 Feb 2026 15:27:44 -0800 Subject: [PATCH 38/84] [Monitor OpenTelemetry Exporter] Fix Ingestion Sampling Response Offline Storage (#44980) * Fix ingestion sampling 206 issue. * Update CHANGELOG.md * Make telemetry sampled message more specific and update tests. * Update CHANGELOG.md * Updated message values. --- .../CHANGELOG.md | 2 + .../opentelemetry/exporter/export/_base.py | 27 +++++- .../tests/test_base_exporter.py | 92 +++++++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index 478a2e1a41f7..bd9f2cbd852b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -9,6 +9,8 @@ ### Bugs Fixed ### Other Changes +- Fix Ingestion-Side Sampling Disk Persist Behavior + ([#44980](https://github.com/Azure/azure-sdk-for-python/pull/44980)) ## 1.0.0b47 (2026-02-03) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py index e4a8c999c033..ebff4fef4812 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py @@ -287,7 +287,16 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: reach_ingestion = True resend_envelopes = [] for error in track_response.errors: - if _is_retryable_code(error.status_code): + # Check for sampling rejection - these should not be retried + # because the server will always reject them based on sampling rules + if _is_sampling_rejection(error.message): + if not self._is_stats_exporter(): + logger.info( + "Data dropped due to ingestion sampling: %s %s.", + error.message, + envelopes[error.index] if error.index is not None else "", + ) + elif _is_retryable_code(error.status_code): resend_envelopes.append(envelopes[error.index]) # type: ignore # Track retried items in customer sdkstats if self._should_collect_customer_sdkstats(): @@ -568,6 +577,22 @@ def _reached_ingestion_code(response_code: Optional[int]) -> bool: return response_code in _REACHED_INGESTION_STATUS_CODES +def _is_sampling_rejection(message: Optional[str]) -> bool: + """Determine if error message indicates ingestion-side sampling rejection. + + When the server rejects telemetry due to ingestion sampling, the error message + will be "Telemetry sampled out." These items should not be retried or persisted + because the server will always reject them based on sampling rules. + + :param str message: Error message from the server + :return: True if the error indicates a sampling rejection + :rtype: bool + """ + if message is None: + return False + return message.lower() == "telemetry sampled out." + + _MONITOR_DOMAIN_MAPPING = { "EventData": TelemetryEventData, "ExceptionData": TelemetryExceptionData, diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py index f1ca99984f1b..097726261cfc 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py @@ -15,6 +15,7 @@ _format_storage_telemetry_item, _get_auth_policy, _get_authentication_credential, + _is_sampling_rejection, BaseExporter, ExportResult, _get_storage_directory, @@ -731,6 +732,97 @@ def test_transmission_206_no_retry(self): self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) exporter.storage.put.assert_not_called() + def test_transmission_206_sampling_rejection_not_retried(self): + """Test that items rejected due to ingestion sampling are not retried or persisted.""" + exporter = BaseExporter(disable_offline_storage=True) + exporter.storage = mock.Mock() + custom_envelopes_to_export = [ + TelemetryItem(name="Test1", time=datetime.now()), + TelemetryItem(name="Test2", time=datetime.now()), + TelemetryItem(name="Test3", time=datetime.now()), + ] + with mock.patch.object(AzureMonitorClient, "track") as post: + post.return_value = TrackResponse( + items_received=3, + items_accepted=0, + errors=[ + # This item should NOT be retried due to sampling rejection + TelemetryErrorDetails( + index=0, + status_code=500, + message="Telemetry sampled out.", + ), + # This item should NOT be retried due to sampling rejection + TelemetryErrorDetails( + index=1, + status_code=500, + message="Telemetry sampled out.", + ), + # This item should be retried (normal timeout error) + TelemetryErrorDetails( + index=2, + status_code=408, + message="Timeout error", + ), + ], + ) + result = exporter._transmit(custom_envelopes_to_export) + # Should still attempt storage for the non-sampling rejection error + self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) + # Storage should be called only for the non-sampling error (index=2) + exporter.storage.put.assert_called_once() + # Verify only one envelope was stored (the one with non-sampling error) + stored_envelopes = exporter.storage.put.call_args[0][0] + self.assertEqual(len(stored_envelopes), 1) + + def test_transmission_206_all_sampling_rejections_no_storage(self): + """Test that when all items are rejected due to sampling, nothing is persisted.""" + exporter = BaseExporter(disable_offline_storage=True) + exporter.storage = mock.Mock() + custom_envelopes_to_export = [ + TelemetryItem(name="Test1", time=datetime.now()), + TelemetryItem(name="Test2", time=datetime.now()), + ] + with mock.patch.object(AzureMonitorClient, "track") as post: + post.return_value = TrackResponse( + items_received=2, + items_accepted=0, + errors=[ + TelemetryErrorDetails( + index=0, + status_code=500, + message="Telemetry sampled out.", + ), + TelemetryErrorDetails( + index=1, + status_code=500, + message="Telemetry sampled out.", + ), + ], + ) + result = exporter._transmit(custom_envelopes_to_export) + self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) + # Storage should NOT be called since all errors are sampling rejections + exporter.storage.put.assert_not_called() + + def test_is_sampling_rejection_true(self): + """Test that _is_sampling_rejection correctly identifies sampling rejection messages.""" + self.assertTrue(_is_sampling_rejection("Telemetry sampled out.")) + self.assertTrue(_is_sampling_rejection("telemetry sampled out.")) + self.assertTrue(_is_sampling_rejection("TELEMETRY SAMPLED OUT.")) + self.assertTrue(_is_sampling_rejection("Telemetry Sampled Out.")) + + def test_is_sampling_rejection_false(self): + """Test that _is_sampling_rejection returns False for non-sampling messages.""" + self.assertFalse(_is_sampling_rejection("Internal server error")) + self.assertFalse(_is_sampling_rejection("Bad request")) + self.assertFalse(_is_sampling_rejection("Timeout error")) + self.assertFalse(_is_sampling_rejection("")) + self.assertFalse(_is_sampling_rejection(None)) + # Similar messages that don't match exactly should return False + self.assertFalse(_is_sampling_rejection("Telemetry sampled out")) # Missing period + self.assertFalse(_is_sampling_rejection("Sampled out")) + def test_transmission_400(self): with mock.patch("requests.Session.request") as post: post.return_value = MockResponse(400, "{}") From 19f27e67bf83d77b37abde8bb1758c5a99d70456 Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Tue, 3 Feb 2026 17:07:05 -0800 Subject: [PATCH 39/84] [Corehttp] Add misc updates (#44931) This pulls in applicable changes that were made in azure-core but not yet applied to corehttp. Signed-off-by: Paul Van Eck Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- sdk/core/corehttp/CHANGELOG.md | 11 + sdk/core/corehttp/corehttp/credentials.py | 19 +- .../instrumentation/tracing/opentelemetry.py | 43 +++- sdk/core/corehttp/corehttp/paging.py | 13 + sdk/core/corehttp/corehttp/rest/_aiohttp.py | 16 +- .../rest/_http_response_impl_async.py | 2 + .../corehttp/corehttp/rest/_requests_basic.py | 12 +- sdk/core/corehttp/corehttp/rest/_rest_py3.py | 4 +- .../corehttp/runtime/pipeline/__init__.py | 4 +- .../corehttp/runtime/pipeline/_tools.py | 2 +- .../runtime/policies/_authentication.py | 26 +- .../runtime/policies/_authentication_async.py | 18 +- .../runtime/policies/_distributed_tracing.py | 13 + .../corehttp/runtime/policies/_retry.py | 17 +- .../corehttp/runtime/policies/_retry_async.py | 11 +- .../corehttp/runtime/policies/_universal.py | 11 + sdk/core/corehttp/corehttp/serialization.py | 238 +++++++++++++++++- sdk/core/corehttp/corehttp/transport/_base.py | 4 +- .../corehttp/transport/_base_async.py | 4 +- .../corehttp/transport/aiohttp/_aiohttp.py | 53 ++-- .../transport/requests/_requests_basic.py | 43 ++-- sdk/core/corehttp/corehttp/utils/_utils.py | 3 +- .../tests/async_tests/test_transport_async.py | 121 +++++++++ .../corehttp/tests/test_stream_generator.py | 5 +- sdk/core/corehttp/tests/test_tracer_otel.py | 72 +++++- sdk/core/corehttp/tests/test_transport.py | 95 +++++++ 26 files changed, 769 insertions(+), 91 deletions(-) create mode 100644 sdk/core/corehttp/tests/async_tests/test_transport_async.py create mode 100644 sdk/core/corehttp/tests/test_transport.py diff --git a/sdk/core/corehttp/CHANGELOG.md b/sdk/core/corehttp/CHANGELOG.md index 74661c7c2a53..8b30d36ab798 100644 --- a/sdk/core/corehttp/CHANGELOG.md +++ b/sdk/core/corehttp/CHANGELOG.md @@ -12,11 +12,22 @@ - `DistributedHttpTracingPolicy` and `distributed_trace`/`distributed_trace_async` decorators were added to support OpenTelemetry tracing for SDK operations. - SDK clients can define an `_instrumentation_config` class variable to configure the OpenTelemetry tracer used in method span creation. Possible configuration options are `library_name`, `library_version`, `schema_url`, and `attributes`. - Added a global settings object, `corehttp.settings`, to the `corehttp` package. This object can be used to set global settings for the `corehttp` package. Currently the only setting is `tracing_enabled` for enabling/disabling tracing. [#39172](https://github.com/Azure/azure-sdk-for-python/pull/39172) +- Added `start_time` and `context` keyword arguments to `OpenTelemetryTracer.start_span` and `start_as_current_span` methods. +- Added `set_span_error_status` static method to `OpenTelemetryTracer` for setting a span's status to ERROR. +- Added `is_generated_model`, `attribute_list`, and `TypeHandlerRegistry` to `corehttp.serialization` module for SDK model handling. ### Breaking Changes ### Bugs Fixed +- Fixed `retry_backoff_max` being ignored in retry policies when configuring retries. +- Raise correct exception if transport is used while already closed. +- A timeout error when using the `aiohttp` transport will now be raised as a `corehttp.exceptions.ServiceResponseTimeoutError`, a subtype of the previously raised `ServiceResponseError`. +- When using with `aiohttp` 3.10 or later, a connection timeout error will now be raised as a `corehttp.exceptions.ServiceRequestTimeoutError`, which can be retried. +- Fixed leaked requests and aiohttp exceptions for streamed responses. +- Improved granularity of `ServiceRequestError` and `ServiceResponseError` exceptions raised in timeout scenarios from the requests and aiohttp transports. +- `BearerTokenCredentialPolicy` and `AsyncBearerTokenCredentialPolicy` will now properly chain exceptions raised during claims challenge handling. If a credential raises an exception when attempting to acquire a token in response to a claims challenge, that exception will be raised with the original 401 response as the cause. + ### Other Changes - Added `opentelemetry-api` as an optional dependency for tracing. [#39172](https://github.com/Azure/azure-sdk-for-python/pull/39172) diff --git a/sdk/core/corehttp/corehttp/credentials.py b/sdk/core/corehttp/corehttp/credentials.py index 6b31a4557ac9..b913b08e5fd5 100644 --- a/sdk/core/corehttp/corehttp/credentials.py +++ b/sdk/core/corehttp/corehttp/credentials.py @@ -68,7 +68,11 @@ def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = ... def close(self) -> None: - pass + """Close the credential, releasing any resources it holds. + + :return: None + :rtype: None + """ class ServiceNamedKey(NamedTuple): @@ -93,7 +97,7 @@ class ServiceKeyCredential: It provides the ability to update the key without creating a new client. :param str key: The key used to authenticate to a service - :raises: TypeError + :raises TypeError: If the key is not a string. """ def __init__(self, key: str) -> None: @@ -117,7 +121,8 @@ def update(self, key: str) -> None: to update long-lived clients. :param str key: The key used to authenticate to a service - :raises: ValueError or TypeError + :raises ValueError: If the key is None or empty. + :raises TypeError: If the key is not a string. """ if not key: raise ValueError("The key used for updating can not be None or empty") @@ -132,7 +137,7 @@ class ServiceNamedKeyCredential: :param str name: The name of the credential used to authenticate to a service. :param str key: The key used to authenticate to a service. - :raises: TypeError + :raises TypeError: If the name or key is not a string. """ def __init__(self, name: str, key: str) -> None: @@ -180,7 +185,11 @@ async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptio ... async def close(self) -> None: - pass + """Close the credential, releasing any resources. + + :return: None + :rtype: None + """ async def __aexit__( self, diff --git a/sdk/core/corehttp/corehttp/instrumentation/tracing/opentelemetry.py b/sdk/core/corehttp/corehttp/instrumentation/tracing/opentelemetry.py index 2876dfdd0589..01c82fba217e 100644 --- a/sdk/core/corehttp/corehttp/instrumentation/tracing/opentelemetry.py +++ b/sdk/core/corehttp/corehttp/instrumentation/tracing/opentelemetry.py @@ -5,13 +5,14 @@ from __future__ import annotations from contextlib import contextmanager from contextvars import Token -from typing import Optional, Dict, Sequence, cast, Callable, Iterator, TYPE_CHECKING +from typing import Any, Optional, Dict, Sequence, cast, Callable, Iterator, TYPE_CHECKING from opentelemetry import context as otel_context_module, trace from opentelemetry.trace import ( Span, SpanKind as OpenTelemetrySpanKind, Link as OpenTelemetryLink, + StatusCode, ) from opentelemetry.trace.propagation import get_current_span as get_current_span_otel from opentelemetry.propagate import extract, inject @@ -80,6 +81,8 @@ def start_span( kind: SpanKind = _SpanKind.INTERNAL, attributes: Optional[Attributes] = None, links: Optional[Sequence[Link]] = None, + start_time: Optional[int] = None, + context: Optional[Dict[str, Any]] = None, ) -> Span: """Starts a span without setting it as the current span in the context. @@ -91,17 +94,29 @@ def start_span( :paramtype attributes: Mapping[str, AttributeValue] :keyword links: Links to add to the span. :paramtype links: list[~corehttp.instrumentation.tracing.Link] + :keyword start_time: The start time of the span in nanoseconds since the epoch. + :paramtype start_time: Optional[int] + :keyword context: A dictionary of context values corresponding to the parent span. If not provided, + the current global context will be used. + :paramtype context: Optional[Dict[str, any]] :return: The span that was started :rtype: ~opentelemetry.trace.Span """ otel_kind = _KIND_MAPPINGS.get(kind, OpenTelemetrySpanKind.INTERNAL) otel_links = self._parse_links(links) + otel_context = None + if context: + otel_context = extract(context) + otel_span = self._tracer.start_span( name, + context=otel_context, kind=otel_kind, attributes=attributes, links=otel_links, + start_time=start_time, + record_exception=False, ) return otel_span @@ -114,12 +129,12 @@ def start_as_current_span( kind: SpanKind = _SpanKind.INTERNAL, attributes: Optional[Attributes] = None, links: Optional[Sequence[Link]] = None, + start_time: Optional[int] = None, + context: Optional[Dict[str, Any]] = None, end_on_exit: bool = True, ) -> Iterator[Span]: """Context manager that starts a span and sets it as the current span in the context. - Exiting the context manager will call the span's end method. - .. code:: python with tracer.start_as_current_span("span_name") as span: @@ -134,12 +149,19 @@ def start_as_current_span( :paramtype attributes: Optional[Attributes] :keyword links: Links to add to the span. :paramtype links: Optional[Sequence[Link]] + :keyword start_time: The start time of the span in nanoseconds since the epoch. + :paramtype start_time: Optional[int] + :keyword context: A dictionary of context values corresponding to the parent span. If not provided, + the current global context will be used. + :paramtype context: Optional[Dict[str, any]] :keyword end_on_exit: Whether to end the span when exiting the context manager. Defaults to True. :paramtype end_on_exit: bool :return: The span that was started - :rtype: ~opentelemetry.trace.Span + :rtype: Iterator[~opentelemetry.trace.Span] """ - span = self.start_span(name, kind=kind, attributes=attributes, links=links) + span = self.start_span( + name, kind=kind, attributes=attributes, links=links, start_time=start_time, context=context + ) with trace.use_span( # pylint: disable=not-context-manager span, record_exception=False, end_on_exit=end_on_exit ) as span: @@ -162,6 +184,17 @@ def use_span(cls, span: Span, *, end_on_exit: bool = True) -> Iterator[Span]: ) as active_span: yield active_span + @staticmethod + def set_span_error_status(span: Span, description: Optional[str] = None) -> None: + """Set the status of a span to ERROR with the provided description, if any. + + :param span: The span to set the ERROR status on. + :type span: ~opentelemetry.trace.Span + :param description: An optional description of the error. + :type description: str + """ + span.set_status(StatusCode.ERROR, description=description) + def _parse_links(self, links: Optional[Sequence[Link]]) -> Optional[Sequence[OpenTelemetryLink]]: if not links: return None diff --git a/sdk/core/corehttp/corehttp/paging.py b/sdk/core/corehttp/corehttp/paging.py index 438a75d76592..69498d027142 100644 --- a/sdk/core/corehttp/corehttp/paging.py +++ b/sdk/core/corehttp/corehttp/paging.py @@ -80,6 +80,13 @@ def __iter__(self) -> Iterator[Iterator[ReturnType]]: return self def __next__(self) -> Iterator[ReturnType]: + """Get the next page in the iterator. + + :returns: An iterator of objects in the next page. + :rtype: iterator[ReturnType] + :raises StopIteration: If there are no more pages to return. + :raises ~corehttp.exceptions.BaseError: If the request to get the next page fails. + """ if self.continuation_token is None and self._did_a_call_already: raise StopIteration("End of paging") try: @@ -129,6 +136,12 @@ def __iter__(self) -> Iterator[ReturnType]: return self def __next__(self) -> ReturnType: + """Get the next item in the iterator. + + :returns: The next item in the iterator. + :rtype: ReturnType + :raises StopIteration: If there are no more items to return. + """ if self._page_iterator is None: self._page_iterator = itertools.chain.from_iterable(self.by_page()) return next(self._page_iterator) diff --git a/sdk/core/corehttp/corehttp/rest/_aiohttp.py b/sdk/core/corehttp/corehttp/rest/_aiohttp.py index a9efbe0f8244..78e26e572aa5 100644 --- a/sdk/core/corehttp/corehttp/rest/_aiohttp.py +++ b/sdk/core/corehttp/corehttp/rest/_aiohttp.py @@ -38,6 +38,7 @@ ServiceRequestError, ServiceResponseError, IncompleteReadError, + ServiceResponseTimeoutError, ) from ..runtime.pipeline import AsyncPipeline from ..transport._base_async import _ResponseStopIteration @@ -224,7 +225,18 @@ async def read(self) -> bytes: """ if not self._content: self._stream_download_check() - self._content = await self._internal_response.read() + try: + self._content = await self._internal_response.read() + except aiohttp.client_exceptions.ClientPayloadError as err: + # This is the case that server closes connection before we finish the reading. aiohttp library + # raises ClientPayloadError. + raise IncompleteReadError(err, error=err) from err + except aiohttp.client_exceptions.ClientResponseError as err: + raise ServiceResponseError(err, error=err) from err + except asyncio.TimeoutError as err: + raise ServiceResponseTimeoutError(err, error=err) from err + except aiohttp.client_exceptions.ClientError as err: + raise ServiceRequestError(err, error=err) from err await self._set_read_checks() return _aiohttp_content_helper(self) @@ -306,7 +318,7 @@ async def __anext__(self): except aiohttp.client_exceptions.ClientResponseError as err: raise ServiceResponseError(err, error=err) from err except asyncio.TimeoutError as err: - raise ServiceResponseError(err, error=err) from err + raise ServiceResponseTimeoutError(err, error=err) from err except aiohttp.client_exceptions.ClientError as err: raise ServiceRequestError(err, error=err) from err except Exception: diff --git a/sdk/core/corehttp/corehttp/rest/_http_response_impl_async.py b/sdk/core/corehttp/corehttp/rest/_http_response_impl_async.py index e91fa7c6108c..66a5e4868c5b 100644 --- a/sdk/core/corehttp/corehttp/rest/_http_response_impl_async.py +++ b/sdk/core/corehttp/corehttp/rest/_http_response_impl_async.py @@ -69,6 +69,7 @@ async def read(self) -> bytes: async def iter_raw(self, **kwargs: Any) -> AsyncIterator[bytes]: """Asynchronously iterates over the response's bytes. Will not decompress in the process + :return: An async iterator of bytes from the response :rtype: AsyncIterator[bytes] """ @@ -79,6 +80,7 @@ async def iter_raw(self, **kwargs: Any) -> AsyncIterator[bytes]: async def iter_bytes(self, **kwargs: Any) -> AsyncIterator[bytes]: """Asynchronously iterates over the response's bytes. Will decompress in the process + :return: An async iterator of bytes from the response :rtype: AsyncIterator[bytes] """ diff --git a/sdk/core/corehttp/corehttp/rest/_requests_basic.py b/sdk/core/corehttp/corehttp/rest/_requests_basic.py index dd98a9ccf69a..6adf4ceada79 100644 --- a/sdk/core/corehttp/corehttp/rest/_requests_basic.py +++ b/sdk/core/corehttp/corehttp/rest/_requests_basic.py @@ -38,8 +38,8 @@ from ..runtime.pipeline import Pipeline from ._http_response_impl import _HttpResponseBaseImpl, HttpResponseImpl from ..exceptions import ( - ServiceRequestError, ServiceResponseError, + ServiceResponseTimeoutError, IncompleteReadError, HttpResponseError, DecodeError, @@ -162,6 +162,14 @@ def __next__(self): _LOGGER.warning("Unable to stream download.") internal_response.close() raise HttpResponseError(err, error=err) from err + except requests.ConnectionError as err: + internal_response.close() + if err.args and isinstance(err.args[0], ReadTimeoutError): + raise ServiceResponseTimeoutError(err, error=err) from err + raise ServiceResponseError(err, error=err) from err + except requests.RequestException as err: + internal_response.close() + raise ServiceResponseError(err, error=err) from err except Exception as err: _LOGGER.warning("Unable to stream download.") internal_response.close() @@ -178,7 +186,7 @@ def _read_raw_stream(response, chunk_size=1): except CoreDecodeError as e: raise DecodeError(e, error=e) from e except ReadTimeoutError as e: - raise ServiceRequestError(e, error=e) from e + raise ServiceResponseTimeoutError(e, error=e) from e else: # Standard file-like object. while True: diff --git a/sdk/core/corehttp/corehttp/rest/_rest_py3.py b/sdk/core/corehttp/corehttp/rest/_rest_py3.py index 82ecef36ff9e..6a51305ae24a 100644 --- a/sdk/core/corehttp/corehttp/rest/_rest_py3.py +++ b/sdk/core/corehttp/corehttp/rest/_rest_py3.py @@ -300,7 +300,7 @@ def json(self) -> Any: :return: The JSON deserialized response body :rtype: any - :raises json.decoder.JSONDecodeError or ValueError (in python 2.7) if object is not JSON decodable: + :raises json.decoder.JSONDecodeError: if the body is not valid JSON. """ @abc.abstractmethod @@ -309,7 +309,7 @@ def raise_for_status(self) -> None: If response is good, does nothing. - :raises ~corehttp.HttpResponseError if the object has an error status code.: + :raises ~corehttp.HttpResponseError: if the object has an error status code. """ diff --git a/sdk/core/corehttp/corehttp/runtime/pipeline/__init__.py b/sdk/core/corehttp/corehttp/runtime/pipeline/__init__.py index 9663a7d0b4d1..86c89a74595f 100644 --- a/sdk/core/corehttp/corehttp/runtime/pipeline/__init__.py +++ b/sdk/core/corehttp/corehttp/runtime/pipeline/__init__.py @@ -97,7 +97,7 @@ def __delitem__(self, key: str) -> None: def clear(self) -> None: # pylint: disable=docstring-missing-return, docstring-missing-rtype """Context objects cannot be cleared. - :raises: TypeError + :raises TypeError: If context objects cannot be cleared. """ raise TypeError("Context objects cannot be cleared.") @@ -106,7 +106,7 @@ def update( # pylint: disable=docstring-missing-return, docstring-missing-rtype ) -> None: """Context objects cannot be updated. - :raises: TypeError + :raises TypeError: If context objects cannot be updated. """ raise TypeError("Context objects cannot be updated.") diff --git a/sdk/core/corehttp/corehttp/runtime/pipeline/_tools.py b/sdk/core/corehttp/corehttp/runtime/pipeline/_tools.py index 9c3e09074501..e8d38e68837d 100644 --- a/sdk/core/corehttp/corehttp/runtime/pipeline/_tools.py +++ b/sdk/core/corehttp/corehttp/runtime/pipeline/_tools.py @@ -39,7 +39,7 @@ def await_result(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: :type args: list :rtype: any :return: The result of the function - :raises: TypeError + :raises TypeError: If the function returns an awaitable object. """ result = func(*args, **kwargs) if hasattr(result, "__await__"): diff --git a/sdk/core/corehttp/corehttp/runtime/policies/_authentication.py b/sdk/core/corehttp/corehttp/runtime/policies/_authentication.py index ec3623890a68..0a1723b79fdc 100644 --- a/sdk/core/corehttp/corehttp/runtime/policies/_authentication.py +++ b/sdk/core/corehttp/corehttp/runtime/policies/_authentication.py @@ -10,7 +10,7 @@ from ...credentials import TokenRequestOptions from ...rest import HttpResponse, HttpRequest from . import HTTPPolicy, SansIOHTTPPolicy -from ...exceptions import ServiceRequestError +from ...exceptions import ServiceRequestError, HttpResponseError if TYPE_CHECKING: @@ -93,7 +93,7 @@ class BearerTokenCredentialPolicy(_BearerTokenCredentialPolicyBase, HTTPPolicy[H :param str scopes: Lets you specify the type of access needed. :keyword auth_flows: A list of authentication flows to use for the credential. :paramtype auth_flows: list[dict[str, Union[str, list[dict[str, str]]]]] - :raises: :class:`~corehttp.exceptions.ServiceRequestError` + :raises ~corehttp.exceptions.ServiceRequestError: If the request fails. """ def on_request( @@ -158,7 +158,19 @@ def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HT if response.http_response.status_code == 401: self._token = None # any cached token is invalid if "WWW-Authenticate" in response.http_response.headers: - request_authorized = self.on_challenge(request, response) + try: + request_authorized = self.on_challenge(request, response) + except Exception as ex: + # If the response is streamed, read it so the error message is immediately available to the user. + # Otherwise, a generic error message will be given and the user will have to read the response + # body to see the actual error. + if response.context.options.get("stream"): + try: + response.http_response.read() # type: ignore + except Exception: # pylint:disable=broad-except + pass + # Raise the exception from the token request with the original 401 response. + raise ex from HttpResponseError(response=response.http_response) if request_authorized: try: response = self.next.send(request) @@ -215,7 +227,8 @@ class ServiceKeyCredentialPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseT :type credential: ~corehttp.credentials.ServiceKeyCredential :param str name: The name of the key header used for the credential. :keyword str prefix: The name of the prefix for the header value if any. - :raises: ValueError or TypeError + :raises ValueError: if name is None or empty. + :raises TypeError: if name is not a string or if credential is not an instance of ServiceKeyCredential. """ def __init__( # pylint: disable=unused-argument @@ -238,4 +251,9 @@ def __init__( # pylint: disable=unused-argument self._prefix = prefix + " " if prefix else "" def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Called before the policy sends a request. + + :param request: The request to be modified before sending. + :type request: ~corehttp.runtime.pipeline.PipelineRequest + """ request.http_request.headers[self._name] = f"{self._prefix}{self._credential.key}" diff --git a/sdk/core/corehttp/corehttp/runtime/policies/_authentication_async.py b/sdk/core/corehttp/corehttp/runtime/policies/_authentication_async.py index f1eee89b03c9..1797036cae7f 100644 --- a/sdk/core/corehttp/corehttp/runtime/policies/_authentication_async.py +++ b/sdk/core/corehttp/corehttp/runtime/policies/_authentication_async.py @@ -13,6 +13,7 @@ from ._base_async import AsyncHTTPPolicy from ._authentication import _BearerTokenCredentialPolicyBase from ...rest import AsyncHttpResponse, HttpRequest +from ...exceptions import HttpResponseError from ...utils._utils import get_running_async_lock if TYPE_CHECKING: @@ -66,7 +67,7 @@ async def on_request( :type request: ~corehttp.runtime.pipeline.PipelineRequest :keyword auth_flows: A list of authentication flows to use for the credential. :paramtype auth_flows: list[dict[str, Union[str, list[dict[str, str]]]]] - :raises: :class:`~corehttp.exceptions.ServiceRequestError` + :raises ~corehttp.exceptions.ServiceRequestError: If the request fails. """ # If auth_flows is an empty list, we should not attempt to authorize the request. if auth_flows is not None and len(auth_flows) == 0: @@ -123,7 +124,20 @@ async def send( if response.http_response.status_code == 401: self._token = None # any cached token is invalid if "WWW-Authenticate" in response.http_response.headers: - request_authorized = await self.on_challenge(request, response) + try: + request_authorized = await self.on_challenge(request, response) + except Exception as ex: + # If the response is streamed, read it so the error message is immediately available to the user. + # Otherwise, a generic error message will be given and the user will have to read the response + # body to see the actual error. + if response.context.options.get("stream"): + try: + await response.http_response.read() # type: ignore + except Exception: # pylint:disable=broad-except + pass + + # Raise the exception from the token request with the original 401 response + raise ex from HttpResponseError(response=response.http_response) if request_authorized: try: response = await self.next.send(request) diff --git a/sdk/core/corehttp/corehttp/runtime/policies/_distributed_tracing.py b/sdk/core/corehttp/corehttp/runtime/policies/_distributed_tracing.py index a26b63c0bc3c..50ff9466d3a4 100644 --- a/sdk/core/corehttp/corehttp/runtime/policies/_distributed_tracing.py +++ b/sdk/core/corehttp/corehttp/runtime/policies/_distributed_tracing.py @@ -55,6 +55,11 @@ def __init__( # pylint: disable=unused-argument self._instrumentation_config = instrumentation_config def on_request(self, request: PipelineRequest[HttpRequest]) -> None: + """Starts a span for the network call. + + :param request: The PipelineRequest object. + :type request: ~corehttp.runtime.pipeline.PipelineRequest + """ ctxt = request.context.options try: tracing_options: TracingOptions = ctxt.pop("tracing_options", {}) @@ -103,6 +108,13 @@ def on_response( request: PipelineRequest[HttpRequest], response: PipelineResponse[HttpRequest, SansIOHttpResponse], ) -> None: + """Ends the span for the network call and updates its status. + + :param request: The PipelineRequest object. + :type request: ~corehttp.runtime.pipeline.PipelineRequest + :param response: The PipelineResponse object. + :type response: ~corehttp.runtime.pipeline.PipelineResponse + """ if self.TRACING_CONTEXT not in request.context: return @@ -127,6 +139,7 @@ def _set_http_client_span_attributes( response: Optional[SansIOHttpResponse] = None, ) -> None: """Add attributes to an HTTP client span. + :param span: The span to add attributes to. :type span: ~opentelemetry.trace.Span :param request: The request made diff --git a/sdk/core/corehttp/corehttp/runtime/policies/_retry.py b/sdk/core/corehttp/corehttp/runtime/policies/_retry.py index 54e55a3c26b2..6397e309e583 100644 --- a/sdk/core/corehttp/corehttp/runtime/policies/_retry.py +++ b/sdk/core/corehttp/corehttp/runtime/policies/_retry.py @@ -52,6 +52,8 @@ class RetryMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum for retry modes.""" + # pylint: disable=enum-must-be-uppercase Exponential = "exponential" Fixed = "fixed" @@ -104,7 +106,7 @@ def configure_retries(self, options: Dict[str, Any]) -> Dict[str, Any]: "read": options.pop("retry_read", self.read_retries), "status": options.pop("retry_status", self.status_retries), "backoff": options.pop("retry_backoff_factor", self.backoff_factor), - "max_backoff": options.pop("retry_backoff_max", self.BACKOFF_MAX), + "max_backoff": options.pop("retry_backoff_max", self.backoff_max), "methods": options.pop("retry_on_methods", self._method_whitelist), "timeout": options.pop("timeout", self.timeout), "history": [], @@ -394,28 +396,21 @@ class RetryPolicy(RetryPolicyBase, HTTPPolicy[HttpRequest, HttpResponse]): :keyword int retry_total: Total number of retries to allow. Takes precedence over other counts. Default value is 10. - :keyword int retry_connect: How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Default value is 3. - :keyword int retry_read: How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Default value is 3. - :keyword int retry_status: How many times to retry on bad status codes. Default value is 3. - :keyword float retry_backoff_factor: A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). In fixed mode, retry policy will always sleep for {backoff factor}. In 'exponential' mode, retry policy will sleep for: `{backoff factor} * (2 ** ({number of total retries} - 1))` seconds. If the backoff_factor is 0.1, then the retry will sleep for [0.0s, 0.2s, 0.4s, ...] between retries. The default value is 0.8. - :keyword int retry_backoff_max: The maximum back off time. Default value is 120 seconds (2 minutes). - :keyword RetryMode retry_mode: Fixed or exponential delay between attemps, default is exponential. - :keyword int timeout: Timeout setting for the operation in seconds, default is 604800s (7 days). """ @@ -481,10 +476,10 @@ def send(self, request: PipelineRequest[HttpRequest]) -> PipelineResponse[HttpRe :param request: The PipelineRequest object :type request: ~corehttp.runtime.pipeline.PipelineRequest - :return: Returns the PipelineResponse or raises error if maximum retries exceeded. + :return: The PipelineResponse. :rtype: ~corehttp.runtime.pipeline.PipelineResponse - :raises: ~corehttp.exceptions.BaseError if maximum retries exceeded. - :raises: ~corehttp.exceptions.ClientAuthenticationError if authentication + :raises ~corehttp.exceptions.BaseError: if maximum retries exceeded. + :raises ~corehttp.exceptions.ClientAuthenticationError: if authentication fails. """ retry_active = True response = None diff --git a/sdk/core/corehttp/corehttp/runtime/policies/_retry_async.py b/sdk/core/corehttp/corehttp/runtime/policies/_retry_async.py index bd495e20c180..d482cce1ab5b 100644 --- a/sdk/core/corehttp/corehttp/runtime/policies/_retry_async.py +++ b/sdk/core/corehttp/corehttp/runtime/policies/_retry_async.py @@ -54,23 +54,18 @@ class AsyncRetryPolicy(RetryPolicyBase, AsyncHTTPPolicy[HttpRequest, AsyncHttpRe :keyword int retry_total: Total number of retries to allow. Takes precedence over other counts. Default value is 10. - :keyword int retry_connect: How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Default value is 3. - :keyword int retry_read: How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Default value is 3. - :keyword int retry_status: How many times to retry on bad status codes. Default value is 3. - :keyword float retry_backoff_factor: A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). Retry policy will sleep for: `{backoff factor} * (2 ** ({number of total retries} - 1))` seconds. If the backoff_factor is 0.1, then the retry will sleep for [0.0s, 0.2s, 0.4s, ...] between retries. The default value is 0.8. - :keyword int retry_backoff_max: The maximum back off time. Default value is 120 seconds (2 minutes). """ @@ -138,10 +133,10 @@ async def send(self, request: PipelineRequest[HttpRequest]) -> PipelineResponse[ :param request: The PipelineRequest object :type request: ~corehttp.runtime.pipeline.PipelineRequest - :return: Returns the PipelineResponse or raises error if maximum retries exceeded. + :return: The PipelineResponse. :rtype: ~corehttp.runtime.pipeline.PipelineResponse - :raise: ~corehttp.exceptions.BaseError if maximum retries exceeded. - :raise: ~corehttp.exceptions.ClientAuthenticationError if authentication fails + :raises ~corehttp.exceptions.BaseError: if maximum retries exceeded. + :raises ~corehttp.exceptions.ClientAuthenticationError: if authentication fails. """ retry_active = True response = None diff --git a/sdk/core/corehttp/corehttp/runtime/policies/_universal.py b/sdk/core/corehttp/corehttp/runtime/policies/_universal.py index ebb813170dd5..cce0989a3ee4 100644 --- a/sdk/core/corehttp/corehttp/runtime/policies/_universal.py +++ b/sdk/core/corehttp/corehttp/runtime/policies/_universal.py @@ -143,6 +143,7 @@ def user_agent(self) -> str: def add_user_agent(self, value: str) -> None: """Add value to current user agent with a space. + :param str value: value to add to user agent. """ self._user_agent = "{} {}".format(self._user_agent, value) @@ -401,6 +402,11 @@ def deserialize_from_http_generics( return cls.deserialize_from_text(response.text(encoding), mime_type, response=response) def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Set the response encoding in the request context. + + :param request: The PipelineRequest object. + :type request: ~corehttp.runtime.pipeline.PipelineRequest + """ options = request.context.options response_encoding = options.pop("response_encoding", self._response_encoding) if response_encoding: @@ -452,6 +458,11 @@ def __init__( self.proxies = proxies def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Adds the proxy information to the request context. + + :param request: The PipelineRequest object. + :type request: ~corehttp.runtime.pipeline.PipelineRequest + """ ctxt = request.context.options if self.proxies and "proxies" not in ctxt: ctxt["proxies"] = self.proxies diff --git a/sdk/core/corehttp/corehttp/serialization.py b/sdk/core/corehttp/corehttp/serialization.py index a9470c3bf37e..49c1c6066918 100644 --- a/sdk/core/corehttp/corehttp/serialization.py +++ b/sdk/core/corehttp/corehttp/serialization.py @@ -4,14 +4,23 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +# pylint: disable=protected-access import base64 +from functools import partial from json import JSONEncoder -from typing import Union, cast, Any +from typing import Dict, List, Optional, Union, cast, Any, Type, Callable, Tuple from datetime import datetime, date, time, timedelta from datetime import timezone -__all__ = ["NULL", "CoreJSONEncoder"] +__all__ = [ + "NULL", + "CoreJSONEncoder", + "is_generated_model", + "attribute_list", + "TypeHandlerRegistry", +] +TZ_UTC = timezone.utc class _Null: @@ -111,10 +120,176 @@ def _datetime_as_isostr(dt: Union[datetime, date, time, timedelta]) -> str: return _timedelta_as_isostr(dt) +class TypeHandlerRegistry: + """A registry for custom serializers and deserializers for specific types or conditions.""" + + def __init__(self) -> None: + self._serializer_types: Dict[Type, Callable] = {} + self._deserializer_types: Dict[Type, Callable] = {} + self._serializer_predicates: List[Tuple[Callable[[Any], bool], Callable]] = [] + self._deserializer_predicates: List[Tuple[Callable[[Any], bool], Callable]] = [] + + self._serializer_cache: Dict[Type, Optional[Callable]] = {} + self._deserializer_cache: Dict[Type, Optional[Callable]] = {} + + def register_serializer( + self, condition: Union[Type, Callable[[Any], bool]] + ) -> Callable[[Callable[[Any], Dict[str, Any]]], Callable[[Any], Dict[str, Any]]]: + """Decorator to register a serializer. + + The handler function is expected to take a single argument, the object to serialize, + and return a dictionary representation of that object. + + Examples: + + .. code-block:: python + + @registry.register_serializer(CustomModel) + def serialize_single_type(value: CustomModel) -> dict: + return value.to_dict() + + @registry.register_serializer(lambda x: isinstance(x, BaseModel)) + def serialize_with_condition(value: BaseModel) -> dict: + return value.to_dict() + + # Called manually for a specific type + def custom_serializer(value: CustomModel) -> Dict[str, Any]: + return {"custom": value.custom} + + registry.register_serializer(CustomModel)(custom_serializer) + + :param condition: A type or a callable predicate function that takes an object and returns a bool. + :type condition: Union[Type, Callable[[Any], bool]] + :return: A decorator that registers the handler function. + :rtype: Callable[[Callable[[Any], Dict[str, Any]]], Callable[[Any], Dict[str, Any]]] + :raises TypeError: If the condition is neither a type nor a callable. + """ + + def decorator(handler_func: Callable[[Any], Dict[str, Any]]) -> Callable[[Any], Dict[str, Any]]: + if isinstance(condition, type): + self._serializer_types[condition] = handler_func + elif callable(condition): + self._serializer_predicates.append((condition, handler_func)) + else: + raise TypeError("Condition must be a type or a callable predicate function.") + + self._serializer_cache.clear() + return handler_func + + return decorator + + def register_deserializer( + self, condition: Union[Type, Callable[[Any], bool]] + ) -> Callable[[Callable[[Type, Dict[str, Any]], Any]], Callable[[Type, Dict[str, Any]], Any]]: + """Decorator to register a deserializer. + + The handler function is expected to take two arguments: the target type and the data dictionary, + and return an instance of the target type. + + Examples: + + .. code-block:: python + + @registry.register_deserializer(CustomModel) + def deserialize_single_type(cls: Type[CustomModel], data: dict) -> CustomModel: + return cls(**data) + + @registry.register_deserializer(lambda t: issubclass(t, BaseModel)) + def deserialize_with_condition(cls: Type[BaseModel], data: dict) -> BaseModel: + return cls(**data) + + # Called manually for a specific type + def custom_deserializer(cls: Type[CustomModel], data: Dict[str, Any]) -> CustomModel: + return cls(custom=data["custom"]) + + registry.register_deserializer(CustomModel)(custom_deserializer) + + :param condition: A type or a callable predicate function that takes an object and returns a bool. + :type condition: Union[Type, Callable[[Any], bool]] + :return: A decorator that registers the handler function. + :rtype: Callable[[Callable[[Type, Dict[str, Any]], Any]], Callable[[Type, Dict[str, Any]], Any]] + :raises TypeError: If the condition is neither a type nor a callable. + """ + + def decorator(handler_func: Callable[[Type, Dict[str, Any]], Any]) -> Callable[[Type, Dict[str, Any]], Any]: + if isinstance(condition, type): + self._deserializer_types[condition] = handler_func + elif callable(condition): + self._deserializer_predicates.append((condition, handler_func)) + else: + raise TypeError("Condition must be a type or a callable predicate function.") + + self._deserializer_cache.clear() + return handler_func + + return decorator + + def get_serializer(self, obj: Any) -> Optional[Callable[[Any], Dict[str, Any]]]: + """Gets the appropriate serializer for an object. + + It first checks the type dictionary for a direct type match. + If no match is found, it iterates through the predicate list to find a match. + + Results of the lookup are cached for performance based on the object's type. + + :param obj: The object to serialize. + :type obj: any + :return: The serializer function if found, otherwise None. + :rtype: Optional[Callable[[Any], Dict[str, Any]]] + """ + obj_type = type(obj) + if obj_type in self._serializer_cache: + return self._serializer_cache[obj_type] + + handler = self._serializer_types.get(type(obj)) + if not handler: + for predicate, pred_handler in self._serializer_predicates: + if predicate(obj): + handler = pred_handler + break + + self._serializer_cache[obj_type] = handler + return handler + + def get_deserializer(self, cls: Type) -> Optional[Callable[[Dict[str, Any]], Any]]: + """Gets the appropriate deserializer for a class. + + It first checks the type dictionary for a direct type match. + If no match is found, it iterates through the predicate list to find a match. + + Results of the lookup are cached for performance based on the class. + + :param cls: The class to deserialize. + :type cls: type + :return: A deserializer function bound to the specified class that takes a dictionary and returns + an instance of that class, or None if no deserializer is found. + :rtype: Optional[Callable[[Dict[str, Any]], Any]] + """ + if cls in self._deserializer_cache: + return self._deserializer_cache[cls] + + handler = self._deserializer_types.get(cls) + if not handler: + for predicate, pred_handler in self._deserializer_predicates: + if predicate(cls): + handler = pred_handler + break + + self._deserializer_cache[cls] = partial(handler, cls) if handler else None + return self._deserializer_cache[cls] + + class CoreJSONEncoder(JSONEncoder): """A JSON encoder that's capable of serializing datetime objects and bytes.""" def default(self, o: Any) -> Any: + """Override the default method to handle datetime and bytes serialization. + + :param o: The object to serialize. + :type o: Any + :return: A JSON-serializable representation of the object. + :rtype: Any + """ if isinstance(o, (bytes, bytearray)): return base64.b64encode(o).decode() try: @@ -122,3 +297,62 @@ def default(self, o: Any) -> Any: except AttributeError: pass return super(CoreJSONEncoder, self).default(o) + + +def is_generated_model(obj: Any) -> bool: + """Check if the object is a generated SDK model. + + :param obj: The object to check. + :type obj: any + :return: True if the object is a generated SDK model, False otherwise. + :rtype: bool + """ + return bool(getattr(obj, "_is_model", False) or hasattr(obj, "_attribute_map")) + + +def _get_flattened_attribute(obj: Any) -> Optional[str]: + """Get the name of the flattened attribute in a generated TypeSpec model if one exists. + + :param any obj: The object to check. + :return: The name of the flattened attribute if it exists, otherwise None. + :rtype: Optional[str] + """ + flattened_items = None + try: + flattened_items = getattr(obj, next(a for a in dir(obj) if "__flattened_items" in a), None) + except StopIteration: + return None + + if flattened_items is None: + return None + + for k, v in obj._attr_to_rest_field.items(): + try: + if set(v._class_type._attr_to_rest_field.keys()).intersection(set(flattened_items)): + return k + except AttributeError: + # if the attribute does not have _class_type, it is not a typespec generated model + continue + return None + + +def attribute_list(obj: Any) -> List[str]: + """Get a list of attribute names for a generated SDK model. + + :param obj: The object to get attributes from. + :type obj: any + :return: A list of attribute names. + :rtype: List[str] + """ + if not is_generated_model(obj): + raise TypeError("Object is not a generated SDK model.") + if hasattr(obj, "_attribute_map"): + return list(obj._attribute_map.keys()) + flattened_attribute = _get_flattened_attribute(obj) + retval: List[str] = [] + for attr_name, rest_field in obj._attr_to_rest_field.items(): + if flattened_attribute == attr_name: + retval.extend(attribute_list(rest_field._class_type)) + else: + retval.append(attr_name) + return retval diff --git a/sdk/core/corehttp/corehttp/transport/_base.py b/sdk/core/corehttp/corehttp/transport/_base.py index f210ae95952c..dbcabc352547 100644 --- a/sdk/core/corehttp/corehttp/transport/_base.py +++ b/sdk/core/corehttp/corehttp/transport/_base.py @@ -80,10 +80,8 @@ def _handle_non_stream_rest_response(response: HttpResponse) -> None: """ try: response.read() + finally: response.close() - except Exception as exc: - response.close() - raise exc class HttpTransport(ContextManager["HttpTransport"], abc.ABC, Generic[HTTPRequestType, HTTPResponseType]): diff --git a/sdk/core/corehttp/corehttp/transport/_base_async.py b/sdk/core/corehttp/corehttp/transport/_base_async.py index 23092fdcfd89..b12d95b413c4 100644 --- a/sdk/core/corehttp/corehttp/transport/_base_async.py +++ b/sdk/core/corehttp/corehttp/transport/_base_async.py @@ -46,10 +46,8 @@ async def _handle_non_stream_rest_response(response: AsyncHttpResponse) -> None: """ try: await response.read() + finally: await response.close() - except Exception as exc: - await response.close() - raise exc class _ResponseStopIteration(Exception): diff --git a/sdk/core/corehttp/corehttp/transport/aiohttp/_aiohttp.py b/sdk/core/corehttp/corehttp/transport/aiohttp/_aiohttp.py index 6decaddf4dd8..ec74b60cbfe8 100644 --- a/sdk/core/corehttp/corehttp/transport/aiohttp/_aiohttp.py +++ b/sdk/core/corehttp/corehttp/transport/aiohttp/_aiohttp.py @@ -24,7 +24,7 @@ # # -------------------------------------------------------------------------- from __future__ import annotations -from typing import Optional, TYPE_CHECKING, Type, cast, MutableMapping +from typing import Optional, TYPE_CHECKING, Type, MutableMapping from types import TracebackType import logging @@ -34,7 +34,9 @@ from ...exceptions import ( ServiceRequestError, + ServiceRequestTimeoutError, ServiceResponseError, + ServiceResponseTimeoutError, ) from .._base_async import AsyncHttpTransport, _handle_non_stream_rest_response from .._base import _create_connection_config @@ -52,6 +54,15 @@ CONTENT_CHUNK_SIZE = 10 * 1024 _LOGGER = logging.getLogger(__name__) +try: + # ConnectionTimeoutError was only introduced in aiohttp 3.10 so we want to keep this + # backwards compatible. If client is using aiohttp <3.10, the behaviour will safely + # fall back to treating a TimeoutError as a ServiceResponseError (that wont be retried). + from aiohttp.client_exceptions import ConnectionTimeoutError +except ImportError: + + class ConnectionTimeoutError(Exception): ... # type: ignore[no-redef] + class AioHttpTransport(AsyncHttpTransport): """AioHttp HTTP sender implementation. @@ -71,6 +82,7 @@ def __init__(self, *, session: Optional[aiohttp.ClientSession] = None, session_o raise ValueError("session_owner cannot be False if no session is provided") self.connection_config = _create_connection_config(**kwargs) self._use_env_settings = kwargs.pop("use_env_settings", True) + self._has_been_opened = False async def __aenter__(self): await self.open() @@ -86,23 +98,31 @@ async def __aexit__( async def open(self): """Opens the connection.""" - if not self.session and self._session_owner: - jar = aiohttp.DummyCookieJar() - clientsession_kwargs = { - "trust_env": self._use_env_settings, - "cookie_jar": jar, - "auto_decompress": False, - } - self.session = aiohttp.ClientSession(**clientsession_kwargs) - # pyright has trouble to understand that self.session is not None, since we raised at worst in the init - self.session = cast(aiohttp.ClientSession, self.session) + if self._has_been_opened and not self.session: + raise ValueError( + "HTTP transport has already been closed. " + "You may check if you're calling a function outside of the `async with` of your client creation, " + "or if you called `await close()` on your client already." + ) + if not self.session: + if self._session_owner: + jar = aiohttp.DummyCookieJar() + clientsession_kwargs = { + "trust_env": self._use_env_settings, + "cookie_jar": jar, + "auto_decompress": False, + } + self.session = aiohttp.ClientSession(**clientsession_kwargs) + else: + raise ValueError("session_owner cannot be False and no session is available") + + self._has_been_opened = True await self.session.__aenter__() async def close(self): """Closes the connection.""" if self._session_owner and self.session: await self.session.close() - self._session_owner = False self.session = None def _build_ssl_config(self, cert, verify): @@ -221,11 +241,16 @@ async def send( ) if not stream: await _handle_non_stream_rest_response(response) - + except AttributeError as err: + if self.session is None: + raise ValueError("No session available for request.") from err + raise except aiohttp.client_exceptions.ClientResponseError as err: raise ServiceResponseError(err, error=err) from err + except ConnectionTimeoutError as err: + raise ServiceRequestTimeoutError(err, error=err) from err except asyncio.TimeoutError as err: - raise ServiceResponseError(err, error=err) from err + raise ServiceResponseTimeoutError(err, error=err) from err except aiohttp.client_exceptions.ClientError as err: raise ServiceRequestError(err, error=err) from err return response diff --git a/sdk/core/corehttp/corehttp/transport/requests/_requests_basic.py b/sdk/core/corehttp/corehttp/transport/requests/_requests_basic.py index e3e45b091f92..a708ef4c0574 100644 --- a/sdk/core/corehttp/corehttp/transport/requests/_requests_basic.py +++ b/sdk/core/corehttp/corehttp/transport/requests/_requests_basic.py @@ -24,7 +24,7 @@ # # -------------------------------------------------------------------------- import logging -from typing import Optional, Union, TypeVar, cast, MutableMapping, TYPE_CHECKING +from typing import Optional, Union, TypeVar, MutableMapping, TYPE_CHECKING from urllib3.util.retry import Retry from urllib3.exceptions import ( ProtocolError, @@ -35,7 +35,9 @@ from ...exceptions import ( ServiceRequestError, + ServiceRequestTimeoutError, ServiceResponseError, + ServiceResponseTimeoutError, IncompleteReadError, HttpResponseError, ) @@ -84,6 +86,7 @@ def __init__(self, **kwargs) -> None: raise ValueError("session_owner cannot be False if no session is provided") self.connection_config = _create_connection_config(**kwargs) self._use_env_settings = kwargs.pop("use_env_settings", True) + self._has_been_opened = False def __enter__(self) -> "RequestsTransport": self.open() @@ -106,19 +109,26 @@ def _init_session(self, session: requests.Session) -> None: session.mount(p, adapter) def open(self): - if not self.session and self._session_owner: - self.session = requests.Session() - self._init_session(self.session) - # pyright has trouble to understand that self.session is not None, since we raised at worst in the init - self.session = cast(requests.Session, self.session) + if self._has_been_opened and not self.session: + raise ValueError( + "HTTP transport has already been closed. " + "You may check if you're calling a function outside of the `with` of your client creation, " + "or if you called `close()` on your client already." + ) + if not self.session: + if self._session_owner: + self.session = requests.Session() + self._init_session(self.session) + else: + raise ValueError("session_owner cannot be False and no session is available") + self._has_been_opened = True def close(self): if self._session_owner and self.session: self.session.close() - self._session_owner = False self.session = None - def send( + def send( # pylint: disable=too-many-statements self, request: "RestHttpRequest", *, @@ -165,13 +175,18 @@ def send( ) response.raw.enforce_content_length = True - except ( - NewConnectionError, - ConnectTimeoutError, - ) as err: + except AttributeError as err: + if self.session is None: + raise ValueError("No session available for request.") from err + raise + except NewConnectionError as err: error = ServiceRequestError(err, error=err) + except ConnectTimeoutError as err: + error = ServiceRequestTimeoutError(err, error=err) + except requests.exceptions.ConnectTimeout as err: + error = ServiceRequestTimeoutError(err, error=err) except requests.exceptions.ReadTimeout as err: - error = ServiceResponseError(err, error=err) + error = ServiceResponseTimeoutError(err, error=err) except requests.exceptions.ConnectionError as err: if err.args and isinstance(err.args[0], ProtocolError): error = ServiceResponseError(err, error=err) @@ -186,7 +201,7 @@ def send( _LOGGER.warning("Unable to stream download.") error = HttpResponseError(err, error=err) except requests.RequestException as err: - error = ServiceRequestError(err, error=err) + error = ServiceResponseError(err, error=err) if error: raise error diff --git a/sdk/core/corehttp/corehttp/utils/_utils.py b/sdk/core/corehttp/corehttp/utils/_utils.py index 7918e4d72a3a..21bb33719d21 100644 --- a/sdk/core/corehttp/corehttp/utils/_utils.py +++ b/sdk/core/corehttp/corehttp/utils/_utils.py @@ -169,9 +169,10 @@ def get_file_items(files: "FilesType") -> Sequence[Tuple[str, "FileType"]]: def get_running_async_lock() -> AsyncContextManager: """Get a lock instance from the async library that the current context is running under. + :return: An instance of the running async library's Lock class. :rtype: AsyncContextManager - :raises: RuntimeError if the current context is not running under an async library. + :raises RuntimeError: if the current context is not running under an async library. """ try: diff --git a/sdk/core/corehttp/tests/async_tests/test_transport_async.py b/sdk/core/corehttp/tests/async_tests/test_transport_async.py new file mode 100644 index 000000000000..d91e2baf74cd --- /dev/null +++ b/sdk/core/corehttp/tests/async_tests/test_transport_async.py @@ -0,0 +1,121 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See LICENSE.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +from unittest import mock +import asyncio +from packaging.version import Version + +from corehttp.rest import HttpRequest +from corehttp.transport.aiohttp import AioHttpTransport +from corehttp.runtime.pipeline import AsyncPipeline +from corehttp.exceptions import ( + ServiceResponseError, + ServiceRequestError, + ServiceRequestTimeoutError, + ServiceResponseTimeoutError, +) + +import aiohttp +import pytest + + +@pytest.mark.asyncio +async def test_already_close_with_with(caplog, port): + transport = AioHttpTransport() + + request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port)) + + async with AsyncPipeline(transport) as pipeline: + await pipeline.run(request) + + # This is now closed, new requests should fail + with pytest.raises(ValueError) as err: + await transport.send(request) + assert "HTTP transport has already been closed." in str(err) + + +@pytest.mark.asyncio +async def test_already_close_manually(caplog, port): + transport = AioHttpTransport() + + request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port)) + + await transport.send(request) + await transport.close() + + # This is now closed, new requests should fail + with pytest.raises(ValueError) as err: + await transport.send(request) + assert "HTTP transport has already been closed." in str(err) + + +@pytest.mark.asyncio +async def test_close_too_soon_works_fine(caplog, port): + transport = AioHttpTransport() + + request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port)) + + await transport.close() + result = await transport.send(request) + + assert result # No exception is good enough here + + +@pytest.mark.asyncio +async def test_aiohttp_timeout_response(port): + async with AioHttpTransport() as transport: + + request = HttpRequest("GET", f"http://localhost:{port}/basic/string") + + with mock.patch.object( + aiohttp.ClientResponse, "start", side_effect=asyncio.TimeoutError("Too slow!") + ) as mock_method: + with pytest.raises(ServiceResponseTimeoutError) as err: + await transport.send(request) + + with pytest.raises(ServiceResponseError) as err: + await transport.send(request) + + stream_resp = HttpRequest("GET", f"http://localhost:{port}/streams/basic") + with pytest.raises(ServiceResponseTimeoutError) as err: + await transport.send(stream_resp, stream=True) + + stream_resp = await transport.send(stream_resp, stream=True) + with mock.patch.object( + aiohttp.streams.StreamReader, "read", side_effect=asyncio.TimeoutError("Too slow!") + ) as mock_method: + with pytest.raises(ServiceResponseTimeoutError) as err: + await stream_resp.read() + + +@pytest.mark.asyncio +async def test_aiohttp_timeout_request(): + async with AioHttpTransport() as transport: + transport.session._connector.connect = mock.Mock(side_effect=asyncio.TimeoutError("Too slow!")) + + request = HttpRequest("GET", f"http://localhost:12345/basic/string") + + # aiohttp 3.10 introduced separate connection timeout + if Version(aiohttp.__version__) >= Version("3.10"): + with pytest.raises(ServiceRequestTimeoutError) as err: + await transport.send(request) + + with pytest.raises(ServiceRequestError) as err: + await transport.send(request) + + stream_request = HttpRequest("GET", f"http://localhost:12345/streams/basic") + with pytest.raises(ServiceRequestTimeoutError) as err: + await transport.send(stream_request, stream=True) + + else: + with pytest.raises(ServiceResponseTimeoutError) as err: + await transport.send(request) + + with pytest.raises(ServiceResponseError) as err: + await transport.send(request) + + stream_request = HttpRequest("GET", f"http://localhost:12345/streams/basic") + with pytest.raises(ServiceResponseTimeoutError) as err: + await transport.send(stream_request, stream=True) diff --git a/sdk/core/corehttp/tests/test_stream_generator.py b/sdk/core/corehttp/tests/test_stream_generator.py index 30bbc70fec5a..b15c9440bd9b 100644 --- a/sdk/core/corehttp/tests/test_stream_generator.py +++ b/sdk/core/corehttp/tests/test_stream_generator.py @@ -9,6 +9,7 @@ from corehttp.transport import HttpTransport from corehttp.runtime.pipeline import Pipeline from corehttp.rest._requests_basic import StreamDownloadGenerator, RestRequestsTransportResponse +from corehttp.exceptions import ServiceResponseError import pytest from utils import HTTP_RESPONSES, create_http_response, create_transport_response @@ -61,7 +62,7 @@ def close(self): http_response = create_http_response(http_response, http_request, MockInternalResponse()) stream = StreamDownloadGenerator(pipeline, http_response, decompress=False) with mock.patch("time.sleep", return_value=None): - with pytest.raises(requests.exceptions.ConnectionError): + with pytest.raises(ServiceResponseError): stream.__next__() @@ -108,5 +109,5 @@ def close(self): ) downloader = response.iter_raw() - with pytest.raises(requests.exceptions.ConnectionError): + with pytest.raises(ServiceResponseError): b"".join(downloader) diff --git a/sdk/core/corehttp/tests/test_tracer_otel.py b/sdk/core/corehttp/tests/test_tracer_otel.py index 074ed50a5c05..cb54e7920c18 100644 --- a/sdk/core/corehttp/tests/test_tracer_otel.py +++ b/sdk/core/corehttp/tests/test_tracer_otel.py @@ -304,10 +304,6 @@ def test_span_exception_without_current_context(tracing_helper): finished_spans = tracing_helper.exporter.get_finished_spans() assert len(finished_spans) == 1 - assert len(finished_spans[0].events) == 1 - assert finished_spans[0].events[0].name == "exception" - assert finished_spans[0].events[0].attributes["exception.type"] == "ValueError" - assert finished_spans[0].events[0].attributes["exception.message"] == "This is an error" assert finished_spans[0].status.status_code == OtelStatusCode.ERROR @@ -327,10 +323,6 @@ def test_span_exception_exit(tracing_helper): finished_spans = tracing_helper.exporter.get_finished_spans() assert len(finished_spans) == 1 - assert len(finished_spans[0].events) == 1 - assert finished_spans[0].events[0].name == "exception" - assert finished_spans[0].events[0].attributes["exception.type"] == "ValueError" - assert finished_spans[0].events[0].attributes["exception.message"] == "This is an error" assert finished_spans[0].status.status_code == OtelStatusCode.ERROR @@ -365,3 +357,67 @@ def test_tracer_caching_different_args(): assert tracer1 is tracer2 assert tracer1 is not tracer3 + + +def test_tracer_set_span_error(tracing_helper): + """Test that the tracer's set_span_status method works correctly.""" + tracer = get_tracer() + assert tracer + + with tracer.start_as_current_span(name="ok-span") as span: + tracer.set_span_error_status(span) + + with tracer.start_as_current_span(name="ok-span") as span: + tracer.set_span_error_status(span, "This is an error") + + # Verify status on finished spans + finished_spans = tracing_helper.exporter.get_finished_spans() + assert len(finished_spans) == 2 + + assert finished_spans[0].status.status_code == OtelStatusCode.ERROR + assert finished_spans[0].status.description is None + + assert finished_spans[1].status.status_code == OtelStatusCode.ERROR + assert finished_spans[1].status.description == "This is an error" + + +def test_start_span_with_start_time(tracing_helper): + """Test that a span can be started with a custom start time.""" + tracer = get_tracer() + assert tracer + start_time = 1234567890 + with tracer.start_as_current_span(name="foo-span", start_time=start_time) as span: + assert span.start_time == start_time + finished_spans = tracing_helper.exporter.get_finished_spans() + assert len(finished_spans) == 1 + assert finished_spans[0].start_time == start_time + + span = tracer.start_span(name="foo-span", start_time=start_time) + assert span.start_time == start_time + span.end() + finished_spans = tracing_helper.exporter.get_finished_spans() + assert len(finished_spans) == 2 + assert finished_spans[1].start_time == start_time + + +def test_tracer_with_custom_context(tracing_helper): + """Test that the tracer can start a span with a custom context.""" + tracer = get_tracer() + assert tracer + + with tracer.start_as_current_span(name="foo-span") as foo_span: + foo_trace_context = tracer.get_trace_context() + + assert "traceparent" in foo_trace_context + + with tracer.start_as_current_span(name="bar-span", context=dict(foo_trace_context)) as bar_span: + pass + + finished_spans = tracing_helper.exporter.get_finished_spans() + assert len(finished_spans) == 2 + assert finished_spans[0].name == "foo-span" + assert finished_spans[1].name == "bar-span" + assert finished_spans[1].context.trace_id == finished_spans[0].context.trace_id + + # foo_span should be the parent of bar_span + assert finished_spans[1].parent.span_id == finished_spans[0].context.span_id diff --git a/sdk/core/corehttp/tests/test_transport.py b/sdk/core/corehttp/tests/test_transport.py new file mode 100644 index 000000000000..a3c51719753d --- /dev/null +++ b/sdk/core/corehttp/tests/test_transport.py @@ -0,0 +1,95 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See LICENSE.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import pytest +from unittest import mock +from socket import timeout as SocketTimeout + +from urllib3.util import connection as urllib_connection +from urllib3.response import HTTPResponse as UrllibResponse +from urllib3.connection import HTTPConnection as UrllibConnection + +from corehttp.rest import HttpRequest +from corehttp.transport.requests import RequestsTransport +from corehttp.runtime.pipeline import Pipeline +from corehttp.exceptions import ServiceResponseError, ServiceResponseTimeoutError, ServiceRequestTimeoutError + + +def test_already_close_with_with(caplog, port): + transport = RequestsTransport() + + request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port)) + + with Pipeline(transport) as pipeline: + pipeline.run(request) + + # This is now closed, new requests should fail + with pytest.raises(ValueError) as err: + transport.send(request) + assert "HTTP transport has already been closed." in str(err) + + +def test_already_close_manually(caplog, port): + transport = RequestsTransport() + + request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port)) + + transport.send(request) + transport.close() + + # This is now closed, new requests should fail + with pytest.raises(ValueError) as err: + transport.send(request) + assert "HTTP transport has already been closed." in str(err) + + +def test_close_too_soon_works_fine(caplog, port): + transport = RequestsTransport() + + request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port)) + + transport.close() # Never opened, should work fine + result = transport.send(request) + + assert result # No exception is good enough here + + +def test_requests_timeout_response(caplog, port): + transport = RequestsTransport() + + request = HttpRequest("GET", f"http://localhost:{port}/basic/string") + + with mock.patch.object(UrllibConnection, "getresponse", side_effect=SocketTimeout) as mock_method: + with pytest.raises(ServiceResponseTimeoutError) as err: + transport.send(request, read_timeout=0.0001) + + with pytest.raises(ServiceResponseError) as err: + transport.send(request, read_timeout=0.0001) + + stream_request = HttpRequest("GET", f"http://localhost:{port}/streams/basic") + with pytest.raises(ServiceResponseTimeoutError) as err: + transport.send(stream_request, stream=True, read_timeout=0.0001) + + stream_resp = transport.send(stream_request, stream=True) + with mock.patch.object(UrllibResponse, "_handle_chunk", side_effect=SocketTimeout) as mock_method: + with pytest.raises(ServiceResponseTimeoutError) as err: + stream_resp.read() + + +def test_requests_timeout_request(caplog, port): + transport = RequestsTransport() + + request = HttpRequest("GET", f"http://localhost:{port}/basic/string") + + with mock.patch.object(urllib_connection, "create_connection", side_effect=SocketTimeout) as mock_method: + with pytest.raises(ServiceRequestTimeoutError) as err: + transport.send(request, connection_timeout=0.0001) + + with pytest.raises(ServiceRequestTimeoutError) as err: + transport.send(request, connection_timeout=0.0001) + + stream_request = HttpRequest("GET", f"http://localhost:{port}/streams/basic") + with pytest.raises(ServiceRequestTimeoutError) as err: + transport.send(stream_request, stream=True, connection_timeout=0.0001) From 5520165075e8ca3ba747d6f0e6fcc07cb350bd2b Mon Sep 17 00:00:00 2001 From: Yuchao Yan Date: Wed, 4 Feb 2026 10:53:09 +0800 Subject: [PATCH 40/84] [resources] update ci.yml (#44953) * update python configuraiton * update ci.yml --- scripts/auto_release/main.py | 9 +++++++++ sdk/resources/ci.yml | 20 +++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/scripts/auto_release/main.py b/scripts/auto_release/main.py index 03ed598dab26..a027b50e34e6 100644 --- a/scripts/auto_release/main.py +++ b/scripts/auto_release/main.py @@ -218,6 +218,15 @@ def check_model_flatten(self): "azure-mgmt-recoveryservicesbackup-passivestamp", "azure-mgmt-certificateregistration", "azure-mgmt-domainregistration", + "azure-mgmt-resource-changes", + "azure-mgmt-resource-databoundaries", + "azure-mgmt-resource-features", + "azure-mgmt-resource-links", + "azure-mgmt-resource-locks", + "azure-mgmt-resource-managedapplications", + "azure-mgmt-resource-policy", + "azure-mgmt-resource-privatelinks", + "azure-mgmt-resource-subscriptions", ]: return if self.from_swagger: diff --git a/sdk/resources/ci.yml b/sdk/resources/ci.yml index cd84447216ed..5a08a24c477f 100644 --- a/sdk/resources/ci.yml +++ b/sdk/resources/ci.yml @@ -44,4 +44,22 @@ extends: - name: azure-mgmt-resource-deploymentscripts safeName: azuremgmtresourcedeploymentscripts - name: azure-mgmt-resource-bicep - safeName: azuremgmtresourcebicep \ No newline at end of file + safeName: azuremgmtresourcebicep + - name: azure-mgmt-resource-changes + safeName: azuremgmtresourcechanges + - name: azure-mgmt-resource-databoundaries + safeName: azuremgmtresourcedataboundaries + - name: azure-mgmt-resource-features + safeName: azuremgmtresourcefeatures + - name: azure-mgmt-resource-links + safeName: azuremgmtresourcelinks + - name: azure-mgmt-resource-locks + safeName: azuremgmtresourcelocks + - name: azure-mgmt-resource-managedapplications + safeName: azuremgmtresourcemanagedapplications + - name: azure-mgmt-resource-policy + safeName: azuremgmtresourcepolicy + - name: azure-mgmt-resource-privatelinks + safeName: azuremgmtresourceprivatelinks + - name: azure-mgmt-resource-subscriptions + safeName: azuremgmtresourcesubscriptions \ No newline at end of file From 2b04197ae4865acaddd43b025ac3e630ef8fdf89 Mon Sep 17 00:00:00 2001 From: Yuchao Yan Date: Wed, 4 Feb 2026 11:11:44 +0800 Subject: [PATCH 41/84] bump typespec-python 0.59.3 (#44992) --- eng/emitter-package-lock.json | 30 +++++++++++++++--------------- eng/emitter-package.json | 4 ++-- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index 1a534f600857..7130d115e197 100644 --- a/eng/emitter-package-lock.json +++ b/eng/emitter-package-lock.json @@ -6,10 +6,10 @@ "": { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.2" + "@azure-tools/typespec-python": "0.59.3" }, "devDependencies": { - "@azure-tools/openai-typespec": "1.7.3", + "@azure-tools/openai-typespec": "1.8.0", "@azure-tools/typespec-autorest": "~0.64.1", "@azure-tools/typespec-azure-core": "~0.64.0", "@azure-tools/typespec-azure-resource-manager": "~0.64.1", @@ -28,9 +28,9 @@ } }, "node_modules/@azure-tools/openai-typespec": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/@azure-tools/openai-typespec/-/openai-typespec-1.7.3.tgz", - "integrity": "sha512-hmbYxVUXI6oYtkTeaXj8LzYZsrh5GQiQiL88YQptFyyBbq75VDA+qnak+7Sk1hxwkZqwy7+WJa8vJqWM3CSRaw==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@azure-tools/openai-typespec/-/openai-typespec-1.8.0.tgz", + "integrity": "sha512-iJRimNIbwqAF6ueYpiL5xY1GJSOA1k3NkqA1NdPlxSJ3bZLP690zR+hHTqEq95HnwqFh2feCDjof9ABtY4keWg==", "dev": true, "license": "MIT", "peerDependencies": { @@ -146,13 +146,13 @@ "dev": true }, "node_modules/@azure-tools/typespec-python": { - "version": "0.59.2", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.2.tgz", - "integrity": "sha512-rt6/YipPeZqTHoJZtE5mzG+FLzAuY+hHSHpudTMaKi8GPlsWlfZcPvb75BfLztvKrrGwEy682i7R1fAmwY7Pqw==", + "version": "0.59.3", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.3.tgz", + "integrity": "sha512-aXnMmKaPz4nhxYLCPyK+DY9GpbcpXn5f56INfcnLpjw0/ukK/NkoVtENBuj6pJ8YO49zCoRXhU1cdwjwP0TMVw==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "@typespec/http-client-python": "~0.26.2", + "@typespec/http-client-python": "~0.26.3", "fs-extra": "~11.2.0", "js-yaml": "~4.1.0", "semver": "~7.6.2", @@ -1079,9 +1079,9 @@ } }, "node_modules/@typespec/http-client-python": { - "version": "0.26.2", - "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.2.tgz", - "integrity": "sha512-bNpjViWsaZER3Z0O/QYgo4OALTDubPuCwuq0iExb8U5AIig/CB4Qsi9zVRtyRfH0ZZ2KJqjlTYaHazrtX4bqLA==", + "version": "0.26.3", + "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.3.tgz", + "integrity": "sha512-LKBi+giSTDbIc1UoAr1+8zGomhes9z68GyIGjxpuN+BxLbdFAUJurDFyDILSJw9rcS8WgYXnVXhHxmP33mqjvw==", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -1467,9 +1467,9 @@ } }, "node_modules/get-tsconfig": { - "version": "4.13.0", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", - "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", + "version": "4.13.1", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.1.tgz", + "integrity": "sha512-EoY1N2xCn44xU6750Sx7OjOIT59FkmstNc3X6y5xpz7D5cBtZRe/3pSlTkDJgqsOk3WwZPkWfonhhUJfttQo3w==", "license": "MIT", "dependencies": { "resolve-pkg-maps": "^1.0.0" diff --git a/eng/emitter-package.json b/eng/emitter-package.json index e16ca6495676..de4ffaf9f7c6 100644 --- a/eng/emitter-package.json +++ b/eng/emitter-package.json @@ -1,7 +1,7 @@ { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.2" + "@azure-tools/typespec-python": "0.59.3" }, "devDependencies": { "@typespec/compiler": "^1.8.0", @@ -13,7 +13,7 @@ "@typespec/sse": "~0.78.0", "@typespec/streams": "~0.78.0", "@typespec/xml": "~0.78.0", - "@azure-tools/openai-typespec": "1.7.3", + "@azure-tools/openai-typespec": "1.8.0", "@azure-tools/typespec-autorest": "~0.64.1", "@azure-tools/typespec-azure-core": "~0.64.0", "@azure-tools/typespec-azure-resource-manager": "~0.64.1", From 5a56514106e453ebc3399776fc1d51c2d7497b69 Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Wed, 4 Feb 2026 09:25:03 -0800 Subject: [PATCH 42/84] Distro release 1.8.6 (#44998) * Distro release 1.8.6 * Add empty line after header --- sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md | 5 ++--- sdk/monitor/azure-monitor-opentelemetry/setup.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md index 9c6f6a521016..235820ac94d0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.8.6 (Unreleased) +## 1.8.6 (2026-02-05) ### Features Added @@ -8,11 +8,10 @@ ([#44902](https://github.com/Azure/azure-sdk-for-python/pull/44902)) ### Breaking Changes + - The default sampling behavior has been changed from ApplicationInsightsSampler with 100% sampling (all traces sampled) to RateLimitedSampler with 5.0 traces per second. This change significantly reduces telemetry volume for high-traffic applications and provides better cost optimization out of the box. Impact: Applications with more than 5 requests per second will see fewer traces exported by default. ([#44925](https://github.com/Azure/azure-sdk-for-python/pull/44925)) -### Bugs Fixed - ### Other Changes - Add missing copyright headers and ensure consistent formatting across files. diff --git a/sdk/monitor/azure-monitor-opentelemetry/setup.py b/sdk/monitor/azure-monitor-opentelemetry/setup.py index feceed9bedbf..13494f9ec99f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/setup.py +++ b/sdk/monitor/azure-monitor-opentelemetry/setup.py @@ -84,7 +84,7 @@ install_requires=[ "azure-core<2.0.0,>=1.28.0", "azure-core-tracing-opentelemetry~=1.0.0b11", - "azure-monitor-opentelemetry-exporter~=1.0.0b46", + "azure-monitor-opentelemetry-exporter~=1.0.0b47", "opentelemetry-sdk==1.39", "opentelemetry-instrumentation-django==0.60b0", "opentelemetry-instrumentation-fastapi==0.60b0", From 3558739a488761afc2bb9c63876511bbb9ddb460 Mon Sep 17 00:00:00 2001 From: Matthew Metcalf Date: Wed, 4 Feb 2026 09:56:24 -0800 Subject: [PATCH 43/84] Fixing Feature Flag Snapshot (#44904) * Fixing Feature Flag Snapshot * Update CHANGELOG.md * Update sdk/appconfiguration/azure-appconfiguration-provider/samples/aad_sample.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Avani Gupta * review comments * mypy fixes * review fixes --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Avani Gupta --- .../CHANGELOG.md | 3 + .../assets.json | 2 +- .../_azureappconfigurationproviderbase.py | 14 +- .../provider/_client_manager.py | 34 +-- .../provider/aio/_async_client_manager.py | 34 ++- .../samples/aad_sample.py | 10 +- .../tests/aio/test_async_snapshots.py | 249 ++++++++++++------ .../tests/asynctestcase.py | 83 ++++++ .../tests/test_snapshots.py | 241 +++++++++++------ .../tests/testcase.py | 82 ++++++ 10 files changed, 556 insertions(+), 196 deletions(-) diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/CHANGELOG.md b/sdk/appconfiguration/azure-appconfiguration-provider/CHANGELOG.md index 134dd91ebb4c..e450321fc92c 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/CHANGELOG.md +++ b/sdk/appconfiguration/azure-appconfiguration-provider/CHANGELOG.md @@ -8,6 +8,9 @@ ### Bugs Fixed +- Fixes a bug where `feature_flag_selects` could be passed in as `None` which resulted in an exception on load, doing this now results in loading the default feature flags. +- Fixes a bug where `feature_flag_selects` couldn't load snapshots. + ### Other Changes ## 2.3.1 (2025-11-13) diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/assets.json b/sdk/appconfiguration/azure-appconfiguration-provider/assets.json index b612cb2b1b0f..5ac650113661 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/assets.json +++ b/sdk/appconfiguration/azure-appconfiguration-provider/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/appconfiguration/azure-appconfiguration-provider", - "Tag": "python/appconfiguration/azure-appconfiguration-provider_3e69808293" + "Tag": "python/appconfiguration/azure-appconfiguration-provider_25357bbd75" } diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_azureappconfigurationproviderbase.py b/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_azureappconfigurationproviderbase.py index d5ff6b58d5cc..7bd2c44344f3 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_azureappconfigurationproviderbase.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_azureappconfigurationproviderbase.py @@ -114,16 +114,6 @@ def process_load_parameters(*args, **kwargs: Any) -> Dict[str, Any]: if kwargs.get("keyvault_credential") is not None and kwargs.get("secret_resolver") is not None: raise ValueError("A keyvault credential and secret resolver can't both be configured.") - # Validate feature flag selectors don't use snapshots - feature_flag_selectors = kwargs.get("feature_flag_selectors") - if feature_flag_selectors: - for selector in feature_flag_selectors: - if hasattr(selector, "snapshot_name") and selector.snapshot_name is not None: - raise ValueError( - "snapshot_name cannot be used with feature_flag_selectors. " - "Use snapshot_name with regular selects instead to load feature flags from snapshots." - ) - # Determine Key Vault usage uses_key_vault = ( "keyvault_credential" in kwargs @@ -230,7 +220,9 @@ def __init__(self, **kwargs: Any) -> None: } self._refresh_timer: _RefreshTimer = _RefreshTimer(**kwargs) self._feature_flag_enabled = kwargs.pop("feature_flag_enabled", False) - self._feature_flag_selectors = kwargs.pop("feature_flag_selectors", [SettingSelector(key_filter="*")]) + self._feature_flag_selectors = kwargs.pop("feature_flag_selectors", None) + if self._feature_flag_selectors is None: + self._feature_flag_selectors = [SettingSelector(key_filter="*")] self._watched_feature_flags: Dict[Tuple[str, str], Optional[str]] = {} self._feature_flag_refresh_timer: _RefreshTimer = _RefreshTimer(**kwargs) self._feature_flag_refresh_enabled = kwargs.pop("feature_flag_refresh_enabled", False) diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_client_manager.py b/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_client_manager.py index d1fa039e474c..ccacbeedba8c 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_client_manager.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/_client_manager.py @@ -137,6 +137,7 @@ def _check_configuration_setting( def load_configuration_settings(self, selects: List[SettingSelector], **kwargs) -> List[ConfigurationSetting]: configuration_settings = [] for select in selects: + configurations = [] if select.snapshot_name is not None: # When loading from a snapshot, ignore key_filter, label_filter, and tag_filters snapshot = self._client.get_snapshot(select.snapshot_name) @@ -162,24 +163,27 @@ def load_configuration_settings(self, selects: List[SettingSelector], **kwargs) def load_feature_flags( self, feature_flag_selectors: List[SettingSelector], **kwargs ) -> List[FeatureFlagConfigurationSetting]: - loaded_feature_flags = [] + loaded_feature_flags: List[FeatureFlagConfigurationSetting] = [] # Needs to be removed unknown keyword argument for list_configuration_settings kwargs.pop("sentinel_keys", None) for select in feature_flag_selectors: - # Handle None key_filter by converting to empty string - key_filter = select.key_filter if select.key_filter is not None else "" - feature_flags = self._client.list_configuration_settings( - key_filter=FEATURE_FLAG_PREFIX + key_filter, - label_filter=select.label_filter, - tags_filter=select.tag_filters, - **kwargs, - ) - for feature_flag in feature_flags: - if not isinstance(feature_flag, FeatureFlagConfigurationSetting): - # If the feature flag is not a FeatureFlagConfigurationSetting, it means it was selected by - # mistake, so we should ignore it. - continue - loaded_feature_flags.append(feature_flag) + feature_flags = [] + if select.snapshot_name is not None: + # When loading from a snapshot, ignore key_filter, label_filter, and tag_filters + snapshot = self._client.get_snapshot(select.snapshot_name) + if snapshot.composition_type != SnapshotComposition.KEY: + raise ValueError(f"Composition type for '{select.snapshot_name}' must be 'key'.") + feature_flags = self._client.list_configuration_settings(snapshot_name=select.snapshot_name, **kwargs) + else: + # Handle None key_filter by converting to empty string + key_filter = select.key_filter if select.key_filter is not None else "" + feature_flags = self._client.list_configuration_settings( + key_filter=FEATURE_FLAG_PREFIX + key_filter, + label_filter=select.label_filter, + tags_filter=select.tag_filters, + **kwargs, + ) + loaded_feature_flags.extend(ff for ff in feature_flags if isinstance(ff, FeatureFlagConfigurationSetting)) return loaded_feature_flags diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/aio/_async_client_manager.py b/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/aio/_async_client_manager.py index 1c75ae885465..424dd8d6ac04 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/aio/_async_client_manager.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/azure/appconfiguration/provider/aio/_async_client_manager.py @@ -10,6 +10,7 @@ from typing import Tuple, Union, Dict, List, Optional, Mapping, TYPE_CHECKING from typing_extensions import Self from azure.core import MatchConditions +from azure.core.async_paging import AsyncItemPaged from azure.core.tracing.decorator import distributed_trace from azure.core.exceptions import HttpResponseError from azure.appconfiguration import ( # type:ignore # pylint:disable=no-name-in-module @@ -164,24 +165,29 @@ async def load_configuration_settings(self, selects: List[SettingSelector], **kw async def load_feature_flags( self, feature_flag_selectors: List[SettingSelector], **kwargs ) -> List[FeatureFlagConfigurationSetting]: - loaded_feature_flags = [] + loaded_feature_flags: List[FeatureFlagConfigurationSetting] = [] # Needs to be removed unknown keyword argument for list_configuration_settings kwargs.pop("sentinel_keys", None) for select in feature_flag_selectors: - # Handle None key_filter by converting to empty string - key_filter = select.key_filter if select.key_filter is not None else "" - feature_flags = self._client.list_configuration_settings( - key_filter=FEATURE_FLAG_PREFIX + key_filter, - label_filter=select.label_filter, - tags_filter=select.tag_filters, - **kwargs, + feature_flags: AsyncItemPaged[ConfigurationSetting] + if select.snapshot_name is not None: + # When loading from a snapshot, ignore key_filter, label_filter, and tag_filters + snapshot = await self._client.get_snapshot(select.snapshot_name) + if snapshot.composition_type != SnapshotComposition.KEY: + raise ValueError(f"Composition type for '{select.snapshot_name}' must be 'key'.") + feature_flags = self._client.list_configuration_settings(snapshot_name=select.snapshot_name, **kwargs) + else: + # Handle None key_filter by converting to empty string + key_filter = select.key_filter if select.key_filter is not None else "" + feature_flags = self._client.list_configuration_settings( + key_filter=FEATURE_FLAG_PREFIX + key_filter, + label_filter=select.label_filter, + tags_filter=select.tag_filters, + **kwargs, + ) + loaded_feature_flags.extend( + [ff async for ff in feature_flags if isinstance(ff, FeatureFlagConfigurationSetting)] ) - async for feature_flag in feature_flags: - if not isinstance(feature_flag, FeatureFlagConfigurationSetting): - # If the feature flag is not a FeatureFlagConfigurationSetting, it means it was selected by - # mistake, so we should ignore it. - continue - loaded_feature_flags.append(feature_flag) return loaded_feature_flags diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/samples/aad_sample.py b/sdk/appconfiguration/azure-appconfiguration-provider/samples/aad_sample.py index 017f9a40930e..2364b6da526a 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/samples/aad_sample.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/samples/aad_sample.py @@ -26,7 +26,15 @@ # Connection to Azure App Configuration using SettingSelector selects = [SettingSelector(key_filter="message*")] -config = load(endpoint=endpoint, credential=credential, selects=selects, **kwargs) +config = load( + endpoint=endpoint, + credential=credential, + selects=selects, + feature_flag_enabled=True, + feature_flag_selectors=None, + **kwargs +) print("message found: " + str("message" in config)) print("test.message found: " + str("test.message" in config)) +print("feature_flag_enabled found: " + str(config.get("feature_management"))) diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/tests/aio/test_async_snapshots.py b/sdk/appconfiguration/azure-appconfiguration-provider/tests/aio/test_async_snapshots.py index 926542d82872..ef39975974b2 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/tests/aio/test_async_snapshots.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/tests/aio/test_async_snapshots.py @@ -7,20 +7,22 @@ import pytest import time from azure.appconfiguration.provider._models import SettingSelector -from azure.appconfiguration.provider._constants import NULL_CHAR +from azure.appconfiguration.provider._constants import NULL_CHAR, FEATURE_MANAGEMENT_KEY, FEATURE_FLAG_KEY from azure.appconfiguration.provider.aio import load from azure.appconfiguration.provider import WatchKey from azure.appconfiguration import ( ConfigurationSetting, - ConfigurationSettingsFilter, - SnapshotComposition, - SnapshotStatus, + FeatureFlagConfigurationSetting, ) from azure.core.exceptions import ResourceNotFoundError -from devtools_testutils import is_live from devtools_testutils.aio import recorded_by_proxy_async from async_preparers import app_config_decorator_async -from asynctestcase import AppConfigTestCase +from asynctestcase import ( + AppConfigTestCase, + cleanup_test_resources_async, + set_test_settings_async, + create_snapshot_async, +) class TestSnapshotSupport: @@ -85,20 +87,6 @@ def test_setting_selector_valid_combinations(self): assert selector.tag_filters == ["env=prod"] assert selector.snapshot_name is None - @pytest.mark.asyncio - async def test_feature_flag_selectors_with_snapshot_raises_error(self): - """Test that feature_flag_selectors with snapshot_name raises ValueError during validation.""" - with pytest.raises( - ValueError, - match=r"snapshot_name cannot be used with feature_flag_selectors\. " - r"Use snapshot_name with regular selects instead to load feature flags from snapshots\.", - ): - await load( - connection_string="Endpoint=test;Id=test;Secret=test", - feature_flag_enabled=True, - feature_flag_selectors=[SettingSelector(snapshot_name="my-snapshot")], - ) - class TestSnapshotProviderIntegration(AppConfigTestCase): """Integration tests for snapshot functionality with recorded tests.""" @@ -156,18 +144,6 @@ async def test_load_provider_with_regular_selectors(self, appconfiguration_conne # Verify we can access the configuration (message is set up by setup_configs) assert "message" in provider - @app_config_decorator_async - @recorded_by_proxy_async - async def test_snapshot_selector_parameter_validation_in_provider(self, appconfiguration_connection_string): - """Test that snapshot selector parameter validation works when loading provider.""" - # Test that feature flag selectors with snapshots are rejected - with pytest.raises(ValueError, match="snapshot_name cannot be used with feature_flag_selectors"): - await self.create_client( - connection_string=appconfiguration_connection_string, - feature_flag_enabled=True, - feature_flag_selectors=[SettingSelector(snapshot_name="test-snapshot")], - ) - @pytest.mark.live_test_only # Needed to fix an azure core dependency compatibility issue @app_config_decorator_async @recorded_by_proxy_async @@ -189,9 +165,23 @@ async def test_create_snapshot_and_load_provider(self, appconfiguration_connecti ConfigurationSetting(key="refresh_test_key", value="original_refresh_value", label=NULL_CHAR), ] - # Set the configuration settings - for setting in test_settings: - await sdk_client.set_configuration_setting(setting) + # Create feature flag settings for the snapshot + # Note: Feature flags in snapshots are NOT loaded as feature flags by the provider + test_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="SnapshotFeature", + enabled=True, + label=NULL_CHAR, + ), + FeatureFlagConfigurationSetting( + feature_id="SnapshotFeatureDisabled", + enabled=False, + label=NULL_CHAR, + ), + ] + + # Set the configuration settings and feature flags + await set_test_settings_async(sdk_client, test_settings + test_feature_flags) variables = kwargs.pop("variables", {}) dynamic_snapshot_name_postfix = variables.setdefault("dynamic_snapshot_name_postfix", str(int(time.time()))) @@ -200,28 +190,18 @@ async def test_create_snapshot_and_load_provider(self, appconfiguration_connecti snapshot_name = f"test-snapshot-{dynamic_snapshot_name_postfix}" try: - # Create the snapshot - snapshot_poller = await sdk_client.begin_create_snapshot( - name=snapshot_name, - filters=[ConfigurationSettingsFilter(key="snapshot_test_*")], # Include all our test keys - composition_type=SnapshotComposition.KEY, - retention_period=3600, # Min valid value is 1 hour + # Create the snapshot including both config settings and feature flags + await create_snapshot_async( + sdk_client, + snapshot_name, + key_filters=["snapshot_test_*", ".appconfig.featureflag/SnapshotFeature*"], ) - snapshot = await snapshot_poller.result() - - # Verify snapshot was created successfully - if is_live(): - assert snapshot.name == snapshot_name - else: - assert snapshot.name == "Sanitized" - assert snapshot.status == SnapshotStatus.READY - assert snapshot.composition_type == SnapshotComposition.KEY - # Load provider using the snapshot with refresh enabled + # Load provider using the snapshot with refresh enabled and feature flags enabled async with await self.create_client( connection_string=appconfiguration_connection_string, selects=[ - SettingSelector(snapshot_name=snapshot_name), # Snapshot data + SettingSelector(snapshot_name=snapshot_name), # Snapshot data (includes feature flags) SettingSelector(key_filter="refresh_test_key"), # Non-snapshot key for refresh testing ], refresh_on=[WatchKey("refresh_test_key")], # Watch non-snapshot key for refresh @@ -238,6 +218,10 @@ async def test_create_snapshot_and_load_provider(self, appconfiguration_connecti snapshot_keys = [key for key in provider.keys() if key.startswith("snapshot_test_")] assert len(snapshot_keys) == 3 + # Verify feature flags from snapshots are NOT loaded as feature flags + # (snapshots don't support feature flag loading, only regular selects do) + assert FEATURE_MANAGEMENT_KEY not in provider, "Feature flags should not be loaded from snapshots" + # Test snapshot immutability: modify the original settings modified_settings = [ ConfigurationSetting( @@ -259,13 +243,9 @@ async def test_create_snapshot_and_load_provider(self, appconfiguration_connecti ), ] - # Update the original settings with new values - for setting in modified_settings: - await sdk_client.set_configuration_setting(setting) - - # Add a completely new key after initial load + # Update the original settings with new values and add a new key new_key = ConfigurationSetting(key="new_key_added_after_load", value="new_value", label=NULL_CHAR) - await sdk_client.set_configuration_setting(new_key) + await set_test_settings_async(sdk_client, modified_settings + [new_key]) # Wait for refresh interval to pass time.sleep(1) @@ -296,23 +276,138 @@ async def test_create_snapshot_and_load_provider(self, appconfiguration_connecti assert provider_current["snapshot_test_json"]["nested"] == "MODIFIED_VALUE" # Modified value finally: - # Clean up: delete the snapshot and test settings - try: - # Archive the snapshot (delete is not supported, but archive effectively removes it) - await sdk_client.archive_snapshot(snapshot_name) - except Exception: - pass - - # Clean up test settings - for setting in test_settings: - try: - await sdk_client.delete_configuration_setting(key=setting.key, label=setting.label) - except Exception: - pass - - # Clean up additional test keys - try: - await sdk_client.delete_configuration_setting(key="new_key_added_after_load", label=NULL_CHAR) - except Exception: - pass + # Clean up test resources + cleanup_settings = ( + test_settings + + test_feature_flags + + [ConfigurationSetting(key="new_key_added_after_load", value="", label=NULL_CHAR)] + ) + await cleanup_test_resources_async( + sdk_client, + settings=cleanup_settings, + snapshot_names=[snapshot_name], + ) + return variables + + @pytest.mark.live_test_only # Needed to fix an azure core dependency compatibility issue + @app_config_decorator_async + @recorded_by_proxy_async + async def test_create_snapshot_and_load_provider_with_feature_flags( + self, appconfiguration_connection_string, **kwargs + ): + """Test creating a snapshot and loading provider with feature flags from non-snapshot selectors.""" + # Create SDK client for setup + sdk_client = self.create_sdk_client(appconfiguration_connection_string) + + # Create unique test configuration settings for the snapshot + test_settings = [ + ConfigurationSetting(key="ff_snapshot_test_key1", value="ff_snapshot_test_value1", label=NULL_CHAR), + ConfigurationSetting(key="ff_snapshot_test_key2", value="ff_snapshot_test_value2", label=NULL_CHAR), + ] + + # Create feature flag settings - some for snapshot, some for regular loading + # Note: Feature flags in snapshots are NOT loaded as feature flags by the provider + snapshot_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="SnapshotOnlyFeature", + enabled=True, + label=NULL_CHAR, + ), + ] + + # Feature flags loaded via regular selectors (not from snapshot) + regular_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="RegularFeature", + enabled=True, + label=NULL_CHAR, + ), + FeatureFlagConfigurationSetting( + feature_id="RegularFeatureDisabled", + enabled=False, + label=NULL_CHAR, + ), + ] + + # Set the configuration settings and feature flags + await set_test_settings_async(sdk_client, test_settings + snapshot_feature_flags + regular_feature_flags) + + variables = kwargs.pop("variables", {}) + dynamic_snapshot_name_postfix = variables.setdefault("dynamic_ff_snapshot_name_postfix", str(int(time.time()))) + + # Create a unique snapshot name with timestamp to avoid conflicts + snapshot_name = f"test-ff-snapshot-{dynamic_snapshot_name_postfix}" + + try: + # Create the snapshot including config settings and snapshot-only feature flags + await create_snapshot_async( + sdk_client, + snapshot_name, + key_filters=["ff_snapshot_test_*", ".appconfig.featureflag/SnapshotOnlyFeature"], + ) + + # Load provider using snapshot for config settings and regular selectors for feature flags + async with await self.create_client( + connection_string=appconfiguration_connection_string, + feature_flag_enabled=True, # Enable feature flags + feature_flag_selectors=[ + SettingSelector(snapshot_name=snapshot_name), # Load feature flags from snapshot + ], + ) as provider: + + # Verify snapshot configuration settings are loaded + assert provider["ff_snapshot_test_key1"] == "ff_snapshot_test_value1" + assert provider["ff_snapshot_test_key2"] == "ff_snapshot_test_value2" + + # Verify feature flags loaded via regular selectors ARE loaded + feature_flags = provider.get(FEATURE_MANAGEMENT_KEY, {}).get(FEATURE_FLAG_KEY, []) + feature_flag_ids = {ff["id"]: ff["enabled"] for ff in feature_flags} + + # Regular feature flags should be loaded + assert ( + "RegularFeature" not in feature_flag_ids + ), "RegularFeature should not be loaded via regular selector" + assert "RegularFeatureDisabled" not in feature_flag_ids, "RegularFeatureDisabled should not be loaded" + + # Snapshot-only feature flag should be loaded as a feature flag + assert ( + "SnapshotOnlyFeature" in feature_flag_ids + ), "SnapshotOnlyFeature should be loaded as FF from snapshot" + + # Verify exactly 1 feature flag is loaded (the snapshot-only one) + assert len(feature_flags) == 1, f"Expected 1 feature flag, got {len(feature_flags)}" + + # Modify the feature flags in the snapshot + modified_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="SnapshotOnlyFeature", + enabled=False, # Changed from True to False + label=NULL_CHAR, + ), + ] + + await set_test_settings_async(sdk_client, modified_feature_flags) + + # Load a fresh provider without snapshot to verify current feature flag values + async with await self.create_client( + connection_string=appconfiguration_connection_string, + feature_flag_enabled=True, + feature_flag_selectors=[ + SettingSelector(snapshot_name=snapshot_name), # Load feature flags from snapshot + ], + ) as provider_current: + + # Current feature flag values should be the original ones from snapshot (immutable) + current_feature_flags = provider_current.get(FEATURE_MANAGEMENT_KEY, {}).get(FEATURE_FLAG_KEY, []) + current_ff_ids = {ff["id"]: ff["enabled"] for ff in current_feature_flags} + assert current_ff_ids.get("SnapshotOnlyFeature") is True # Original value from snapshot (not modified) + + finally: + # Clean up test resources + cleanup_settings = test_settings + snapshot_feature_flags + regular_feature_flags + await cleanup_test_resources_async( + sdk_client, + settings=cleanup_settings, + snapshot_names=[snapshot_name], + ) return variables diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/tests/asynctestcase.py b/sdk/appconfiguration/azure-appconfiguration-provider/tests/asynctestcase.py index bdab2e0670f2..fe9e9878256c 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/tests/asynctestcase.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/tests/asynctestcase.py @@ -53,3 +53,86 @@ async def setup_configs(client, keyvault_secret_url, keyvault_secret_url2): async with client: for config in get_configs(keyvault_secret_url, keyvault_secret_url2): await client.set_configuration_setting(config) + + +async def cleanup_test_resources_async( + client, + settings=None, + snapshot_names=None, +): + """ + Clean up test resources from Azure App Configuration (async version). + + :param client: The async AzureAppConfigurationClient to use for cleanup. + :param settings: List of ConfigurationSetting objects to delete. + :param snapshot_names: List of snapshot names to archive. + """ + # Archive snapshots + if snapshot_names: + for snapshot_name in snapshot_names: + try: + await client.archive_snapshot(snapshot_name) + except Exception: + pass + + # Delete configuration settings and feature flags + if settings: + for setting in settings: + try: + await client.delete_configuration_setting(key=setting.key, label=setting.label) + except Exception: + pass + + +async def set_test_settings_async(client, settings): + """ + Set multiple configuration settings in Azure App Configuration (async version). + + :param client: The async AzureAppConfigurationClient to use. + :param settings: List of ConfigurationSetting or FeatureFlagConfigurationSetting objects to set. + """ + for setting in settings: + await client.set_configuration_setting(setting) + + +async def create_snapshot_async(client, snapshot_name, key_filters, composition_type=None, retention_period=3600): + """ + Create a snapshot in Azure App Configuration and verify it was created successfully (async version). + + :param client: The async AzureAppConfigurationClient to use. + :param snapshot_name: The name of the snapshot to create. + :param key_filters: List of key filter strings to define what settings to include. + :param composition_type: The composition type for the snapshot (default: SnapshotComposition.KEY). + :param retention_period: The retention period in seconds (default: 3600, minimum valid value). + :return: The created snapshot. + """ + from azure.appconfiguration import SnapshotComposition, ConfigurationSettingsFilter, SnapshotStatus + from devtools_testutils import is_live + + if composition_type is None: + composition_type = SnapshotComposition.KEY + + # Convert key filter strings to ConfigurationSettingsFilter objects + filters = [ConfigurationSettingsFilter(key=key_filter) for key_filter in key_filters] + + snapshot_poller = await client.begin_create_snapshot( + name=snapshot_name, + filters=filters, + composition_type=composition_type, + retention_period=retention_period, + ) + snapshot = await snapshot_poller.result() + + # Verify snapshot was created successfully + assert snapshot.status == SnapshotStatus.READY, f"Snapshot status is {snapshot.status}, expected READY" + assert ( + snapshot.composition_type == composition_type + ), f"Snapshot composition_type is {snapshot.composition_type}, expected {composition_type}" + + # Verify snapshot name (sanitized in playback mode) + if is_live(): + assert snapshot.name == snapshot_name, f"Snapshot name is {snapshot.name}, expected {snapshot_name}" + else: + assert snapshot.name == "Sanitized", f"Snapshot name is {snapshot.name}, expected 'Sanitized' in playback" + + return snapshot diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/tests/test_snapshots.py b/sdk/appconfiguration/azure-appconfiguration-provider/tests/test_snapshots.py index 3a31c3ac874c..9e72a99b793e 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/tests/test_snapshots.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/tests/test_snapshots.py @@ -7,18 +7,16 @@ import pytest import time from azure.appconfiguration.provider._models import SettingSelector -from azure.appconfiguration.provider._constants import NULL_CHAR +from azure.appconfiguration.provider._constants import NULL_CHAR, FEATURE_MANAGEMENT_KEY, FEATURE_FLAG_KEY from azure.appconfiguration.provider import load, WatchKey from azure.appconfiguration import ( ConfigurationSetting, - ConfigurationSettingsFilter, - SnapshotComposition, - SnapshotStatus, + FeatureFlagConfigurationSetting, ) from azure.core.exceptions import ResourceNotFoundError -from devtools_testutils import recorded_by_proxy, is_live +from devtools_testutils import recorded_by_proxy from preparers import app_config_decorator -from testcase import AppConfigTestCase +from testcase import AppConfigTestCase, cleanup_test_resources, set_test_settings, create_snapshot class TestSnapshotSupport: @@ -83,19 +81,6 @@ def test_setting_selector_valid_combinations(self): assert selector.tag_filters == ["env=prod"] assert selector.snapshot_name is None - def test_feature_flag_selectors_with_snapshot_raises_error(self): - """Test that feature_flag_selectors with snapshot_name raises ValueError during validation.""" - with pytest.raises( - ValueError, - match=r"snapshot_name cannot be used with feature_flag_selectors\. " - r"Use snapshot_name with regular selects instead to load feature flags from snapshots\.", - ): - load( - connection_string="Endpoint=test;Id=test;Secret=test", - feature_flag_enabled=True, - feature_flag_selectors=[SettingSelector(snapshot_name="my-snapshot")], - ) - class TestSnapshotProviderIntegration(AppConfigTestCase): """Integration tests for snapshot functionality with recorded tests.""" @@ -154,18 +139,6 @@ def test_load_provider_with_regular_selectors(self, appconfiguration_connection_ # Verify we can access the configuration (message is set up by setup_configs) assert "message" in provider - @app_config_decorator - @recorded_by_proxy - def test_snapshot_selector_parameter_validation_in_provider(self, appconfiguration_connection_string): - """Test that snapshot selector parameter validation works when loading provider.""" - # Test that feature flag selectors with snapshots are rejected - with pytest.raises(ValueError, match="snapshot_name cannot be used with feature_flag_selectors"): - self.create_client( - connection_string=appconfiguration_connection_string, - feature_flag_enabled=True, - feature_flag_selectors=[SettingSelector(snapshot_name="test-snapshot")], - ) - @pytest.mark.live_test_only # Needed to fix an azure core dependency compatibility issue @app_config_decorator @recorded_by_proxy @@ -187,9 +160,23 @@ def test_create_snapshot_and_load_provider(self, appconfiguration_connection_str ConfigurationSetting(key="refresh_test_key", value="original_refresh_value", label=NULL_CHAR), ] - # Set the configuration settings - for setting in test_settings: - sdk_client.set_configuration_setting(setting) + # Create feature flag settings for the snapshot + # Note: Feature flags in snapshots are NOT loaded as feature flags by the provider + test_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="SnapshotFeature", + enabled=True, + label=NULL_CHAR, + ), + FeatureFlagConfigurationSetting( + feature_id="SnapshotFeatureDisabled", + enabled=False, + label=NULL_CHAR, + ), + ] + + # Set the configuration settings and feature flags + set_test_settings(sdk_client, test_settings + test_feature_flags) variables = kwargs.pop("variables", {}) dynamic_snapshot_name_postfix = variables.setdefault("dynamic_snapshot_name_postfix", str(int(time.time()))) @@ -198,27 +185,18 @@ def test_create_snapshot_and_load_provider(self, appconfiguration_connection_str snapshot_name = f"test-snapshot-{dynamic_snapshot_name_postfix}" try: - # Create the snapshot - snapshot = sdk_client.begin_create_snapshot( - name=snapshot_name, - filters=[ConfigurationSettingsFilter(key="snapshot_test_*")], # Include all our test keys - composition_type=SnapshotComposition.KEY, - retention_period=3600, # Min valid value is 1 hour - ).result() - - # Verify snapshot was created successfully - if is_live(): - assert snapshot.name == snapshot_name - else: - assert snapshot.name == "Sanitized" - assert snapshot.status == SnapshotStatus.READY - assert snapshot.composition_type == SnapshotComposition.KEY - - # Load provider using the snapshot with refresh enabled + # Create the snapshot including both config settings and feature flags + create_snapshot( + sdk_client, + snapshot_name, + key_filters=["snapshot_test_*", ".appconfig.featureflag/SnapshotFeature*"], + ) + + # Load provider using the snapshot with refresh enabled and feature flags enabled provider = self.create_client( connection_string=appconfiguration_connection_string, selects=[ - SettingSelector(snapshot_name=snapshot_name), # Snapshot data + SettingSelector(snapshot_name=snapshot_name), # Snapshot data (includes feature flags) SettingSelector(key_filter="refresh_test_key"), # Non-snapshot key for refresh testing ], refresh_on=[WatchKey("refresh_test_key")], # Watch non-snapshot key for refresh @@ -235,6 +213,10 @@ def test_create_snapshot_and_load_provider(self, appconfiguration_connection_str snapshot_keys = [key for key in provider.keys() if key.startswith("snapshot_test_")] assert len(snapshot_keys) == 3 + # Verify feature flags from snapshots are NOT loaded as feature flags + # (snapshots don't support feature flag loading, only regular selects do) + assert FEATURE_MANAGEMENT_KEY not in provider, "Feature flags should not be loaded from snapshots" + # Test snapshot immutability: modify the original settings modified_settings = [ ConfigurationSetting( @@ -256,13 +238,9 @@ def test_create_snapshot_and_load_provider(self, appconfiguration_connection_str ), ] - # Update the original settings with new values - for setting in modified_settings: - sdk_client.set_configuration_setting(setting) - - # Add a completely new key after initial load + # Update the original settings with new values and add a new key new_key = ConfigurationSetting(key="new_key_added_after_load", value="new_value", label=NULL_CHAR) - sdk_client.set_configuration_setting(new_key) + set_test_settings(sdk_client, modified_settings + [new_key]) # Wait for refresh interval to pass time.sleep(1) @@ -293,23 +271,132 @@ def test_create_snapshot_and_load_provider(self, appconfiguration_connection_str assert provider_current["snapshot_test_json"]["nested"] == "MODIFIED_VALUE" # Modified value finally: - # Clean up: delete the snapshot and test settings - try: - # Archive the snapshot (delete is not supported, but archive effectively removes it) - sdk_client.archive_snapshot(snapshot_name) - except Exception: - pass - - # Clean up test settings - for setting in test_settings: - try: - sdk_client.delete_configuration_setting(key=setting.key, label=setting.label) - except Exception: - pass - - # Clean up additional test keys - try: - sdk_client.delete_configuration_setting(key="new_key_added_after_load", label=NULL_CHAR) - except Exception: - pass + # Clean up test resources + cleanup_settings = ( + test_settings + + test_feature_flags + + [ConfigurationSetting(key="new_key_added_after_load", value="", label=NULL_CHAR)] + ) + cleanup_test_resources( + sdk_client, + settings=cleanup_settings, + snapshot_names=[snapshot_name], + ) + return variables + + @pytest.mark.live_test_only # Needed to fix an azure core dependency compatibility issue + @app_config_decorator + @recorded_by_proxy + def test_create_snapshot_and_load_provider_with_feature_flags(self, appconfiguration_connection_string, **kwargs): + """Test creating a snapshot and loading provider with feature flags from non-snapshot selectors.""" + # Create SDK client for setup + sdk_client = self.create_sdk_client(appconfiguration_connection_string) + + # Create unique test configuration settings for the snapshot + test_settings = [ + ConfigurationSetting(key="ff_snapshot_test_key1", value="ff_snapshot_test_value1", label=NULL_CHAR), + ConfigurationSetting(key="ff_snapshot_test_key2", value="ff_snapshot_test_value2", label=NULL_CHAR), + ] + + # Create feature flag settings - some for snapshot, some for regular loading + # Note: Feature flags in snapshots are NOT loaded as feature flags by the provider + snapshot_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="SnapshotOnlyFeature", + enabled=True, + label=NULL_CHAR, + ), + ] + + # Feature flags loaded via regular selectors (not from snapshot) + regular_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="RegularFeature", + enabled=True, + label=NULL_CHAR, + ), + FeatureFlagConfigurationSetting( + feature_id="RegularFeatureDisabled", + enabled=False, + label=NULL_CHAR, + ), + ] + + # Set the configuration settings and feature flags + set_test_settings(sdk_client, test_settings + snapshot_feature_flags + regular_feature_flags) + + variables = kwargs.pop("variables", {}) + dynamic_snapshot_name_postfix = variables.setdefault("dynamic_ff_snapshot_name_postfix", str(int(time.time()))) + + # Create a unique snapshot name with timestamp to avoid conflicts + snapshot_name = f"test-ff-snapshot-{dynamic_snapshot_name_postfix}" + + try: + # Create the snapshot including config settings and snapshot-only feature flags + create_snapshot( + sdk_client, + snapshot_name, + key_filters=["ff_snapshot_test_*", ".appconfig.featureflag/SnapshotOnlyFeature"], + ) + + # Load provider using snapshot for config settings and regular selectors for feature flags + provider = self.create_client( + connection_string=appconfiguration_connection_string, + feature_flag_enabled=True, # Enable feature flags + feature_flag_selectors=[ + SettingSelector(snapshot_name=snapshot_name), # Load feature flags from snapshot + ], + ) + + # Verify snapshot configuration settings are loaded + assert provider["ff_snapshot_test_key1"] == "ff_snapshot_test_value1" + assert provider["ff_snapshot_test_key2"] == "ff_snapshot_test_value2" + + # Verify feature flags loaded via regular selectors ARE loaded + feature_flags = provider.get(FEATURE_MANAGEMENT_KEY, {}).get(FEATURE_FLAG_KEY, []) + feature_flag_ids = {ff["id"]: ff["enabled"] for ff in feature_flags} + + # Regular feature flags should be loaded + assert "RegularFeature" not in feature_flag_ids, "RegularFeature should not be loaded via regular selector" + assert "RegularFeatureDisabled" not in feature_flag_ids, "RegularFeatureDisabled should not be loaded" + + # Snapshot-only feature flag should be loaded as a feature flag + assert "SnapshotOnlyFeature" in feature_flag_ids, "SnapshotOnlyFeature should be loaded as FF from snapshot" + + # Verify exactly 1 feature flag is loaded (the snapshot-only one) + assert len(feature_flags) == 1, f"Expected 1 feature flag, got {len(feature_flags)}" + + # Modify the feature flags in the snapshot + modified_feature_flags = [ + FeatureFlagConfigurationSetting( + feature_id="SnapshotOnlyFeature", + enabled=False, # Changed from True to False + label=NULL_CHAR, + ), + ] + + set_test_settings(sdk_client, modified_feature_flags) + + # Load a fresh provider without snapshot to verify current feature flag values + provider_current = self.create_client( + connection_string=appconfiguration_connection_string, + feature_flag_enabled=True, + feature_flag_selectors=[ + SettingSelector(snapshot_name=snapshot_name), # Load feature flags from snapshot + ], + ) + + # Current feature flag values should be the original ones from snapshot (immutable) + current_feature_flags = provider_current.get(FEATURE_MANAGEMENT_KEY, {}).get(FEATURE_FLAG_KEY, []) + current_ff_ids = {ff["id"]: ff["enabled"] for ff in current_feature_flags} + assert current_ff_ids.get("SnapshotOnlyFeature") is True # Original value from snapshot (not modified) + + finally: + # Clean up test resources + cleanup_settings = test_settings + snapshot_feature_flags + regular_feature_flags + cleanup_test_resources( + sdk_client, + settings=cleanup_settings, + snapshot_names=[snapshot_name], + ) return variables diff --git a/sdk/appconfiguration/azure-appconfiguration-provider/tests/testcase.py b/sdk/appconfiguration/azure-appconfiguration-provider/tests/testcase.py index 67451060f4f5..5863b13756e1 100644 --- a/sdk/appconfiguration/azure-appconfiguration-provider/tests/testcase.py +++ b/sdk/appconfiguration/azure-appconfiguration-provider/tests/testcase.py @@ -140,6 +140,88 @@ def create_feature_flag_config_setting(key, label, enabled, tags=None): return FeatureFlagConfigurationSetting(feature_id=key, label=label, enabled=enabled, tags=tags) +def cleanup_test_resources( + client, + settings=None, + snapshot_names=None, +): + """ + Clean up test resources from Azure App Configuration. + + :param client: The AzureAppConfigurationClient to use for cleanup. + :param settings: List of ConfigurationSetting objects to delete. + :param snapshot_names: List of snapshot names to archive. + """ + # Archive snapshots + if snapshot_names: + for snapshot_name in snapshot_names: + try: + client.archive_snapshot(snapshot_name) + except Exception: + pass + + # Delete configuration settings and feature flags + if settings: + for setting in settings: + try: + client.delete_configuration_setting(key=setting.key, label=setting.label) + except Exception: + pass + + +def set_test_settings(client, settings): + """ + Set multiple configuration settings in Azure App Configuration. + + :param client: The AzureAppConfigurationClient to use. + :param settings: List of ConfigurationSetting or FeatureFlagConfigurationSetting objects to set. + """ + for setting in settings: + client.set_configuration_setting(setting) + + +def create_snapshot(client, snapshot_name, key_filters, composition_type=None, retention_period=3600): + """ + Create a snapshot in Azure App Configuration and verify it was created successfully. + + :param client: The AzureAppConfigurationClient to use. + :param snapshot_name: The name of the snapshot to create. + :param key_filters: List of key filter strings to define what settings to include. + :param composition_type: The composition type for the snapshot (default: SnapshotComposition.KEY). + :param retention_period: The retention period in seconds (default: 3600, minimum valid value). + :return: The created snapshot. + """ + from azure.appconfiguration import SnapshotComposition, ConfigurationSettingsFilter, SnapshotStatus + from devtools_testutils import is_live + + if composition_type is None: + composition_type = SnapshotComposition.KEY + + # Convert key filter strings to ConfigurationSettingsFilter objects + filters = [ConfigurationSettingsFilter(key=key_filter) for key_filter in key_filters] + + snapshot = client.begin_create_snapshot( + name=snapshot_name, + filters=filters, + composition_type=composition_type, + retention_period=retention_period, + ).result() + + # Verify snapshot was created successfully + assert snapshot.status == SnapshotStatus.READY, f"Snapshot status is {snapshot.status}, expected READY" + assert ( + snapshot.composition_type == composition_type + ), f"Snapshot composition_type is {snapshot.composition_type}, expected {composition_type}" + + # Verify snapshot name (sanitized in playback mode) + if is_live(): + assert snapshot.name == snapshot_name, f"Snapshot name is {snapshot.name}, expected {snapshot_name}" + else: + assert snapshot.name == "Sanitized", f"Snapshot name is {snapshot.name}, expected 'Sanitized' in playback" + + return snapshot + + def get_feature_flag(client, feature_id): for feature_flag in client[FEATURE_MANAGEMENT_KEY][FEATURE_FLAG_KEY]: if feature_flag["id"] == feature_id: From ebbe47c61851cb13556ce4cb487f9bbf750c2edc Mon Sep 17 00:00:00 2001 From: Sydney Lister <103153180+slister1001@users.noreply.github.com> Date: Wed, 4 Feb 2026 12:57:59 -0500 Subject: [PATCH 44/84] Fix AAD authentication in ACA environments for RedTeam (#44938) When running red team scans in ACA environments, DefaultAzureCredential fails because Azure CLI is not available. This fix allows passing an explicit credential from the RedTeam instance to get_chat_target(). Changes: - Add credential parameter to get_chat_target() function - Add _create_token_provider() helper to create callable from credential - Pass self.credential from RedTeam.scan() to get_chat_target() - Add credential field to AzureOpenAIModelConfiguration TypedDict - Add tests for credential-based authentication paths Auth priority: api_key > credential > use_aad_auth (DefaultAzureCredential) --- .../azure/ai/evaluation/red_team/_red_team.py | 73 +++++++-- .../red_team/_utils/strategy_utils.py | 43 ++++-- .../test_redteam/test_strategy_utils.py | 142 +++++++++++++++++- 3 files changed, 227 insertions(+), 31 deletions(-) diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_red_team.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_red_team.py index 704ee535024f..aff8b174d879 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_red_team.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_red_team.py @@ -24,7 +24,9 @@ ) # TODO: uncomment when app insights checked in from azure.ai.evaluation._model_configurations import EvaluationResult from azure.ai.evaluation.simulator._model_tools import ManagedIdentityAPITokenManager -from azure.ai.evaluation.simulator._model_tools._generated_rai_client import GeneratedRAIClient +from azure.ai.evaluation.simulator._model_tools._generated_rai_client import ( + GeneratedRAIClient, +) from azure.ai.evaluation._user_agent import UserAgentSingleton from azure.ai.evaluation._model_configurations import ( AzureOpenAIModelConfiguration, @@ -59,7 +61,11 @@ from pyrit.prompt_target import PromptChatTarget # Local imports - constants and utilities -from ._utils.constants import TASK_STATUS, MAX_SAMPLING_ITERATIONS_MULTIPLIER, RISK_TO_NUM_SUBTYPE_MAP +from ._utils.constants import ( + TASK_STATUS, + MAX_SAMPLING_ITERATIONS_MULTIPLIER, + RISK_TO_NUM_SUBTYPE_MAP, +) from ._utils.logging_utils import ( setup_logger, log_section_header, @@ -205,7 +211,8 @@ def __init__( # Initialize RAI client self.generated_rai_client = GeneratedRAIClient( - azure_ai_project=self.azure_ai_project, token_manager=self.token_manager.credential + azure_ai_project=self.azure_ai_project, + token_manager=self.token_manager.credential, ) # Initialize a cache for attack objectives by risk category and strategy @@ -386,7 +393,12 @@ async def _get_attack_objectives( if custom_objectives: # Use custom objectives for this risk category return await self._get_custom_attack_objectives( - risk_cat_value, num_objectives, num_objectives_with_subtypes, strategy, current_key, is_agent_target + risk_cat_value, + num_objectives, + num_objectives_with_subtypes, + strategy, + current_key, + is_agent_target, ) else: # No custom objectives for this risk category, but risk_categories was specified @@ -574,7 +586,13 @@ async def _get_custom_attack_objectives( self.prompt_to_risk_subtype[content] = risk_subtype # Store in cache and return - self._cache_attack_objectives(current_key, risk_cat_value, strategy, selected_prompts, selected_cat_objectives) + self._cache_attack_objectives( + current_key, + risk_cat_value, + strategy, + selected_prompts, + selected_cat_objectives, + ) return selected_prompts async def _get_rai_attack_objectives( @@ -680,12 +698,22 @@ async def _get_rai_attack_objectives( # Filter and select objectives using num_objectives_with_subtypes selected_cat_objectives = self._filter_and_select_objectives( - objectives_response, strategy, baseline_objectives_exist, baseline_key, num_objectives_with_subtypes + objectives_response, + strategy, + baseline_objectives_exist, + baseline_key, + num_objectives_with_subtypes, ) # Extract content and cache selected_prompts = self._extract_objective_content(selected_cat_objectives) - self._cache_attack_objectives(current_key, risk_cat_value, strategy, selected_prompts, selected_cat_objectives) + self._cache_attack_objectives( + current_key, + risk_cat_value, + strategy, + selected_prompts, + selected_cat_objectives, + ) return selected_prompts @@ -820,7 +848,11 @@ async def get_xpia_prompts_with_retry(): # Build the contexts list: XPIA context + any baseline contexts with agent fields contexts = [ - {"content": formatted_context, "context_type": context_type, "tool_name": tool_name} + { + "content": formatted_context, + "context_type": context_type, + "tool_name": tool_name, + } ] # Add baseline contexts with agent fields as separate context entries @@ -1362,10 +1394,13 @@ async def scan( # Fetch attack objectives all_objectives = await self._fetch_all_objectives( - flattened_attack_strategies, application_scenario, is_agent_target, client_id + flattened_attack_strategies, + application_scenario, + is_agent_target, + client_id, ) - chat_target = get_chat_target(target) + chat_target = get_chat_target(target, credential=self.credential) self.chat_target = chat_target # Execute attacks @@ -1481,7 +1516,10 @@ async def _fetch_all_objectives( # Calculate and log num_objectives_with_subtypes once globally num_objectives = self.attack_objective_generator.num_objectives - max_num_subtypes = max((RISK_TO_NUM_SUBTYPE_MAP.get(rc, 0) for rc in self.risk_categories), default=0) + max_num_subtypes = max( + (RISK_TO_NUM_SUBTYPE_MAP.get(rc, 0) for rc in self.risk_categories), + default=0, + ) num_objectives_with_subtypes = max(num_objectives, max_num_subtypes) if num_objectives_with_subtypes != num_objectives: @@ -1594,7 +1632,11 @@ async def _execute_attacks( progress_bar.close() async def _process_orchestrator_tasks( - self, orchestrator_tasks: List, parallel_execution: bool, max_parallel_tasks: int, timeout: int + self, + orchestrator_tasks: List, + parallel_execution: bool, + max_parallel_tasks: int, + timeout: int, ): """Process orchestrator tasks either in parallel or sequentially.""" if parallel_execution and orchestrator_tasks: @@ -1629,7 +1671,12 @@ async def _process_orchestrator_tasks( continue async def _finalize_results( - self, skip_upload: bool, skip_evals: bool, eval_run, output_path: str, scan_name: str + self, + skip_upload: bool, + skip_evals: bool, + eval_run, + output_path: str, + scan_name: str, ) -> RedTeamResult: """Process and finalize scan results.""" log_section_header(self.logger, "Processing results") diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/strategy_utils.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/strategy_utils.py index 26455d3031f7..ce789b6d2770 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/strategy_utils.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/red_team/_utils/strategy_utils.py @@ -6,7 +6,9 @@ from typing import Dict, List, Union, Optional, Any, Callable, cast import logging -from azure.ai.evaluation.simulator._model_tools._generated_rai_client import GeneratedRAIClient +from azure.ai.evaluation.simulator._model_tools._generated_rai_client import ( + GeneratedRAIClient, +) from .._attack_strategy import AttackStrategy from pyrit.prompt_converter import ( PromptConverter, @@ -35,8 +37,10 @@ from .._default_converter import _DefaultConverter from pyrit.prompt_target import OpenAIChatTarget, PromptChatTarget from .._callback_chat_target import _CallbackChatTarget -from azure.ai.evaluation._model_configurations import AzureOpenAIModelConfiguration, OpenAIModelConfiguration - +from azure.ai.evaluation._model_configurations import ( + AzureOpenAIModelConfiguration, + OpenAIModelConfiguration, +) # Azure OpenAI uses cognitive services scope for AAD authentication AZURE_OPENAI_SCOPE = "https://cognitiveservices.azure.com/.default" @@ -65,7 +69,9 @@ def get_token() -> str: def create_tense_converter( - generated_rai_client: GeneratedRAIClient, is_one_dp_project: bool, logger: logging.Logger + generated_rai_client: GeneratedRAIClient, + is_one_dp_project: bool, + logger: logging.Logger, ) -> TenseConverter: """Factory function for creating TenseConverter with proper dependencies.""" converter_target = AzureRAIServiceTarget( @@ -141,12 +147,22 @@ def _resolve_converter(strategy): def get_chat_target( - target: Union[PromptChatTarget, Callable, AzureOpenAIModelConfiguration, OpenAIModelConfiguration], + target: Union[ + PromptChatTarget, + Callable, + AzureOpenAIModelConfiguration, + OpenAIModelConfiguration, + ], + credential: Optional[Any] = None, ) -> PromptChatTarget: """Convert various target types to a PromptChatTarget. :param target: The target to convert :type target: Union[PromptChatTarget, Callable, AzureOpenAIModelConfiguration, OpenAIModelConfiguration] + :param credential: Optional credential object with get_token method for AAD authentication. + Used as a fallback when target doesn't have an api_key or credential field. This is useful + in ACA environments where DefaultAzureCredential is not available. + :type credential: Optional[Any] :return: A PromptChatTarget instance :rtype: PromptChatTarget """ @@ -166,9 +182,9 @@ def _message_to_dict(message): if not isinstance(target, Callable): if "azure_deployment" in target and "azure_endpoint" in target: # Azure OpenAI api_key = target.get("api_key", None) - credential = target.get("credential", None) api_version = target.get("api_version", "2024-06-01") - + # Check for credential in target dict or use passed credential parameter + target_credential = target.get("credential", None) or credential if api_key: # Use API key authentication chat_target = OpenAIChatTarget( @@ -177,13 +193,13 @@ def _message_to_dict(message): api_key=api_key, api_version=api_version, ) - elif credential: + elif target_credential: # Use explicit TokenCredential for AAD auth (e.g., in ACA environments) - token_provider = _create_token_provider(credential) + token_provider = _create_token_provider(target_credential) chat_target = OpenAIChatTarget( model_name=target["azure_deployment"], endpoint=target["azure_endpoint"], - api_key=token_provider, # Callable that returns tokens + api_key=token_provider, # PyRIT accepts callable that returns token api_version=api_version, ) else: @@ -252,7 +268,12 @@ async def callback_target( "context": {}, } messages_list.append(formatted_response) # type: ignore - return {"messages": messages_list, "stream": stream, "session_state": session_state, "context": {}} + return { + "messages": messages_list, + "stream": stream, + "session_state": session_state, + "context": {}, + } chat_target = _CallbackChatTarget(callback=callback_target) # type: ignore diff --git a/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_redteam/test_strategy_utils.py b/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_redteam/test_strategy_utils.py index 41e6d75a454e..793e04c681ab 100644 --- a/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_redteam/test_strategy_utils.py +++ b/sdk/evaluation/azure-ai-evaluation/tests/unittests/test_redteam/test_strategy_utils.py @@ -15,7 +15,12 @@ ) from azure.ai.evaluation.red_team._attack_strategy import AttackStrategy from azure.ai.evaluation.red_team._callback_chat_target import _CallbackChatTarget -from pyrit.prompt_converter import PromptConverter, Base64Converter, FlipConverter, MorseConverter +from pyrit.prompt_converter import ( + PromptConverter, + Base64Converter, + FlipConverter, + MorseConverter, +) from pyrit.prompt_target import PromptChatTarget, OpenAIChatTarget initialize_pyrit(memory_db_type=IN_MEMORY) @@ -119,7 +124,10 @@ def test_get_chat_target_azure_openai(self, mock_openai_chat_target): mock_openai_chat_target.reset_mock() # Test with AAD auth - config = {"azure_deployment": "gpt-35-turbo", "azure_endpoint": "https://example.openai.azure.com"} + config = { + "azure_deployment": "gpt-35-turbo", + "azure_endpoint": "https://example.openai.azure.com", + } result = get_chat_target(config) @@ -131,8 +139,8 @@ def test_get_chat_target_azure_openai(self, mock_openai_chat_target): ) @patch("azure.ai.evaluation.red_team._utils.strategy_utils.OpenAIChatTarget") - def test_get_chat_target_azure_openai_with_credential(self, mock_openai_chat_target): - """Test getting chat target from an Azure OpenAI configuration with TokenCredential.""" + def test_get_chat_target_azure_openai_with_credential_in_target(self, mock_openai_chat_target): + """Test getting chat target from an Azure OpenAI configuration with credential in target dict.""" mock_instance = MagicMock() mock_openai_chat_target.return_value = mock_instance @@ -167,6 +175,116 @@ def test_get_chat_target_azure_openai_with_credential(self, mock_openai_chat_tar assert result == mock_instance + @patch("azure.ai.evaluation.red_team._utils.strategy_utils.OpenAIChatTarget") + def test_get_chat_target_azure_openai_with_credential_parameter(self, mock_openai_chat_target): + """Test getting chat target with credential passed as parameter (for ACA environments).""" + mock_instance = MagicMock() + mock_openai_chat_target.return_value = mock_instance + + # Create a mock credential that behaves like TokenCredential + mock_credential = MagicMock() + mock_token = MagicMock() + mock_token.token = "test-access-token" + mock_credential.get_token.return_value = mock_token + + # Config without api_key or credential + config = { + "azure_deployment": "gpt-35-turbo", + "azure_endpoint": "https://example.openai.azure.com", + } + + # Pass credential as parameter (this is how RedTeam.scan() passes it) + result = get_chat_target(config, credential=mock_credential) + + # Verify OpenAIChatTarget was called with a callable for api_key + mock_openai_chat_target.assert_called_once() + call_kwargs = mock_openai_chat_target.call_args[1] + assert call_kwargs["model_name"] == "gpt-35-turbo" + assert call_kwargs["endpoint"] == "https://example.openai.azure.com" + assert call_kwargs["api_version"] == "2024-06-01" + # api_key should be a callable (token provider) + assert callable(call_kwargs["api_key"]) + + # Verify the token provider returns the expected token + token_provider = call_kwargs["api_key"] + token = token_provider() + assert token == "test-access-token" + mock_credential.get_token.assert_called_with("https://cognitiveservices.azure.com/.default") + + assert result == mock_instance + + @patch("azure.ai.evaluation.red_team._utils.strategy_utils.OpenAIChatTarget") + def test_get_chat_target_azure_openai_api_key_takes_precedence(self, mock_openai_chat_target): + """Test that api_key takes precedence over credential when both are provided.""" + mock_instance = MagicMock() + mock_openai_chat_target.return_value = mock_instance + + mock_credential = MagicMock() + + config = { + "azure_deployment": "gpt-35-turbo", + "azure_endpoint": "https://example.openai.azure.com", + "api_key": "test-api-key", + "credential": mock_credential, + } + + result = get_chat_target(config) + + # Should use api_key, not credential + mock_openai_chat_target.assert_called_once_with( + model_name="gpt-35-turbo", + endpoint="https://example.openai.azure.com", + api_key="test-api-key", + api_version="2024-06-01", + ) + # Credential should not be used + mock_credential.get_token.assert_not_called() + + assert result == mock_instance + + @patch("azure.ai.evaluation.red_team._utils.strategy_utils.OpenAIChatTarget") + def test_get_chat_target_azure_openai_target_credential_takes_precedence_over_parameter( + self, mock_openai_chat_target + ): + """Test that target['credential'] takes precedence over credential parameter.""" + mock_instance = MagicMock() + mock_openai_chat_target.return_value = mock_instance + + # Create two different mock credentials + target_credential = MagicMock() + target_token = MagicMock() + target_token.token = "target-credential-token" + target_credential.get_token.return_value = target_token + + param_credential = MagicMock() + param_token = MagicMock() + param_token.token = "param-credential-token" + param_credential.get_token.return_value = param_token + + # Config with credential in target dict + config = { + "azure_deployment": "gpt-35-turbo", + "azure_endpoint": "https://example.openai.azure.com", + "credential": target_credential, + } + + # Pass different credential as parameter + result = get_chat_target(config, credential=param_credential) + + # Verify OpenAIChatTarget was called + mock_openai_chat_target.assert_called_once() + call_kwargs = mock_openai_chat_target.call_args[1] + + # Verify the token provider uses target_credential, not param_credential + token_provider = call_kwargs["api_key"] + token = token_provider() + assert token == "target-credential-token" + target_credential.get_token.assert_called_with("https://cognitiveservices.azure.com/.default") + # param_credential should not be used + param_credential.get_token.assert_not_called() + + assert result == mock_instance + @patch("azure.ai.evaluation.red_team._utils.strategy_utils.OpenAIChatTarget") def test_get_chat_target_openai(self, mock_openai_chat_target): """Test getting chat target from an OpenAI configuration.""" @@ -178,18 +296,28 @@ def test_get_chat_target_openai(self, mock_openai_chat_target): result = get_chat_target(config) mock_openai_chat_target.assert_called_once_with( - model_name="gpt-4", endpoint=None, api_key="test-api-key", api_version="2024-06-01" + model_name="gpt-4", + endpoint=None, + api_key="test-api-key", + api_version="2024-06-01", ) # Test with base_url mock_openai_chat_target.reset_mock() - config = {"model": "gpt-4", "api_key": "test-api-key", "base_url": "https://example.com/api"} + config = { + "model": "gpt-4", + "api_key": "test-api-key", + "base_url": "https://example.com/api", + } result = get_chat_target(config) mock_openai_chat_target.assert_called_once_with( - model_name="gpt-4", endpoint="https://example.com/api", api_key="test-api-key", api_version="2024-06-01" + model_name="gpt-4", + endpoint="https://example.com/api", + api_key="test-api-key", + api_version="2024-06-01", ) @patch("azure.ai.evaluation.red_team._utils.strategy_utils._CallbackChatTarget") From 55cc4483d67bce394dd0fd508904b379d7e86c3c Mon Sep 17 00:00:00 2001 From: jenny <63012604+JennyPng@users.noreply.github.com> Date: Wed, 4 Feb 2026 11:13:51 -0800 Subject: [PATCH 45/84] Update azpysdk 'black' error message in CI (#45000) --- eng/tools/azure-sdk-tools/azpysdk/black.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/eng/tools/azure-sdk-tools/azpysdk/black.py b/eng/tools/azure-sdk-tools/azpysdk/black.py index c8c926fc98e4..ef51b013bc21 100644 --- a/eng/tools/azure-sdk-tools/azpysdk/black.py +++ b/eng/tools/azure-sdk-tools/azpysdk/black.py @@ -79,7 +79,9 @@ def run(self, args: argparse.Namespace) -> int: if run_result.stderr and "reformatted" in run_result.stderr.decode("utf-8"): if in_ci(): - logger.info(f"The package {package_name} needs reformat. Run `black` locally to reformat.") + logger.info( + f"The package {package_name} needs reformat. Run `azpysdk black .` locally from the package root to reformat." + ) results.append(1) else: logger.info(f"The package {package_name} was reformatted.") From 6de4f7dc536dd583c6077e9e3b61881b61941a19 Mon Sep 17 00:00:00 2001 From: amber-yujueWang Date: Wed, 4 Feb 2026 11:51:09 -0800 Subject: [PATCH 46/84] Wangamber/transcription update samples (#44989) * fix multipartform * fix pylint * update patch * fix enhancedmode bug * update samples and record tests * update samples --- .../azure-ai-transcription/CHANGELOG.md | 10 + .../azure-ai-transcription/README.md | 73 +++-- .../azure-ai-transcription/_metadata.json | 4 +- .../azure-ai-transcription/assets.json | 2 +- .../azure/ai/transcription/_client.py | 2 +- .../azure/ai/transcription/_configuration.py | 2 +- .../transcription/_operations/_operations.py | 3 +- .../ai/transcription/_operations/_patch.py | 13 +- .../ai/transcription/_utils/model_base.py | 124 +++++++- .../ai/transcription/_utils/serialization.py | 17 +- .../azure/ai/transcription/_utils/utils.py | 9 +- .../azure/ai/transcription/_version.py | 2 +- .../azure/ai/transcription/aio/_client.py | 2 +- .../ai/transcription/aio/_configuration.py | 2 +- .../aio/_operations/_operations.py | 3 +- .../transcription/aio/_operations/_patch.py | 13 +- .../azure/ai/transcription/models/_enums.py | 4 +- .../azure/ai/transcription/models/_models.py | 4 +- .../azure/ai/transcription/models/_patch.py | 47 ++- .../azure-ai-transcription/cspell.json | 3 +- .../azure-ai-transcription/pyproject.toml | 2 +- .../assets/sample-howstheweather-cn.wav | Bin 0 -> 53652 bytes .../assets/sample-whatstheweatherlike-en.mp3 | Bin 0 -> 12276 bytes .../sample_transcribe_audio_file_async.py | 12 +- .../sample_transcribe_from_url_async.py | 12 +- ...ple_transcribe_multiple_languages_async.py | 69 +++-- ...ample_transcribe_with_diarization_async.py | 12 +- ...ple_transcribe_with_enhanced_mode_async.py | 276 ++++++++++++++++-- ...ample_transcribe_with_phrase_list_async.py | 54 ++-- ..._transcribe_with_profanity_filter_async.py | 12 +- .../samples/sample_transcribe_audio_file.py | 12 +- .../samples/sample_transcribe_from_url.py | 12 +- .../sample_transcribe_multiple_languages.py | 69 +++-- .../sample_transcribe_with_diarization.py | 12 +- .../sample_transcribe_with_enhanced_mode.py | 273 +++++++++++++++-- .../sample_transcribe_with_phrase_list.py | 46 +-- ...sample_transcribe_with_profanity_filter.py | 12 +- .../tests/assets/sample-howstheweather-cn.wav | Bin 0 -> 53652 bytes .../azure-ai-transcription/tests/conftest.py | 54 ++-- .../azure-ai-transcription/tests/preparer.py | 24 +- .../tests/test_transcription_basic.py | 33 +-- .../tests/test_transcription_basic_async.py | 39 ++- .../test_transcription_client_management.py | 8 +- ...t_transcription_client_management_async.py | 4 +- .../tests/test_transcription_diarization.py | 12 +- .../test_transcription_diarization_async.py | 14 +- .../tests/test_transcription_enhanced_mode.py | 13 +- .../tests/test_transcription_file.py | 15 +- .../tests/test_transcription_file_async.py | 15 +- .../tests/test_transcription_options.py | 62 ++-- .../tests/test_transcription_options_async.py | 40 +-- .../tests/test_transcription_url.py | 4 +- .../tests/test_transcription_url_async.py | 6 +- .../azure-ai-transcription/tsp-location.yaml | 2 +- 54 files changed, 1138 insertions(+), 431 deletions(-) create mode 100644 sdk/cognitiveservices/azure-ai-transcription/samples/assets/sample-howstheweather-cn.wav create mode 100644 sdk/cognitiveservices/azure-ai-transcription/samples/assets/sample-whatstheweatherlike-en.mp3 create mode 100644 sdk/cognitiveservices/azure-ai-transcription/tests/assets/sample-howstheweather-cn.wav diff --git a/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md b/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md index 850550c553c8..8cfa85875e9e 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md +++ b/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.0.0b3 (2026-02-04) + +### Features Added + +- Enhanced Mode now automatically sets `enabled=True` when `task`, `target_language`, or `prompt` are specified + +### Bugs Fixed + +- Fixed Enhanced Mode not being activated when using `EnhancedModeProperties` without explicitly setting `enabled=True` + ## 1.0.0b2 (2025-12-19) ### Bugs Fixed diff --git a/sdk/cognitiveservices/azure-ai-transcription/README.md b/sdk/cognitiveservices/azure-ai-transcription/README.md index 4a96edf3c0fd..18e31f3c2d97 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/README.md +++ b/sdk/cognitiveservices/azure-ai-transcription/README.md @@ -149,10 +149,18 @@ from azure.ai.transcription.models import TranscriptionContent, TranscriptionOpt # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] -api_key = os.environ["AZURE_SPEECH_API_KEY"] + +# We recommend using role-based access control (RBAC) for production scenarios +api_key = os.environ.get("AZURE_SPEECH_API_KEY") +if api_key: + credential = AzureKeyCredential(api_key) +else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client -client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) +client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file import pathlib @@ -197,10 +205,18 @@ from azure.ai.transcription.models import TranscriptionOptions # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] -api_key = os.environ["AZURE_SPEECH_API_KEY"] + +# We recommend using role-based access control (RBAC) for production scenarios +api_key = os.environ.get("AZURE_SPEECH_API_KEY") +if api_key: + credential = AzureKeyCredential(api_key) +else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client -client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) +client = TranscriptionClient(endpoint=endpoint, credential=credential) # URL to your audio file (must be publicly accessible) audio_url = "https://example.com/path/to/audio.wav" @@ -238,31 +254,29 @@ from azure.ai.transcription.models import ( # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] -api_key = os.environ["AZURE_SPEECH_API_KEY"] + +# We recommend using role-based access control (RBAC) for production scenarios +api_key = os.environ.get("AZURE_SPEECH_API_KEY") +if api_key: + credential = AzureKeyCredential(api_key) +else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client -client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) +client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file -import pathlib - audio_file_path = pathlib.Path(__file__).parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create enhanced mode properties - # Enable enhanced mode for advanced processing capabilities - enhanced_mode = EnhancedModeProperties( - task="translation", # Specify the task type (e.g., "translation", "summarization") - target_language="es-ES", # Target language for translation - prompt=[ - "Translate the following audio to Spanish", - "Focus on technical terminology", - ], # Optional prompts to guide the enhanced mode - ) + # Enhanced mode is automatically enabled when task is specified + enhanced_mode = EnhancedModeProperties(task="transcribe") # Create transcription options with enhanced mode - options = TranscriptionOptions(locales=["en-US"], enhanced_mode=enhanced_mode) + options = TranscriptionOptions(enhanced_mode=enhanced_mode) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -271,14 +285,7 @@ with open(audio_file_path, "rb") as audio_file: result = client.transcribe(request_content) # Print the transcription result - print("Transcription with enhanced mode:") - print(f"{result.combined_phrases[0].text}") - - # Print individual phrases if available - if result.phrases: - print("\nDetailed phrases:") - for phrase in result.phrases: - print(f" [{phrase.offset_milliseconds}ms]: {phrase.text}") + print(result.combined_phrases[0].text) ``` @@ -296,10 +303,18 @@ from azure.ai.transcription.models import TranscriptionContent, TranscriptionOpt # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] -api_key = os.environ["AZURE_SPEECH_API_KEY"] + +# We recommend using role-based access control (RBAC) for production scenarios +api_key = os.environ.get("AZURE_SPEECH_API_KEY") +if api_key: + credential = AzureKeyCredential(api_key) +else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client -async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: +async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # Path to your audio file import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/_metadata.json b/sdk/cognitiveservices/azure-ai-transcription/_metadata.json index 730a12350326..d8f3922c3623 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/_metadata.json +++ b/sdk/cognitiveservices/azure-ai-transcription/_metadata.json @@ -1,5 +1,3 @@ { - "apiVersion": "2025-10-15", - "service_name": "Cognitive Services", - "msDocService": "cognitive-services" + "apiVersion": "2025-10-15" } \ No newline at end of file diff --git a/sdk/cognitiveservices/azure-ai-transcription/assets.json b/sdk/cognitiveservices/azure-ai-transcription/assets.json index 3054fe8cf8d1..83197718b3ae 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/assets.json +++ b/sdk/cognitiveservices/azure-ai-transcription/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/cognitiveservices/azure-ai-transcription", - "Tag": "python/cognitiveservices/azure-ai-transcription_5f9f60e291" + "Tag": "python/cognitiveservices/azure-ai-transcription_807296d8e0" } diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_client.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_client.py index 0db2bd87f0e2..dd0f743b3760 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_client.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_client.py @@ -27,7 +27,7 @@ class TranscriptionClient(_TranscriptionClientOperationsMixin): """TranscriptionClient. :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: - `https://westus.api.cognitive.microsoft.com `_. + `https://westus.api.cognitive.microsoft.com `_). Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_configuration.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_configuration.py index ac72b15700dd..7d2baf2d3db3 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_configuration.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_configuration.py @@ -24,7 +24,7 @@ class TranscriptionClientConfiguration: # pylint: disable=too-many-instance-att attributes. :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: - `https://westus.api.cognitive.microsoft.com `_. + `https://westus.api.cognitive.microsoft.com `_). Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_operations.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_operations.py index 7baa39bdacf9..cd70f3c52e6c 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_operations.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_operations.py @@ -110,12 +110,11 @@ def transcribe(self, body: Union[_models.TranscriptionContent, JSON], **kwargs: _body = body.as_dict() if isinstance(body, _Model) else body _file_fields: list[str] = ["audio"] _data_fields: list[str] = ["definition"] - _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) _request = build_transcription_transcribe_request( api_version=self._config.api_version, files=_files, - data=_data, headers=_headers, params=_params, ) diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_patch.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_patch.py index 263038ad743f..af6dc07b7584 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_patch.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_operations/_patch.py @@ -12,7 +12,14 @@ from typing import Any, Optional import json from azure.core.tracing.decorator import distributed_trace -from azure.core.exceptions import map_error, HttpResponseError, ClientAuthenticationError, ResourceNotFoundError, ResourceExistsError, ResourceNotModifiedError +from azure.core.exceptions import ( + map_error, + HttpResponseError, + ClientAuthenticationError, + ResourceNotFoundError, + ResourceExistsError, + ResourceNotModifiedError, +) from .. import models as _models from .._utils.model_base import _deserialize, SdkJSONEncoder @@ -93,7 +100,9 @@ def transcribe_from_url( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run(_request, stream=False, **kwargs) # pylint: disable=protected-access + pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/model_base.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/model_base.py index 12926fa98dcf..c402af2afc63 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/model_base.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/model_base.py @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -758,6 +808,14 @@ def _deserialize_multiple_sequence( return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + def _deserialize_sequence( deserializer: typing.Optional[typing.Callable], module: typing.Optional[str], @@ -767,6 +825,19 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +888,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -952,7 +1023,7 @@ def _failsafe_deserialize( ) -> typing.Any: try: return _deserialize(deserializer, response.json(), module, rf, format) - except DeserializationError: + except Exception: # pylint: disable=broad-except _LOGGER.warning( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -965,7 +1036,7 @@ def _failsafe_deserialize_xml( ) -> typing.Any: try: return _deserialize_xml(deserializer, response.text()) - except DeserializationError: + except Exception: # pylint: disable=broad-except _LOGGER.warning( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -998,7 +1069,11 @@ def __init__( @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1084,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1184,7 +1282,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1295,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/serialization.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/serialization.py index 45a3e44e45cb..81ec1de5922b 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/serialization.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/serialization.py @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/utils.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/utils.py index 4c029bd3dfa5..54fdb84a9191 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/utils.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_utils/utils.py @@ -49,9 +49,8 @@ def serialize_multipart_data_entry(data_entry: Any) -> Any: def prepare_multipart_form_data( body: Mapping[str, Any], multipart_fields: list[str], data_fields: list[str] -) -> tuple[list[FileType], dict[str, Any]]: +) -> list[FileType]: files: list[FileType] = [] - data: dict[str, Any] = {} for multipart_field in multipart_fields: multipart_entry = body.get(multipart_field) if isinstance(multipart_entry, list): @@ -59,9 +58,11 @@ def prepare_multipart_form_data( elif multipart_entry: files.append((multipart_field, multipart_entry)) + # if files is empty, sdk core library can't handle multipart/form-data correctly, so + # we put data fields into files with filename as None to avoid that scenario. for data_field in data_fields: data_entry = body.get(data_field) if data_entry: - data[data_field] = serialize_multipart_data_entry(data_entry) + files.append((data_field, str(serialize_multipart_data_entry(data_entry)))) - return files, data + return files diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py index bbcd28b4aa67..c43fdbc2e239 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b2" +VERSION = "1.0.0b3" diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_client.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_client.py index ea92bf364d24..3c0b1e71b730 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_client.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_client.py @@ -27,7 +27,7 @@ class TranscriptionClient(_TranscriptionClientOperationsMixin): """TranscriptionClient. :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: - `https://westus.api.cognitive.microsoft.com `_. + `https://westus.api.cognitive.microsoft.com `_). Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_configuration.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_configuration.py index cf21f43beb9c..3d430e678ca3 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_configuration.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_configuration.py @@ -24,7 +24,7 @@ class TranscriptionClientConfiguration: # pylint: disable=too-many-instance-att attributes. :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: - `https://westus.api.cognitive.microsoft.com `_. + `https://westus.api.cognitive.microsoft.com `_). Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_operations.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_operations.py index 0b1835a4223e..20a77b8ae4bd 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_operations.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_operations.py @@ -90,12 +90,11 @@ async def transcribe( _body = body.as_dict() if isinstance(body, _Model) else body _file_fields: list[str] = ["audio"] _data_fields: list[str] = ["definition"] - _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) _request = build_transcription_transcribe_request( api_version=self._config.api_version, files=_files, - data=_data, headers=_headers, params=_params, ) diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_patch.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_patch.py index 8641af408ea6..53b64e11014f 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_patch.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/aio/_operations/_patch.py @@ -12,7 +12,14 @@ from typing import Any, Optional import json from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.exceptions import map_error, HttpResponseError, ClientAuthenticationError, ResourceNotFoundError, ResourceExistsError, ResourceNotModifiedError +from azure.core.exceptions import ( + map_error, + HttpResponseError, + ClientAuthenticationError, + ResourceNotFoundError, + ResourceExistsError, + ResourceNotModifiedError, +) from ... import models as _models from ..._utils.model_base import _deserialize, SdkJSONEncoder @@ -91,7 +98,9 @@ async def transcribe_from_url( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run(_request, stream=False, **kwargs) # pylint: disable=protected-access + pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_enums.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_enums.py index c6fa0da4254d..e341385368ac 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_enums.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_enums.py @@ -18,6 +18,6 @@ class ProfanityFilterMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): REMOVED = "Removed" """Remove profanity.""" TAGS = "Tags" - """Add "profanity" XML tags""" + """Add "profanity" XML tags.""" MASKED = "Masked" - """Mask the profanity with * except of the first letter, e.g., f***""" + """Mask the profanity with * except of the first letter, e.g., f***.""" diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_models.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_models.py index ba3dd5af6cd6..0ca8d9922af9 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_models.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_models.py @@ -100,7 +100,7 @@ class PhraseListProperties(_Model): :ivar phrases: List of phrases for recognition. :vartype phrases: list[str] - :ivar biasing_weight: Biasing weight for phrase list (1.0 to 20.0). + :ivar biasing_weight: Biasing weight for phrase list (0.0-2.0). :vartype biasing_weight: float """ @@ -109,7 +109,7 @@ class PhraseListProperties(_Model): biasing_weight: Optional[float] = rest_field( name="biasingWeight", visibility=["read", "create", "update", "delete", "query"] ) - """Biasing weight for phrase list (1.0 to 20.0).""" + """Biasing weight for phrase list (0.0-2.0).""" @overload def __init__( diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_patch.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_patch.py index 87676c65a8f0..1f20b6224737 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_patch.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/models/_patch.py @@ -7,9 +7,54 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Optional +from ._models import EnhancedModeProperties as _EnhancedModeProperties -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + +class EnhancedModeProperties(_EnhancedModeProperties): + """Enhanced mode properties for transcription. + + :ivar task: Task type for enhanced mode. + :vartype task: str + :ivar target_language: Target language for enhanced mode. + :vartype target_language: str + :ivar prompt: A list of user prompts. + :vartype prompt: list[str] + """ + + def __init__( + self, + *, + task: Optional[str] = None, + target_language: Optional[str] = None, + prompt: Optional[list[str]] = None, + **kwargs: Any, + ) -> None: + super().__init__(task=task, target_language=target_language, prompt=prompt, **kwargs) + # Automatically set enabled=True if any enhanced mode properties are specified + # This is hidden from public API but sent to the server + self._enabled: Optional[bool] = None + if task is not None or target_language is not None or prompt is not None: + self._enabled = True + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + result = super().as_dict(exclude_readonly=exclude_readonly) + # Always include enabled in the request if it's set + if self._enabled is not None: + result["enabled"] = self._enabled + return result + + +__all__: list[str] = [ + "EnhancedModeProperties" +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/cognitiveservices/azure-ai-transcription/cspell.json b/sdk/cognitiveservices/azure-ai-transcription/cspell.json index 26702324f058..f08faafb5cf8 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/cspell.json +++ b/sdk/cognitiveservices/azure-ai-transcription/cspell.json @@ -7,6 +7,7 @@ "words": [ "diarization", "pclp", - "pcsp" + "pcsp", + "Rehaan" ] } diff --git a/sdk/cognitiveservices/azure-ai-transcription/pyproject.toml b/sdk/cognitiveservices/azure-ai-transcription/pyproject.toml index 95d02d2172c1..96a3aebb064b 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/pyproject.toml +++ b/sdk/cognitiveservices/azure-ai-transcription/pyproject.toml @@ -32,7 +32,7 @@ keywords = ["azure", "azure sdk"] dependencies = [ "isodate>=0.6.1", - "azure-core>=1.35.0", + "azure-core>=1.37.0", "typing-extensions>=4.6.0", ] dynamic = [ diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/assets/sample-howstheweather-cn.wav b/sdk/cognitiveservices/azure-ai-transcription/samples/assets/sample-howstheweather-cn.wav new file mode 100644 index 0000000000000000000000000000000000000000..65d23513004ba6be2eca6c2bbb10438753795911 GIT binary patch literal 53652 zcmeFYWpo_L5+<5i)y&;$G0T#fnVFf{mYJEEVaz;c9y2quWqZsdTec*NS?X3ZRb_6p zbiFfo-=5uH@6S6=d0JJKm6Z??8I|>Ykv%)KZM*RkLj79wZ8K)_tOy-K2t!)d6iyZ+ z#2^ivj2b>`_!ubl|Ns4eQ376lGbLL0p8c=MJ7Qci?0?_+C%5#hv_wg<|M~Bq@}*h- zyE6Z?@c;GX|Mc|#>7KXZ|J(h4H%?3byg8JX=9lLD{{Qc?|8JlF?!oVNO0R$C{_fF# z=l(AH`{>oe|N8e&Ua5|}_q}IcEAakGuS)MRkn_K@j(?XaZQ*yVrN`e_rR7R{@ZWj= z-Og_t{O^+9Cw|}g{d8&GKjliV|H=L5?4Le*OMCPGJLjKV@7eEr|2{9R>$e0-kKX_6 zf286)|9$oQZs|Q1%6OAES5R{NedR4*n*Z;of9L&k$J=&ko!-3P=l>qvzkB@O`K4p{ zfBygPQr_DC{a32T(wtJMm-g_V{L=n--wUOEDxD?&-1k2F?`KNKz=8z4xus())k0~h ze=O^FKmOfA@45G{bnK;l^;-S!vZcrWZXF>)`I1B^DVZXKa*(`v-Wl$>6!P+U6NCp=Y6vDtTeau+FPf$yqmg8l9M{9y(C$wnOdk7k_FC+A(`OlJv08# zD-+~-lewgv_pbNc0;x3D`=s~G2+4c=U5DjAEqLqq{z_Z4QE&2|J4$+CgFB_y-W+F1 zAMGVic%QNTr<4Qw?d`QUc}u&XoOd+de0NE0-jUf$%9ob&*5s9xcig4YES0g>3TTOR zG3eN#ENdnG9;@4X{~CuC5kwB+b5BQD8Pl++-H|H_h|2I(NF;Y#(N+P%l$ zSKc0ZOUj_fBBi@mh`%`tXD?fr@eE>Tk5x!vn6$v&b!jOyz{|3n@T0^Ehm5$*%F<2rS6?Y z-dfm_=^`k}A@EG8S1QRYDf9dJ(i!-BwwBIWug-q|ypr^`?3J~5Y+ea@bG)M|9iR8g zD-rLNx0O=edh@)cyvaLe3EV5KrBr978u9AcD}Qg&l;~SkqIa+6y~%sORO{lBnoDh} zR7&3Vyw_fRl*+!eJ@1%>(4GYTmyX&iC9mAPR$DsTy_Q}&Yn(7EyooEZXs-`JP^VY- z%91*~Jt(yUA>vEsiq|`M=S-=eKu{_Km4Uu`=d&-Wh^nA?bf5WyIgdu8MAQ)3i^k9%WH2$&O(=uB z^6d7srfSBQDUU`G6S;$(Y#ws}ts@-&fU-;ovy>j<{J4Cw1*cFW*U1yceIje=DXxrr zfTtsQN>1=mTu&~V?4Z*qPiB$IWHkMb4x#BZi|Pz2}4bs);*-j(0+G(wV3} z)O4S2K;zLK__%mOQ^|fb0SnQ2noJ)cmMIJ8E73a~%&fpc_yoF&Dq#=0gg2mJh@czT zh&y8ex{m5GRES#AGh{P0pk*irqH(=|Gb45Ar`qfKI{bl=HWS@m)+ZCXY3& z`G{hflXM1O5f$NfbR9)F3M4k15_}T9C0|Jl%$)gj1-XeBu;zC33CRX; z8OMjC_skdafUAYt!n|xkTGDlR3Vud6(kt{WibBI_ED8ZFN6=h448`$AVq{vNail*D z!ZuWcsK8(3p%Fw(rwEQ=yQeyJF+I?BQcQW2M%|9JOznp9~i-G@;Al! zB<+l5;VNh=>WTTu9^&)p7~GOr`7Vr^sgEl2@9=QpZTg%~!!hi8dYL1%4qKBB=U?Kg>{hyk z^T7iIQDnGh8lEc<5af}g&&+Gum}?79u=pr{m@Z_>qH|;uYQU!8j(j~DBPfT2TsE!E ztfPtibX1?YLZ6Wn=ro>7cJb43JEnm4C2a`8H$b+&{9H1cNykCN%@0Cta2)vZ=BN|s z|8LXzcpFz`bEV@L7(>*AQyrS{63z-OZRUd1aHZ+;9 zhV)E#G>LAb>o5%|Jlav8CBE2%^(Q(vYk zcJK%2Pr8zhW+E7dKH`_4L}mtVPon8Yya|=1YiK)k9hO^_2uGuEHY%d8p(g?0VF#e) zs0vk56&eAW@lb!VpFe|_Gacv;J`-%^Dt6J!$V#V>Y2ZaF;wRu=mg92xHtE7|AZ}ER zHsOEL8)yO9N^;OS^o_4brR*VQJ$UEw>}SCM^psL^O!XHi!>y&xR>s#u5=fKGY-jk_@Co6Q!YYT#LlT1W0?PWibdA(o z6t88C#JiYqdX96sF4>QouNoQ_{>{o)KyUT zm!*pS5Iz!kK!20m4hOOiu(mdv4bg??3;grHX6;L>_3Lz!GgXj#J^N_t-1PN@A+`aw zV$)ztDBnvIFFq}LEfJ{C>z#g5-y+?3-_L;&!8iTe`s~q$>EnINYOBeXNk+=2DV@^g z%yJsYjuXB{XWY|W-`%U-L!9w8YE~BSDY{coDX(qj$>hyRh1tGE4YEI`EX*2bIqizG zMOx)94m%`)@>jCMvMK67|DS;(KZiD1e>|vNaEk9m^$*od-8fxU)Vtu>N&oDgxn9_qkpY?7BD;Hu74fPL{(dDxGq^aTryasl!VB(N_Gp{ z!+SN4Imw7n7k-^*mAkI{v~z>?o^f5lqTCmm(Z9z0te(-oU}xso!q!vCq;V95TzNmF$;nyEa-oNGfFqu?NIr*#gO5>{aB# zV};{H0_F=B>zT%z`K_+g=8r|FFd;WNwNb)?#2I;03W8Hc|16&~%&o)+of|AG_%_Pn z`j6Tl>eZT!dUx=Lu(5%+H5=5Cev<+Vv<*ecY^qG4dMfruM@fCbBx!F67RYclCQpzk z+$Ly`hI&@GoA8yn1j~v1=;D^pS>1Z?bXx zF^`)&z%_FGD(aP;p58d6dBV?lQ(8>klhhfB{d3B@35p?yJ@3#(WjX(w{xSL|+KN6g z!GDF<@E@nFqFAo^q3xt-%s!%pg544{$f`Nzpx@^8LrJ_Wb|UGA37 z?WTzAzKMD9n?FxV_?$U5W5tiK#4m*hsgZ4oUXfri)|Uyc9IWwkY2vk)1Dk|~=_iQu z1>WZtdB4qQlw2d?z%o&?T7qY2djq2D~atW%st|l zle15_Mu|7b0wgZ+B-J4QbPL#`12u2#ruUkh>47wlC-u(erw;5yi5zCF>Oj z6jPPwG=J!?`_1ut>eEuKQ9J^lutIQ$Q(LPRjmh~tt=rG^kB{Gd_)#;fen!8PUD>DY zDT1HU&EjE_bagfVHUVS&mTT857-f*!AipN~NaOg%v=fcz_Hm(fE%S$dZbLd=q_@J}K&4WnV>Ei7&Fb^p1+=A-Q*wUw&))`B40&)Qt2lzrOxDl^5g56s#9M zX4;5%YM=Q&)0fd+Q+Ah!D?TU&O1d!xBo)4ko5FX|34SkLE%+$9D%mLCt7@b@1FhWg z3-&e*M_+`Nr3BX=8E*WS&nST~O2gPEb=U6P*zc zSGd*Xb-6zCR7IkD?g_5Y`ks&WbEeS+YqDSGA2Z^j4mk(1BMr&6 zOvg@ZocWAh#bwam_#E;lcj1e!n>bC}hiyvV(Sw4!qTWI^d!0Ql8Z8~D*r+rqd#l!| zW3{b)&iIVbd{Io12g&0ld4dJF6VbUpTkjawQNPBjm8 z7(6!!;p06v(DilptMHP*h9{zy%mm>G@dD8xp+Iy(vRbiE6{)VE4p$ebk85LmQncMv zZROjf@se5MgMusQfk);jZwV}pG}+9u;_-!53fCHf%^J%}v%}OCpm2x1gL}9q)1`5p z^K3`k*$DP6-hwYPMS>fmPhz7uTKqw>O;JbPTzyV8LS0eg0BirOZlZcFFOWt^R*Q7P zvW$}_PQ9(RaXgi>XWKw>P$^{?JG5}=q%qQ8zFUyjl!<%bK1}I%W=#8 zx3h|~skOi9M)5;)o+Z+9*Ywl)#K@YY)?oW=o7@^~9qL%;=|m8{0$(8Ia3?`yv02<% z+*Z6nI!(D-ouJ;Oo~6!K2WW(n z9MA-4q#CWJm1d=;y=J;PQn_EYLV7`3RoYwh5TD=~ZX#EnyW;9^zX?*xG(RwRH1#n~ zDSA}c*wD9lpXpPv%h<%!%=*G1aqB!Ixm3O-ieafRU))2IA_8gt`gZDH^f* znsTe6iabWzK-7d?jB1i3ZjdM6Ilvxk{b7D-8c@8+@S(7{z*#V}aC%V{!zsgPV}9{n z_|7PBes-Vdf~kth7DS8hNxn(P$?q#0Xg+DD=q~G$bXuPue-`a2Y+aZOW2j^h7l4)Rus-QKvl?cZjrl{GsX7J($oC5IM$d| z)UNPML4LuTLe_A}fQ|ZMx!G#Xa-4U`JOchH4PfsI%Zmp|;-wPBCeU)lk>`S6xX z(cRZ^+WVTa>U+wAigNM?lF!0N3@|5TJU7uD;k<84u=Ft_(>J51XhUIe;i^ z6qS=Kl8WU6m5bCLG|#oQb^Ud1bz0pz?IsOY4_Dgdf5|RMRHA0=B2<~o<<7hBJO8w| zv_3a)F^w)BWxP_fu~1nQVpwO~Qhc}gfhpJ0!2Z;E%pJ>ZBNtE^_JDA+I83@$RzXou zCDF9gnzR8xVm;7?Y1?TO>TOD`;+)JR`5=lF+{feSD*l@1gX>SnP}@7pc(cM3XRL3i zQZ%T@P$V+u8Cw^3HkG%;+O9bIy1uwY{1zI`%n)=Jl?NG(m-kd!Royj#+ELo$+AG=y z+6|hm>TxPR^#+hV6zGARm#b zv3Ztdu`S&Z?|S7q#h<0+nel?oB2L^{`c^hgQLOB)cB_?|YMNs8R<&7`s=TZiBbUf- zOTxspg%)NzI!m2kkPkTW_oWrVjga}Zhdd}IE!IE zHzD=W0%oINi0F+tM7lGkzqSyootzFzG2dv+{Lk`m!@gv29{uJU)u|Nedin3Y)>Oz3!Fm|vq0b$ zE*Afigvlz%-^-^c-YXs`4l0H!GUe0cZ)L1(kaV^L)}_L$g39bQ+#1~_G5irvQ+KlS zh2x2RtIcGcYc*KXEyPmBdf8gfmSlTi-{)B2-0q5VhjS}=2YB(DSj+Ym>=3>ay%aB& zRF>Y9>Sb*JcZrbk(r41?(lm)!!izeHmI;>$#zOmcxx=x+ z5$kB~`0n`ZSnP;*h@I=4f4G{twVvmm&fIW*GC4p6*q4#9U)f=T6hUiY1z|biT;VC< zdf|NGpTc>Bh8Y0+}y(F=m-{yg7_%qA7cKE5lUy05tpTx~!izLKu=1aM?B^a^;I$AE{% z)9WzSU|=;y122$|=ApCN)5wtQB`jgBj@i`ExaFBn@k0wdvBe?}!K_(Fa0;+~G>wrNRKo`nAI&fb$dWjAO?M2ZZz(!S~3uqN|7_|qa_Xu50n*i||M*`?E zV6^7Y6~G)+f%@*CQNWfO0U5soC~q&clpdtV(GJLY3fS*^U@8Xy|J4okL;lc481!cy ziYGGwv+sgZ!A^we3~+h=@Qss1A0Z#~gpQ-l=ry_wSg|+sExiofTxV1p{|&OWBWVBHdcpX)(W=viPpqJce&#xmRjWueA^ST_N#s5;>8 zf71qJDB29xbA|?x1rRl|fF2+&+6L8vUff4*pxihb3XFIUrW^v+6RklSS3TCMen3f#c3b@@h@Vz$^*hfTj(O}vEU!_ZFTYL+B zqtB2ECz9jzH7cZQfd$$|n<8JF3mUmbm(YCD1lqN84^aregGM4F83)WzC*b)In#~-c zr_nZ)4En8vR-?Kw$`4eBZa`~y=q=PAX96SG71>A>P6bYDEzKk{nuGRWf3lbK2B!WD z2}Z|YzFWbThS6P>PiBxqklzFBcrec7YvQB0Kd_Rsfmfc#PX_MU55{Z<&$AAF zgc0`UyJ0=;k6+@Nq!rT)rIQFo1B~f?ngF(wNm{bLbRSuW`_V(-L(W1(K?5`r7{Ib1 z#RkAyR$&^Wg(Mn3AP<3KJqJEPhRO?;kO#~pbO2d#GcuNna7UPr7LZQ{s!Nh#28!{0 z+=CSJPjCp+pYA6ufu~9b_OBgy&a>FXPbI~8F1|&D{9#;%2>_;a6!BwPFi~_T+C`Ia zHSh)5_#3)R`vLE;jQI}U=r(@@G;@hGCK6!TJzO4rf%~8?AiEAQlTPA^d>F89-|;be zmgvw^eh`zu%z$qtEg6XA_y};(Z%7q<{n0nD>XnS0_TmST!`KfkL>GBK zULg31UIPm?2G?gWu;mWmd0E^In6IF4w;j^sM<^##k(C$fq!CLM7U^MT{JFN`nt=M%w8 z4B}qE%)O69EQ3aHeepZ-abn)= z9$D#bLGszJBpz_G)%@Rh54FL&@(=QYT}Z#7e7ur0!}rMwvzRol$W=xvDr0A~4!|p3=t5YyLEOLwg7c$WpEcXsDh@g=Ts_LA=EUegodb$e7X8 z#P6d&a4x>%X$Q8fMZ?H3dXC+Od}sweg!g5^&%1{)Qw8mq_MYV^7uO|n#>&+ogCuYH zNABuu7I{j`;7>#aaU!pHj!VVs*e0G?*d>`l6yz22gnq&In1x(6znhti8j*hVJ~nxV z0B_cr1PErM<8I0&vvu%8ZV}!`I`O?l%h3`vk9o)E@o%wSe8`>3sbOY$gj?`gz7_d} zJEP^E6v0q*$kT$YP2WO{N+n)}bWAQ<=Dx#k7UhFw&BkTmO)mpHvn98QJR|k7_W%xFPVl z0my-mGXrUFasxl&Q^_9oJ~I**!HR1K^H5kHZF2)HBQTP|?vvy@{{lGKV16jN0yFIh z{f^@Wd0Y%%z<$G#Y>qboih0B+_}T7B%zN-{V*$B)ge~L`t`~}D4x%eAh7J*%=|=Y% z?h>6R_#0pK^r2DgJmw?Wj9-eP*d1gyc;_ALF5H<lwZ!`kB@ zUW~Sp^`47J&33>`Jj*;5#Ib?QCGaXgm_oc1d}ePpoOT26+6-4`ZgBy854IXRnC7{= z(swA0-;Lj)F!%?hC=OdDezG08+F`p+m zg)Z|datxoveq<`O=QJp34LATMV&iN5l4oGZzD<~6gDl;vvx^ZN&0joRZG zjFcbAy!iBgu zUjt$~_QMJ#i&Uf^$W)q4rbDC!#}lH*b(s6a>6ykf7qmdfxqW;!HkwW6WBGk3omoP) z{93e>X@q@gRfvAL2k-U1xDfAT?_*4dLrlO;JPiFJHR&RVM%hH0(}{rD59QxM^M9IqT(jwr%WgO5qD)*G9R%& zPJ}Z9M6OImgXjf3gef9xxVPMR+VQ#W&hC1yem0w_i}`@%jn&88r)XKx4bxP!Z*g%^oN>J6fUU26uCokRz?n#6 zK~2eaSxbdL-Na|Q?-1X0zT^FC1#JsT4LIy4_7(U(^GVVmVhMc7I;VBoA zBa&i%RQf*a`|+QtzZ(7uOpZ&n=foL!a}#TX;|&=mIxIV0o@Hw|Iqet4})QKsbljr=D zCw%$7{--{5QF>HbyR`l}#^N2ee4Eq(HY*e=T*{8>fx12ZO+ry*->ByiVUgd-4Qd_)zllhz3H1LK53P43?r>(Wl9hNX;4YWDNuk9$8( zB|c0$ml>Urkv==Ghc(_c#<|Bi6b+QMS8r71tH1ch2QLe&5`Hz}Q`EjPhsp?|_e4Dm zD+s;eGml!`xmQz;WIGcSV(q+FnVN^Ga@l6F=l^E$H*BWq9Aq1 zz@P;_PDN{JN69PETinxK#rD*)#r(u@JAY`-qfFlnK6Oyax#Yy3V-x26xc;kBmLU6Q z`ku@;1_NMX3C<%Po#2k5o#vTlp{}uCyP$dDC&~;cb35Wl#KSU`%a)7o66y$u3+xmm z^0TV$NKcB(i6Yqxe6pjT^}ESwyjoN@e{J^JjLzw+(uSv`Brf@}>qq-!l3~x9lVQ%d zUJzz4bPaLkxL=^P(%mY5O;6o!{U(1|$hU};sCALg!~cvJQ)XDSf5hpa2?1&Tul?M* zddkL<)50I@6|{z%?l7497RMV_6e$Xt?AP#Yb?*Jlvzb*3 zAK7<%#=6J2yW>`}Ys%j0uew3L)%*_zrG@*J`54KD$A+gzH7~O{Y(bzRV5EPMzOUvl zxkS28w162(5DQQKCMiF;d{)2Q3E8%+$ikks zn(lip>`p`FB>Uw{ly^0M_;mHv1|A4)84(*E6gnX6S!C77*pTA^;{&ew|MDrT>7fje z_Z5$aH?^J;_iVe}a?HH3curBdf~|SIbDWvNOuvlgsVKQHNtUrBFDbWsmNLg^6gc`g zkt@Y>4c`-~r4nU#?FQWeUATY4kcpwgLpz473uzP9AS^ccK;Sq3Q+k=ssF|ahE3=E7 zOaQ(>e|q*ivaH=Ki%qYLy$rsE#d(3bud`QWH_UvUT05mM4dwY1w#dJoGpwMwb*W41 z>FlY=|Bc!T)5DT2?dSmNl{c2$?3rq(L$pzYitb9{mKJ3hN z%RGCyzOeQ_DvXvtQtnpNlt-y{`AqW<_HW@wefRiY@m=O09#G%!p>DdWDX?H8R4xcy zzYgy%3EDx1d73+?0;cb0<*chMcZ)v*_P5h8vZ!yqD|>m~0AnXphvHcVjd8Vkx4n@o z#@)wr#naalOTP+`R3kYrGKu%dyKCC&e&}B44B8A$u+Ip;j(+`oShZ7;s*F>a6a~`1 zMGx5J*!#6PfUum&`P0EWPhuz23-P0c4J^{Rr-oyp$dSPerM#&w?Yw1FHvO=w_tB8>wm8HtQ z%c{sWN~=iri&hCU1XjU2K?*wnR(7>mE!&BC0f^9Pti=7$RQes(#cq$o6Ua$Ca(7>6 zBj+%OzeDO6Vs~2aSsz%^EKX}vTU*-^+j_glvCI|jN#!;Ik~kWVW-dWg*mdDR(G<}J z2-lw|{!5%JmI0G5mvolwkXR-8k~xw=lB1G6k|pAr;xy5EQ6rHQ-jKP19l*f72W007 zi6%mRB^T)_a`kg%IqEsK*k{gj>?^q-X)7HeZ7A(1?I2~O$0T*2{gz^#xVmVu zuozZsaqx996AuA2LrcDMC%DU=V)sJ#NteItlykKcIX62VI^H=1PR40j3V#agi-e*`QHUs4 z_*QsN*hiQu_*>9MkO*tNk4!Ga>^ad|_^#hh8&L^eL$djF-pViJKXbJ?gQqrdXZ~D< zr!v=sYssyLZ@@sln7ayJP?Pynd;(ttoZKpiM!i5KfSpc<$iIR363)TNI0=x~cFZ#7 z9`g~>J?1B4VggtXMCXlxulDMYLO}al@NV1 zszNMmHCP$mC%efb_+p$!Hj)cu0;x*|k+nof6@dJ?0ezeSSlh zFgM;n-ZvPD85sLiXgvq^l*FI{K;z_y1I)`0a6mu64J*M8l(MK1ssX*4fTNk z)l2j^6m;p2YNF<#mnbMNfpxhCuu30@{nkKjiO`>X=uaWk`vH3NH%)*(8sYo_eL>UV z?iY}o5q7;`*dOD7F%T+(NLU_rLRe`z7jJ*iTd3Wzr zgPkw$KrRJPE)n`@gr1AR-r}JDUTJuDIORcYejtfjaE_prVA!=$6?CIVH(>|P0MMBX z^hZFxGH62&EJIyX8`ksnpx+FjzxyGQ`7e+|Q;=;}$jN}67pX8h7oZAu$oJaPZID?@ z=x-K%4rsjuzE+Y!SD7>rILtnqbE|k^4J%z*WAu;H91*9F+Zs(@fp6FYyhwdifh;0z!KMWCD|ot_;19M?D>5U3E5p0O zffnMUj94IL*8)zm6!k$9X%Xz@$|rju7BL*Gx(w_`3qXN1fM3AhrYf31w4@eT;7s(H zoBl-hGhjI_dpt}}1pZ4&`=uNaMCC{6%QY$LD{bI@?+Gj?Jh<^{TmHsPl1GeHNz z5EyL)$aMs+#}+YlFav0Qe|ir+$Jfw2+J@}&Omfxr%;LXsi#;=(AMFlDS7$fJR7WcZ zvJEnCFyFHdwfi|b+DFK{aXD*pG`h%^jq}% zd@P!3szBvk`AMlxdRh8e!ivtZQ<;9uSSApUrGrQ@=W=gwFZBHIl<_=r)pHJX$Q|=+ z8J3Hdhvr7c^Z5s|UFnB@9r}?Izwn19L!H;RV4-onwWEV^$D?+#{n}uCRegZp(7?k% zsX_BYiozy_{uwaMSEJAOnWtN*3RWzZDa2FQvrMc&BKQo_31H)ot-l;xDmhj}eE==ubg3vCecC`1~T6XuGz6*)h=cko%?7n=F%?dsl2o1_Y0 z<^y48&^p-37LS5qk7Whs3M&-$7l+FCsO;+Qng~r@ja)llyH`6++eST0{zUv)@CnZ% zNp69ot65ZN%IurspL{e4C-(my_j%8|O)vL8-TA!5yNL;{(^}`PFl}@0=f4TAsA*u8 zh`%Bgk@4Y;!u&%%2fqq=8T8s`lcJ$?oWv?_D8485le7}{z-7=$28*hQLnUve9c7!O z$abI-gnhzBX$y=9oBE4_= z-Sni?K1r_l@*h9GK`-aUJ$*CeTkNj}+0n&M9iO;MY&*p`zgpqZkpsi~h1CeF5#k?I z9GL1qLsv^VLHbDYT~=1!Sb9hD6{0Yv3h#(a(zc4;3Y9!rwn-7Bid215Ro3Qc1)30* zRJ8(j7aUQyhv>eF(yPL;g8f3X@D7v3XFGRWyPC!tl!bHhW@Wbc#Uyq~di*Ob=~Vp9 z_g`KWJ&Ah!_=V)lnG`nfw9&`86z`Gt)v;lT{!6o6)m&a(a!W)-Z^dK9mxQO-{!9m) z20YXd#)7VKjhr)WgRKWGy-ewa_j2lGG)rBQx;On?hB@^{!t4*r{=OYo=Xpll=(q3V zpQMHt&b2?G$0ftGV}oXv5muO2aYy-OF;gSz20!y_sS8(~mTnLvz$$e#{=n9Sh@_>` zIr2fu1?rZ%c;B%BwE}wiAMsn`TS?zhw@1@Yty8X-wiMX}k-`STSm7gxj%g#9!;WSz zvO+-ta}?S5H}0;EY-=^^AB}CA6$Q5d_kYhc~SR$ z*#tfw#YbD+TuT+pi5*CP@#7R{)xRm92;WguT)WQDx>&L08cq z;;NEb;v7M9CI|NH&VsjCf3Bs=X)9-T6yf~o+13odj6X8EXFN-LlQJ)P=g*7Z5bYpyeG`R*)c@rfKARJ*Y**yQtu(8DZ}OVtvM|H!Hfx?n%E&>q&kH z8w)oJRpRGTqhhmWkdIJr)?L?K*Z<*{=y${asDBgR(b{p!N3zq>V#zr16k&`&%)UkE zXce5wE)@0>ZWLT$n=&uy5q=F{2YAIK_j+fJeVw(FX@FsW!HwLUtmPS#(l=!Mow+je zW%`7aVTql;fA|vqIsQxd&(`U({N5(BV-Tqv6R2clgf0VwNR;f-= z@v7RYnTqAI&eCw{d+8$iVP&)i>rQIBYi_CsYN~4QXf;0j^j-D!bV~JX#SMt=TPA)f z+9*mBrm=ruDe4N}-Sc7HSq|1ki^ynhr2Cw!vum9*&au#uX|HK}Zmv+gyJ%#=syvk2 zCue8Q?VP$f#_ZNPJ~<<@mSrTS9Z&6(wkC6K9%o3hR(JEfAI1>HI9b|M5vwNJhd%4{ zKYecL60{#RiRv|KnP#(Q2t@0RQa4wHD|aa#DkMr@Wt1{hc~{X-5vVvUZzYeG%jE|l zq+y`+tmK^dz9>$3NAQ{TW1BI{u^Y{URjePxZY}4Vae7Z3_ej?Z=SZj4dCJkpQQr~d zNV2cD_lC61&e=OUT00buMfT;kGS=nhxMGFzbWvR4#ll)e6%Bf0g7Ika9@BYqoaMZA ziEV}blcT#U*S&|^N&Z47nEha3M)6c>lB}I#z4E5&lDd`Vl_pHvOS=ku;ce{^?PP6# zZMfE`iPMbJc;HRfUaeEVRvlE0Qz-x$i~uCmEpI6wBWo&^NYX_2gewFM*$h}YtLbSz zgxl=)bsce(v2V3n%ss(VN{l@XtBd9oRxS9PH#fI#4$Vr>tdRLW<4%S$b7N+utZ!LQ zvr}`v<|^|~6tpi2Gy0e&S#oU6ohJ7MzAK7ku|b ztrny)&G0!IM)q?-p3|dYw_RWg=k=rccM?#b$xt8@=#ue*>2HhHzRg+2^Nv4>=CTt-Q>2X* zta`gP+lTXg?%yqNdC>6SS|OK0n9#l&D% zsKR*#arvS7ee;&)UdqYKUY#A2y&y}TCCloYWzM>qeK@B_F3PKzKe6CMq26%77;9=^ z>0~?ZAg*;>e^_Tqg>s2Q_E_0Xb6Iy!zs4^rU|Ha*px9t($l#FJkYOQ>LJYyHg42UE zK{VjI{|CQ|zU%eld^Ec6n)B*~s!_^7#WUGzX*)?raShQ+!6?><=b>==k-y0u_iS{} zcB!570gb+GnQty{dTtyJ_&O7>Ide-*rX*pGL zKj)s!JCc8+z_)0VA)@%B>4AmXx;QVmhr*7a!%VC&Qeu~#fSB}Wx(xjRzmR~KKz-2b zpoziCkhUSULZl(vfyKHIBnoO87!+Xe%kh1pzwEO~*GpRuB7uvPpA-w^m1RYe^Wrt4 zHo^?x?XwXefQ0AXd-l5rxXL+`?Hg?MtuJ6#LAzqN;bYO;!nA_Wf(iLadCl{7<_71U zhF)LI?v>prdm>mvR?gAf5qTl`U-R<{Y8D+f_!RFn4FVa@aYVV6d*1L;!1KHuy?VEtXs?hrZ>hd zhChq07TzoPnlH~^kf+Yuky|bIQBK92xa?EeH?oVe2j{fNjm&$VwKT%Euf@Gx<%cp%FN12Ew^^u9R?fR-JQW20S1@B-KC-3%Cp?nmk)(l-`xR z6rW-jGqY$dRY1HE{fti#md5rX6$Kl?Z>?P9Yv@66D~uWQeFr=>-OrsP9rf%X>mF{5 zrIvYs$z|MYY-hY=aOel>&ANBG_qv&IMMiafb#3%r4JpRY#$Bcz=F65BoZ7Y)Y+3GB zdXxMef(OE7z>BIg=E9GW6`6_Rz0wu(^2%wd9qPN93vj)77k4LaL0p}R+4t)%s4NUac@xAxV zb2oGS1>V+Do1P0>Xp77|)b!3c1}u7rAxpnXUtiDY@9JjguEUv^V8}KsF^(~{2H*8& z+zjh`+X4sT+UTz6<@r|z9pQ$&(*hDp#e0!AXc+jAewH0lSdfE zxmBD_TUk3#^Fkd|wNlkrq6(kviS#De#$W7R(6a*cyhAh#|50d0ha+G3gLp8m5?&A* z9V{Pk`!0B!cwDYOoHOBSthE`qG|OuwK@*W|@Ya44*&d!88W-#yK>fG9 zojrxFm(JaeesPwxrXkBpAF@Vtcf;DEaf;C z_u4A64|nWzeuh}COWtAra=`}S2H;J)8A-=#ibjw<=t*oVh)kX$f2iP;xvI%(Rx?Gj zNpoFuKr>Jy(X3Om>OQJI%1MeT@_w?m($W%{*v6csH&JWIImBR*6u*LvL{&&3_zBgA z-jf-j*1^Pp#dp`c&C}PdcDWqS?Z4T2SsQYlEIZ6`<{PFyCcp6(NZs7%H{3NGGwe3} zVUQW08t<73%%3c0x&78_HlCxZvx#e&+wD2yTOF7j+8p`76Cs_kW%wE5F?EJnF0LXy zFKeP$sBEBmubQNmXy$8{XzFVU)Q8jy)aBL7RL7Nv6?^38Wk;nOB`d_^*e-DY%Ok%K zk3{=%i0;M;k=X)1|8TT3^nct5{u=1)m%|grboVe{|)p%;c%7P9h?;y;urZ0p1mOR6lZ6+HcM>p zIX>6Gvfn)3T-S`6pPR;-;!H1$+l{{(I~dh)uz zp7B0BP#A0&nZo-lNP!5#HN+-rBvV1WU(!wXUd~t6P-UqWsN*y}LCZ5VV$CJBSUpLV zt1P4Js;B|+ksl=Q#qZfS%prO;HH(}#V zwtlhk9U5mPS8aDaPkZk+-!SluS`_)jtA{MaF5^amp+7-1&PPdm*#&t>Ayx6!d(^n* zN6lDGTa8Km1KdZ%s>aI6iplZ`vX0Wal5XM#EXxF`Y%+()gh<23FnZk(-ko0Z*TWUV z6+Ral5>!IG%VqC&&m#ADS6}CMjtce`w#n8F+@EkiIc1&-(OL>~mg&0bv}uQFh$(8k zZoFnJYeLMOEN3{Gt)sm!#5XQ-U3Gu-Jrmcd_-cG zHjqzO99C{qRZ(wM=c^lPe$XVtxp!CPP_|btQ*4wEmJw1;45SZM!lY4q$uUH2QB6Ei zs6+Q64Fy@?9o;b^3ZD%&34HY(_wMklcdv9Uf{4_McBieHZH)B*=eEqSs4bc1yXO1m z2j=VM!{+topUid4GIM?NA@fGdJ&tcHW3S=p>s;bG=6>OEdz<=C2HJ;`B1&Ej!7y}< z@TBMtd4(Ry9ut3-u(B@l!HUw#zm!!~6ICZvCsoT;byatj6_h_H*2y12%-$EtJMkCR z$^>Z~KY+fY56=y;!PEZkKEC&|dzovlbB<$)eXH%Z6|rvS zhI8$?I4;`)XP9N0Ww~XaWxhpXnPg5g4K`^_T}}5*i_JYPHMkbm-8S6u$T`RJD$s;i zRal8UPHm^h(p{OMl1H*fvaQmAk_Y05_=aSTbcAf9yp)24_rYYv0R^t;FS{zaBkm_I zWY@9B*wgGtwgJ1BO%c1;M@$2HK6w}7&_xy$N#FkFB6*b6_w*E?hqM#Akqo{$S{{6y&4J(j>wIUt8t*wzYtJor zvOC*V#{Cm4mE12}OI@8@$*xRif9EF0arP{N~IO(N@ zjEnw6U!#vgR9SWKP-!lnBiRDckeh+u@=&@`a+qyE8;H^PEwsBp3_h|KgPi}8@2j_l z_lakMr?aQI=X+0mPb1G1&rQ!Q&koOYkH=lcT@NDL);ng~=h*IAD}aR{+*r$Kv&eMV z&_~bcY8C!a*hZIN(3`}z=dQ4SM|3#0hTO{LNNGhSWkexU%$6;bRAcigIeA~?z^CFz z@J^y?1WV?T+bE2#LRX+M`Xn`&s!6q`PEq~nRuE@CK-^LCL}HTsB3UNp7zv$Dw8aOa zWBIotZ;~G?vC?p@KD~%;5o9+cg(lcSI2kJ%k!3ox2iPfSBJsQ z*jw7RTl2Y0%NcVY({n>(eP-dP!jpv;b(aj7rMx}Utq9)cjTKg)G-5_pPLZpauIM38 zmG%)or#FGji}1C=HsJfx1LUqpd`D8$F6s{Tg!(|8q?$sX#TKeIjWHFWr*@lUh%_qI z%GOGoOBS(p=+(q!;U^@M7YR=YHufL&&h@->|LE@LUg_rCi#^HSJzmnc*yr?h^7r&t z_aE_n^g28mPZRe*S4U@kM-#Y8Pqhx^5-clB(+xdzR|{U|d-Dql%IQa&R#_Li;sZk7 zpV(jICHABAuKc_rPH{u#lx$$LsfC0QKP$YAt;I%yuS`?X1mYBVh(hUlbQ@YsABLV5 znyN%?qh`~$AnJFUGmvB3lg~nlDF&y6{3J|3! zKedA1MK`B^r9$LH(nqMsBji1*JoAY?Bq<|nBEKnLFW(|FNXD}Zs9K^-==tm#ITuWY zev3Zdn%-&N9Pel!;a~6n=-2zR{7?O>{eArv{I7h?ecQZmz`FgekP|{s?OJ<3+X<_I zGh0rYO~xF3eqqIe=K1~e4;N_kIi`2EQ=ShYEfPm)Sx(wpaaK7?X_C*B{?5(-k1tfX z53PnyK~G{s@Y>L8RFzI*1~77_H{F%$Pi`Tq5WR@<w35T_enfaM?0`z4>zO*K}xhFsf%0e%}%Id-|M zr*gOIrK+m3uguPFr#gtX!#&rF>_ER@f8rO2-qg=@9D^~<=p@QRd=ym>k)kW20wROz z$EHhg`9Zi#j#I`d-b)MFnp6k;05XyH24Wh5fz-gxz=uF`ux?Nnm=MtU>-*RGD*Iaa z4*3Q{yr?3$E;u&$HE_Vs^ZDHQPM>|0t()}%x0>6>?c|a;kGa0-ong4{M!r4wRBkA5 za$$kdW%GLZ(eH#w%oy1nWgqoI^=;)vnLyl&^5VlWHHx4(mMQd#a>y2R1Ev?VpPou- z$Wx-0_%&fj$cpw8B>j;cE!`zAtxQ*TRu;Jz7?qB7*@15#B=Uw94;m;3D4V?m-Bo$GIn+Es!Qr({&D{Oyo&n#Ch7r1xObBNf_ z+say1<{|q0{5Ls*Y+3g6+}64}mUFJ5VH-A{$&_2vPvGstqZ%y7#5%Gbz71`HJVYc| zfsjuKsRp!=o=uG>vqcW!S!^|Cgg)jO#1%SM{8lztX;PI}Qz}H^kxXVh#BE_|w1Z$K zzY^cZ69Wrt3-9~ro^V>Q&@b^l_AKz6_MGx|_Kys94}Xokh0*+-k$Is%{j)sXo$G8v zImYtByw_sn>e^P?+c;j>*IL_{C+jQbkI$~2`CI0g?7jIFOq-ltLl$%>b48x3?xhuJ zhpGi<3&@xE zVf?pe^iAl5f1c;AbA$b?wSZ%+C#}P6^X%^&x1AfDOB_mjbFPn3T-YWzn0Y2WDWgmF z<$?!hg~uLM5NVP)bt?3>cs2EuO(h!Ysjw!z75#yv2+I>6s2s+?%Gu}CS^9MaT_kI$T%)R~>ZCxVZJGPTD`7e+LwBRMuw=Y9crtSMBP>mDF1j%E7WyEj)lPAmXXf zRA=%c-VbfgD;28eH+d((d-9-AljuEQJ=R2~3wH4&krBbF{zC5XL5wT9C0MZ>TxfJ02;;_Ec9&=#p45 zK2znEe5T%srsB(i2X&clCl*Myi_bH0WM>TFUjx=lqo_)-TKEU0m4swX6`d4&WlzMX zfiYkreusPLU8)|lkC{)mB$M&RNV({hpdw)N*AG??+oPuhmC=@{4&D>*Mp}mE2Gac9 z0~>>6cuM4Z@b)MS9rRCd*S6QPJTy$xzt#tgM=ULD105m99Q%38Rek@weHrf0`Ja-% zs&jZo(tVBBh>DkaRBbg?)uk01BvsfZ%vfePdq@06a$ho+MX4X~rO0&fN!SH%2nw_( zK8f5+w`QlXBbgKQFZ6ACB@z`k$Sedh3*^9jrJba3YIOVW~Ps(@|Hnd zcdo!}GMp`tWIy;4`aJYYtE^BV-*GBD6aUJdmk(4b6}4rHC8NY%aYJcO*;AQ977-Ux z-SLmeP<|44GVT&A!E*6bcn+LO>cA7W5>bP^OrH|>leJOk6lVDo3C&z4t_po<1Bk{K zVl}ae=uW{L-kwOa@UhT}@N9_Z?SPa+U%)%#QHZ(Xh1-Qrgp}c3;TvI5xElCqKXLtF zXSgFK(sX`q2dqa}qN?e;JgXnA2Y0$!-Zo&{O0cwv(hK&|+vw z1!j$mc*v&2}YlJpvk88rmY ziF#~*ssYgq?m(@G*P;u!R(J==1Gen6@bJi1-W@?rGy`3T(nu=L8@U!~4^gEA#2=01 zbI}3eq(CcgKlfedLU_X7W_!)$nCF_@MzgUe^d)pKB^y8J{>-12T{&Y}dO^mnysPGF z9$6H_j)>lnrzsdK75gNQlI7ryun(P$Bx4_iRYa3TV}#eyj?jOo7pR0B zF_h^q9wKQhX(fKatf3#$b=gMZYwRlEyLBVhVwa%@x+8ywpa#+iF$oq64)g0kg!>5a z%V~+cMh+mKfmnSm+7tYBK8H3#@9C95e?R5z?wW5O#631ugx;m;rc=->I@0VkcGiE+ zm*t2uU!)()kmt$_skUX_apA7~tH?OvBVqw#ksecq)PJfOWeaI}W*E7Lh=>*uc4D5W zj<5mp1S0W|@T&sttUX*Oext6ChsYb$L*^{JvmcgzCmkWaLsufNi8L^#+D^Cudx*A2 z;`zUWH!e`B`LhH|5DK*+=L9YIX)vnX0`5eMz-v$$c^Ta9e*{d5%kC`aa(gRlXA5TD zY|1rdnl^yOPv~bBY|CAry(DvCdh4uSg}+!5U3vb;;nMsG=v%xZU0T{y^+KHn{rI(H zDL_z(XIC=|fxmTL)EK)jXd~Dt$P!#dE5hh+d+adwmv8}boxa0v5%&SJ}0M8QnK0i-%ALE?b3+&4M`;-60e0Ra_cLX>j(us75n{G?8XvqHIn zEN{F!&RNC2#=4a&wDhnnHcvC1F_h7r%fFD@B70e;H{)E^ocwe{H>=W3)Ol z5V!!hLze?{{o8$<_lno#>Eo^gUj2>XxjN!N9j)w(Y?;>P)-l`_%R=+d#<65*5jxL|5^NqQS&R z!2gfImBOxA6SS$|9dAc;M3@)c>`U`Z^qh4cc53V$tgAQ$^zZhD-crK+*i^|h%@{Fk z*Y_%XR#?tB$}$}8=*PHW_J^)Z-p2k5f!X1qKnz`re!zE=v*5k^F|$iDR=!m+OyQ9e zicyM7isOnk@@vu>lB(jBY)u%azfKr%moP;*4_kz8MBWQV0a4_jU_PQlh9SL?rRZr) zDHOtpcL+-pz7w7TLRw`Y@NN^hd99;|!_z{wgL%Fyo^I~V&Vlw?)&-Vp=JU|2yUFlL zS5J4SP*h;aUkK(=Ti;#(#W2az(muv<%CX%=`zwd@ftkM(*(sa}Y@SYxNqkF|D*qtw zsVt+uq;9FMs4A_h17pHZ6h~xrr9VpkWVoe+4vNEw&qG3HTtmC0HZ)UeHi5 zL-0@_LYgC!knTubq#V)|X^e~qvi@8kS=%F%!gGRI{x9$}?R777uCX_=u~w4XYkp?D zYba;X=zlD%3bAT_-8uaW-Cf-S<85xY?U-$YeX_e#00H{RhsZ&}T)YfvCl}M_#O0tj zaf7m)>L>L!jahS0GgR|P{aEEwc2YX!b!CJ^27Uys=$qthQEy>iED<}0jzjkISs=w! z5Lkd{X9o||W&EG`S{Qe)4c^P!qN~E!gHwZ>gL>!>o##n`KAAhN7LKvjPTVwZ1UKG1 z(ojl&T%W3cs9UYut2?jT1(8*iENPa5)aERLi`^1`YR9&8wl1UC62-j-go$M0_C+UX!2uk6!pi@9@_o0d|R<0hW* ziGG3MqtRvPsPAi7W?s(C>`Crd*@y zrv6JkNmE&ypuG!y;30KKHL2vY2Lty*b(Ib%YX)p0=mSk(vKNB8&9e!7sg!M$qL2OMoegXJxjtX~xa{~=# z`Z?b?-wp397%`pe%7V#oG>)*XoJ|X?xJuks%XsMfd1AuMqs&2*-&7OM=Qyj{_PssF z(Zp@`n7z~ep5R6xh4&JCL0$_9@)1>*ImtejG?xFQc%(2W%Bj|>6V;{RJTWM9mAe#Y zWRs;;q2tl%>EinocjjeHDM4u<{9{TF?My%D#^)yt)I z^>q=}XUX{E}F9%9u7l{aHq9+wRMLWgs$|Mz~bjS4ssfvdg*?=nw&&uiCUc*n}KceCHJ(YA`#c3i+h zaT6@0Wszky^j)vvme{V_hFK%_Y3^(81?~dRuYtVKZxG4;mbVD`i0%@`i+lve9AHuL z81Z|_2)R?f6P{8N6-|{nvZm4ovY%j#aGZDndzP6%*QA<~FGNZ_0VZ~l0JF}(lY&1) z&q#$(gP?+8Y0l!QPQ&(Z6^Opt`me-V)Uzhf`bW*$gF~DH$xOFOdN4?0_^wVv!U| z>Oj9QU+iG^(MPDdR97-nG#Yf&Ul@-~0DrBY`KjRhT?ZnuMg~v$&-mm%uV;?ywzILT zvvZK$45O!*U1ObPv2lsE5!SI>wsn`iHAtG~JPm!NUp%e+!a!B%L1+fE8O#>6Mm54_ z_+wE#wUVZpZOm47v$&c>D|sz;iRVccN}9lv&sa7BPXsKzhrCUUCelSM@ZH!_ECbz% ztP@n^4+P);v~X(ZDm(=w`tO6UlhCuuH5tZ!o%Uh&R<`%ncGgAKoz_R(1M5`V2-{+N zdB-c~ELW0C>&f=72;BDX47GvhwkP~ANRsd(o=k3~Zc=aQpV{N$cj8ZC2gor{x%I%A+%d zlSw_uF^OKoK9}^D4wVc9CfyNfCus-i6v=0H0DG9N&Tgan6IY1m#AN7We~z9(hoY^K zL40}iNTgZRAMOyG>M!(7^7zj5KTto@1gHS{|nM@dk*eWh7>#8^{|6P_S-z^uw{iU1iuw*UU zk6p;>Xg#q?bWJo+v_Uu$9gF-4%>G`y^$}4-8_5eT3(WFW_xASQ^Hz8FbmZAGtY5j8 zAi+@c3u8~C$JE(;)^y8k<}$1=ZFc(z*DCKd-!FmMk!AcBNNHgWVk*6vohNA^tD+dL zbSMc`C6!Ed6ud4@$(^8y(c+WLG~h3GC;q~}2%ln&Ag1!EK+dlR@jvaO!iXothUj2c zAk#nB+t-76@?1k5`?y=CafS?CzVV}Ji0)1P@A}CwDq=9MGxf7RckX~uN3DN$NFg{O zJWXVfh4cwYqVk+3LEB$lT{9)_MVwAEQCUg;v;23tO8Sbf0o>ACBA2i;`n})~u%PzB zTg=sn7$z>N0p9jV*cfp8TL-@es|TujA?n)k%9?0NGBnYNjjs%S3ckyKTUgidPCvt7 zH5FPq+ef&M`ZfgXMq48ayf6J!OiPz4dTZAu{F)G#P$n@YX?MbW?Pk>;1$fg-db4@d zAW;V_2*i{+KtviEP72?TTn7IbBD6GoByu~vK6EoUFt|AQLomg^*Y&}gW*%(ZS1`7K z(;qJwmYtHbq~M*dps=*Qt=VI};Oyo-80gDS7e2t-Qd4DnG#9`}XI4ULin!>$3TtMnR~ys&OV@1nQK~}n&YiQycF*zp@v*UHeeX#yxyJ zPm+?$EG=6zWoVpD^{b+o_asj~Kz>WOpW567>I%TU~5W{PSGRl;s4%q1604_=6~H_e5p!Kaf?xXUYjx1G3KJ=rF-_U;5*x8FVEKW+DR zXnLOlJE!+8h)hFuvZke1l;={KB@Rv+UFxsoOmzzD5bhWJ5KW9EhA;aTx(E2@Mi0Wc zI7Z~Ka}+N1bIk$poe8N(`DMvTHYEDYe;H~VsO#O}C~ZA!@ffP)J;+SXnVz4VUFuWs z7dIcSeLbi^;+*M82#gh+XO)Q)%MYo5r%-X3>L0;M+KbmwyscB8Ugd1q^PskPKV+E4D zDVbN_VvqA*_0mlb^cO5frV6)9`XphMwUx`39;dx0$)a8pLxrWncIPJBTl;zUuR$Kt ziJ%$3_>rnca-dB0((1UM<$pUGq1-f-VB_dw4Bm&kG1@x^;d zFhWAa`x8ee7~=;ghf3KKCn>9vR>2#7L&0vre8G7^E$EN9%-;*#mq4JqlQ#Ft&&+6> zZpdIV_I&E`_K%mHUz)y%Y`;W0<9V_jiG`*6l`mC(Nn)WSfn>46L4kdQajbcvyD%Kb zePUqfrleD3l2CCuEhGrh+9YM&b!UWd-otyEpL9pkzsxk@1^hgJD_ia+S+?)+qL>uBsF zp-0q(3?{3p50txIC9ZsG{6@uf=|EN~LivkB%|mH|R7x+dBuQgtQ>%rC!V?|6^^%-Q z=_5bSefQhDQeQh4EHp^+-hY1dX}V!Nwob!O^d{7SGkK0ms_sQ6hnu+jxb{0fI;8&5 z{GWwkqO16nl1UVn)~582OHe))FBE;`{{nLtZA0UTT=uiPx3Z1AH9HsI6P7u~7s}HM z-Y{Hh)xo*C>qGhmYK>pRVoKH&%l#zMzg$bV$C&V4pq-m4Yn`i-VfG^@+=W)7@ zIluU(AOSicpQX8+a3w{YQa*mOd^NKKKfrq$$_lLze4xTGLh!RZ%03WP=BN0~7BX*J z+WvQs-X?w7o8Qu8Ft0HA3L1au_4Zu$<-kkvvG@l`S5w-S>XYl}3GG_DuNtCNxw%PuZ;IsTwx4ttTjD6GgMg9F2>(ILzz)xr2Wadl-2L_MNCJu59s z@&=~$ef#~}5ubVan6;I2n7yIVkvaL@lMh?Wm$Au;KNH(l>{?}93NG#^aD;CLYPxH3 zJxu$o%YAJygT$90u9#oxXz3lwXH;|iIns!K0%ji@BFMl;uu;{mC3!4#B|tJ*V)-+vTx9z{WSi0->>gI>EvE@yRzM?RjF`63GZ*N)$SjB zbKT4Ac8A&*FQ~u{k4r4~tm3`WWdLG9h0h1~g~#xh;=S01^54`0wZ6D(aeb9*32Eq^ zt+sw{&h@WnzHZGfqvzSKx~#4XHo5sk{>u-_$8BF-HDK;iPNV*)iNSPo_p?!FH zG!P!*er?>Co0^@HS4r2?+{{JzmpL06`scj=YIw8!X-3)vPYr3K(g&;Ft^c`pBw=P~ zdj58pi0SA2QI_k$W+Fn`K=o4HKfzw=mr{=vZG`7Si2E1k#XvP;iv};b_73$b%9#$qug%8Q=L+8)4w&&v9GCndue#|M>^l1Cs|psOe0>y z(xngKi@BSbPcjbW4A)D19mw~R-z7_AZIL7ZESr_oRuR0pqt6Dv#xL9AfwXD09e_?>}H*?G^==+X&D0}^r4vpSYO{zYs z@g%q%Y52X(PqOc4w8&rV$QLkdfZ5Aj6Bn>OnIG7dlH2SQ(FwtFUL8R%(Rgt)b-Tnb z2~X7nB`i@J?jThl{<4dg@(g!sY&R@9;Kw)5{KR_A(ZGRl2?Z%>72a3Oy6ISsrNs$r zUZ``tY>IeT;Do+XM)wR};S~2w zzI1Yp#NSnUba!-Rc(KQCH`=<`o%XX1x8sUEY(;Ikw$6_I&hm~QOho37?<=QwF~0Nf zl3c2+_^x)v+KRK$-9|@xyRWqhhq%Y0*>o+j9Y!4jgjl2`D=_sKA+-fJATtF{m8D%LoH9>k&k9FRUBAzJ-#hZ^ zc#=gKNtJ4bt2NNH=8LRtb3$JaWKXmmLQb>!&?}fup`t73Ol+M<&WOeH$xKX%RTSon zve{qN-4f#CC#kc=0pXiy_2B+MM_`*Q3QY}c_AYXEvo5iO&2_CKool>PeSF7(0tCjn z))oZaEHNX+RPA+z$+8BK#ayTCXJ1F<)G|E@+C+E7FC<$Ssi-k}Oz<45Nq-U7XX_Jp zg(I<9=z9?(4XQuK?bn3lD;YE9jqD5L1|9+_FFCv?v?-A2(b~InGr0!#HLm;a$rkT{m+R1U$7 zEbGI-UTh=jrkapzvFb=VatJkH&xvJp53;9dF!b{JVfLM5RjS6LY%1F&ZciQ%tP6)j zi=r0(V(cwZmzs@#7k%k9JI-=_%qUmQdC48`+-+T9dR17ZKnPc`?ZG{wY}pD$BS|i5 zb4}MR%&rf^96sk7!3DwwUU0{W8K{!Co{ysKg#AP{h`r=rl%4vCc8Xgn-YE-|uhs3< zanb?A1!OO;MI=7L@)cMm@Rl5kN|E+FK@fb)oZaoGIg!N=qXN%$l?r+oR$0GyjSjv= z50Z(Zwn$Pq+j)fBZeD7>#MN+b3Gt&EK_#pKb^Lqj8$(K;9)U1G(uOyH|2v zvQpYZ{!GzPK1sS(Y7l><0=N@1Bk4fyz9MiVrO-5FC;xFM)BPj#W$ff8Tf;D;LZWT4 zAuoTH&S6~6b@QTVCvr9Z4$(vc&Rr&3gj=e12#*zm}mgw z*A?j%G|5z8?c&SQ0{I1{QMp2qB=01B!b~QHzwMo zYYi9+^gRuWOsFN(n5I`5cbRKi=ePz(c-U`fZ$am16W=(lmoBrQlTK$^>^>H4g_k1B zkzI+U!kaLD|2;Mme^bgV5*iBZ2qa1YW2$+yGh!CjqF%ENBoo=y5ZkV$22vFngQSjPpt8C0pklCm zw`3}_lA1`$iHrCxVH!3aMPMwWG&%|0g4JHnBSz=mCrS@xF0o`q9!XM?tzc%asC}-6BZDD6%`VVMGLWN$Vpz)aQi^A zPw(F3Tm<81lx>N1K9^~xO=S%EI;SDPwQ`~UW?`6>HJt7J(e=ch0Y2LA-LHaAqhY}+ zRFBw!L2ctrLnh%eiev`@n5hS|g}g$HhJNjO;*0VQs&`6O{;N2SIxd`!8qgf!LD2)E zDQObI>mf>R zPk49eoqv+2ooj<@hi8X>RrnQuAZkQ11@{Fz1n&h#bb+V^bq}Urr`ZQ|Pncz`DcJ<( zxtJh+Cpjj)ASuO;rnKPcR0msz{UqEb><7^p50NT>651X<96BCK01|$FaBtw5ucN1L zEQZ_J&^ZA9hC3{_8P;c9J?m4O!BNWd%-{mw}|aT9*h(!$)02o#yXRzUSuso4jx-ZfmARbCN>|> zuLDf2)%>=+Tao23Q)Gf~fOiE@=yONIzMdY(OM} zfB9!2gKx#Fi84fC5h2i!vmhckl>c!>frF;=-}hvppZZ0 zfq5{pfjUzN#IW+<(bgZv>oWL*1uq4qk>$ue@ZH*rtU=l$I-r_4!Fno*x@PxE_e>C7zAP!ssrgM4@gE7FB6DdYk={V9ytQDC{2tEjjWG6 z1$JBr=xq>#0jaORD`*^Wo@BuLY6H|Qn)d>@`wgRIU=y6ETc1^6Coc1oAdE< zc^_d8cM@iCXv}W|_4V?e0|TWa5SIubo?QFJM>+z`sT)88$^kM^GO&+Y!f{cc6Rn1t zy#|`wGMF{@=g1f6D?bD>jt2tU5}=FIKq&eN$Ti;sjb$&8e98jBdogHWH4u?z@g_o) z{S=tTygRV5q&yCIIoZH9Y6N9}{3eYANFqCd5XC|)_MhNyxF1MY_kcteV{nxMyXX$H zMo$KPeGg10574e2fUM_0+Uvmlxe0`-dmyhVDgoWK2HH*!AfLr%We5S$=^1c_9s`L= z3N)lXz(!gC1pV&tn*i;;1g=ma5VRTqF>L~G8q}p5?56?ZP%iA519=wEfgJckHQ^lT z1VpZmz)GqHbQlIkFinvEHTo8)RW@K>DS_P36t=1l-&!EZ7(vRnKrTvywhRGpO9@1{ zvY=-zu)t(cIuD3a?r4n07JxbeDjZm3F3<@d*jEH>9V3)!;2VMZIzSE+Y|V!paL9)R zgYqpf_8g--`G98?2S=_5BsMj)Q~ywz@CE6@_`H$0c~p_Cl3Cz zAP)+>Dj`Ux02$Pfrhrrm78dlUg|;XQ1hz7eih|@Z{#Q20U%{iA4&iq5lCl*ZQn!LA7QUtsILoZ90EEOs1S68gFVG$tO%^KGQjm$z_Dm3GXd7? zf*rJgzlP9$<-l@Ou*763&#Ma3ln0%~!QKRL(+H4M0=e<9pBChy;K)JHof~w(gZvmV zE*_RRI6edGvHD{09otI=H7KfcJe)6Opxi1z4yy}GZLpOJP)gFbeG|UrmVczxOy0B5@XbfKtJMdt%E~Otd>?dE`-s-pZS|TxS-xJ!7m(> zgA_fqcMe!XI#@_1ELpH_0PC{Bwl>H&f@HanngMw^V0i|R7y6H3U)#5BVpbTlvDnrz zJB|_cV%F#WX7{mrcp={kspfCFu`Oc14Br<0H_I)AGKw@1Ti1WfF@D>+$g=<5s;Cwm z9FKz~rWf0{-$lP-GCRS7ifZVF@1nJsbP((glK4QYevl~$`ig)yV;?}ff$n0zVrOSe zhcR2nq3y_Tnl9FM%#K8`#Izo3%h(bl2gcer*21wr{{PA;$}egq42~9Sbpnn^d~3Iu zMKaJ%MN90QXQ18KZ|f|4OTZ>$OYs)5wAdCD{Kc*j;Dq%}x|js91^u5^R#cCoI>qW$ zyubuK-)ada@xMMXiIHzI$C6_8FV2eD6c5hX@ITUu@`@}i1o|slV(lCI<^QJH*jmw2 zlpBIG`R^qrK}?R=-l1>5VtOzB6zMRwR#bXSmqqPSq}SLPRJ0VW$7KI|iLJ$S5Nny( zQgpV(+UB22tc>DqidrqU9y=3bpQ09w9lhui(??OMMVgB39s9)O`se3wNsA`X2?c1+Tkj4@j-k}hVyMJchgSpNS`4@K$4S}xW{@p`OXiq4W) z3;bU{|EkmC@{3A~RWVj_acWU*V>K!|L;pTn@iu>_{M%ne<@{}(|2Ds9{a>Z|-*5Bp zr^f1DRR3bDEY{cG)>ovLBKs~%Ez(f&7P0S`mH(@}v9;n)Q7QkL63hL2i{dT+dwdtQ z<$n)ZN~HMzRs;W88~xAj_aD{v|BYk*N9Fxz^8Qbd@jp|q|8w^F=XLhKht&U`ME^GZ zpSJVQ-~X(|f3#2WcK>#p;`Ea5|Nm;>|4Ezwd$#por=9<_4@iYFvEv}`ak~{%Tt^m zTQBU(Ljj?N;FWSff5ar zXrM#`B^oHvK#2xQG*F^}5)G7SphN>D8Ys~~i3UnEP@;hn4U}l0L<1!nDA7QP21+zg zqJa_(lxUzt10@D8u-s? G;C}#px^@@< literal 0 HcmV?d00001 diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/assets/sample-whatstheweatherlike-en.mp3 b/sdk/cognitiveservices/azure-ai-transcription/samples/assets/sample-whatstheweatherlike-en.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e342abca6fb89dbf8cbc16b19b82f543a2ff05fc GIT binary patch literal 12276 zcmeIYcQl;Q_b)u7jKN^^(UMUk2!qi{M(>Ooy%Q~>MG#>|A1%5egy=nbP4wPdgdm7s zBBDf!aO1ar?{}@c)_w1~|Gn=YcdzxVb)NI=wVrc6=j^jT`|N#v8r=u@f5gPakat+4=d8A3rWGe*XOR>(}q!e=h&Y->a+Z z>+662GSiaRRu&Z$Mj(jLH$xF*008L0T!eY-0O0=3IIam)6>dKKe<0VVup4{`FM%ik zK(=lKTo4Jfi@59{&CA4n+Z|Hqs=ngCKE?MjB2pRH(_WeYBrA|1Vt2ZBZ5FTHKcCVN zv0d*($>-cgP;03=J6^A^1?2%KD2BHc-`!^gQe96xs8@^{h+zfRE<5F3UtQE$tLN6K zj~W`fk^=Pqp>vU~^=m-n?hfIi{H#;CG91vRu`_M4*YKRO|MT*H64C z@Q)f3DiS^#Kc@QZpT_l{$rQ5Tt(RdwK3~~3Px&2~S)n5{#d6XzVCb2?HZt&$c3QO* zXYD`|=2@C(yfvxe$%Dqsy;swB?!L<~8#G<8of-DC{=gfY?0c|~Ue@L?PA2wcC?(#~ z#_{(|0ikvU46BUoQJ6V3r%YBbs z{rm8~t66)~`?u#+AD5Wk4m940zdrTvdy61E;xS+F2WGi-S3iCi^x~sw2j>?g50>Hc zux0vua-r^z?(rCikI6H%J2O=95eclg+jmciD3 zXa|p+dGYl$?ljV?qC4!2^kzE|z5VL0nR`J#I- zUf7Uqq2_g7$cXDV;tzXod~10;h_S%J#?(2 ziK)Gb%OkCabJP&Hu&|mW5Qu?8oe6~nTo4dqVOCW{DVdl%m>?q341)EvXjuomhzKnL z0waLGM{W_D*?q;bPNI^uXh1#!Jj}`N)joUxwWP}cC@s*Z(2tG z^w;DfOaD}}&9=XbL3&r|3N_7^+iywZ<=dMnjO#(|-x^4mG6q>0(&&oIN`r+Vz23i7 zzuX;3igwc9Flh~_Rr~>OIb>KHw%xrq=w%_X)z-TltGZ{_RJMI@gzb;`NpbSl!`$%m zSJ!FCtShmLk)VC!D4|i&PAU28j?s>)F>W;7ZI;%+O4rx@X3a&CbA!Hqu7I4G10m!x z0S9whl?Zx@S>P49K~|hNo`?g_Lkr_01a})S#t@bO3V=g^_0q02^n3W!*_d(my!WO5 z0YZ{UPsy1q6mA>cPZfqW4R|qn-@)|}&1(V>nC?-Wg9^kk3Zz8oVCO2v?g!-H;RB_p zz2VP0;}J~5(KbHyDKVFb;#)T|Uy@a*szCgG#>ryL^J(cqj`2g_@rt|XR}FQg(3O!N z%M!I|eUY^+xnfK`Q}=kvuL!CQVSt=nF7@hz^P@$XRrwqt@O zg_%*DiQc`PKI*WyY`;xg-YIxL4BpxsdH%fctt+fH?uksg%!;i6+fGih@M|n8Otwa-2_wnbe73)>#r^TE?r*ajLAfW9B=zoT%CM$^Q(S5S|E5O0a*Po z-XX@t!2!s6C4&LvFIH*c%I)yGCbD!uc>^G7gH(4Tf4rVEEQO$#76L>g5Vkd69POKY z=mGXXIy(S^77zeTAq+EMrZ=FToaImwDdi2HDh0C=OVP%P1)5Rm~Wy5;-ZriAQQw*Fs6x$k&k&4VW#ld$G&^rn? zP7xi(iFLm1ph@HdaUVzM?QVfYS#4r8_CRhmwuPUJVnEr(Rnxg$Tn{h?o=yys+i& z_B5foOo@?T_*CDX^WDSB3X`^&_%w&|$GAS@56fTcnv=;xSRv_bFW>h6=v!z@)H-|0 z&umMY5GFko3c_G-60bt-v7I(UX^_ zes9$8t8843Hankt@<;$doC9HaOPURUk(n7hNzBEHIqqTVxfGlgdfL1R175PN}fc-pv=XNz-{61aJBor ztfCaeS`0xltPVXkO_Ugh%U(rMn%KDcZDEXdo1i0*EHX|S#&)3gE-{=xu~Fx|Crw%r&d;dDppCStE>J1ML!FdQo! zx(+Q(w?n5psBu6+#PSR(HD$ja@i|I+WmTe)WyOSQpt=<8^1j%<)P8oTPR&v8AIj1h zuk+VN2uE<(=y z)=mF*FrhbiUpIl;`H}Al-UY$I=N`E)DNlUQrY|l_wnt zETtD5yt3BYFj!@#uR63 zW?(H9XZ90E9klqKKNv@8rZrv$yjYB6zqtE*bPH|9*PC%s(L{a-lBR!o-6i;S@^3Xa z<KA@^*o)9t94>KzSA6Cs{9nz(NfjYYiK`=<>AB< zfIsa{H*f#eNQ6*?Q=>vzEnpCcUgqyo@;;T?k8)baMx-gyUBzdA;F zjkDpv*4m=}#ee!VH;+5d8SN1};B(g^00ZF3i=V#*A91uQg|H1DzQ2?I#s59JM0b`e zu%IV`BBIJOO1cr5HAfPsUt+AsvtM+5YSOpLw=o~l5vcOlEYE+PPus5~v?vOsLJE@* zGx90}_M3EtsWK`rKcuUx8boIH3rtF&KeJi4KO>Nif6WrkT{T^Ls3xm;=qXymR(QA* zoGX=BpWua5fRcT3)8yEDb{;njwFYqOS_hT8Gw)bAlo`%Lj^ zS$Xn>a29D?CJ$`!7p^>;Dd3eNtF3&Y0c$NlA9_?t>DkqrlE8FKf%Xs(Yx?RKt?sv^ zE7l09hj$vZ z>Jm32hK*l`de?4ql*`;-oNE5qKTJ8?cBQF)?UX%ZHuB-=0{K^gsE0J?QKoCQDaxe0 z{4N<>ZYLIo@y;Bgj20t>d>8|6nOG78*Y_0R1Y!|GoeBsnuYMvdC==%zuFlLqV_{FD zBuH;YL$EJ+bB?W;DKP{a2aD}yZsg4{N7^jny6h8%kw7k`$TUJ07|@4XQKe8mCE5-L zo3cUK#%Ud(`VX`aE?Ei?j-p5@(_}tdvLplnmLMO=6P}8r1;;oqFe8d>yh;SQ>A+}6 zO@EXyDI_K(hiHnCM#K&iJwYxY3a7^JjPc5LVwnzQ;PTkkCD#qaaZ`>oH+9IdjZru0!omcRJAAaH8g6teQIdUcL1JW*8E@E*1} z$>4_1Pu?3XkF-{|0mf0+BD#AWbwxiKh~^=u>?TWU)B1B>F(n>{k7J1V*?j>;T2M{` zq&zS8h8oFjm9tF|_)vTvsRRVdsV9}C+}lB{zz-$@Bc)$(qtP_y+?1?x?f4UiULqdU zr?n3xUbl=skI#=WP*SFb^_VANWPPxzU;wX@JYrR{pz`McD_w}oIJXmua-$eTZJJaP z=YU|vu4c5wQMh$dlM3GbT#+m}2&Cb{!bE^hif`rvUXZ`!1pxBnTdNDT&l2l~_vXj- zZJUz@SE6qA&lhtDLqzARX*eGUw-Una9rWGW0xo zP?BN<2f}#MVvl{jspO9|?-~H|bdysi9{7P@e{z_-@@~@0;;IWK4uKSO_1R_>0OZ0!ers7CntsM9nOo-Ezw2 z&-+5!gE34%coK~jqCA5Tv_Ne+J4Nq3ez)gBJ}3^`H_V3sOjhWTY91O4rUH_f%;wld z2J2I3Mve^xj;ZQaJ>aR5vKUROGHc@8=+`uEn;mZ#B`$WeY@UCbRj2Jw6v5A^NETK; z?$!|a_`?-5Q)6MQe!LMY8#(J5*_}sXuZ&by*OXPliF+`bDFQTo@f@BzT%e?~sAkzr;byN?{cWZ%_eJF%f4o`uF}Xhz7PpSH{@!it z==gOt`Htr}ei|g?rr$>)mgN8SezEZ1vBrznt2BX2!v}f9+1hRW;k=#C1$>7p!CGV} zun9yF13{3D0lN(QKY$@-Vesxk_Bgt(ye-jVSz#9%&?gdQoAPi{iNdffCAUzb# z!`?1RQUD>)iw;3XdP=-TuF`M{14>C@rW|03j7;IXV=yY53)Weg0VvB%8_CrdZAXXL z*4UT<-7cW9^$<3OZqVCY2|pF`k)5qaT8Mv^~a!fxDxn?r3VL%N=jVMU4j*;lC(-6x5BDf)z1z=J$%irQHd8zU8 z78)CK{MuL^qR?cMR`$6mLCyg2gFaRVv}%-yIlp3l=pYD~nY0(2`V)5A%4?PM$W!Q+G%0kNosLEb8cMB@e8(!MO=4Q(bSw#t zKXwT=LjX7-q}1?*lq3NgckN$EeOy9+GN^V&w0Cr$KqL}Es-Cnr8{C^+-C7;l4)A#0 zA$4lHv=HU^z}mNErUvd0KtO>EKzX)P*#7g>i69#jzNSz@QG)(n$+$JlcyY6sxc)IO#?D{oP`ZjjUD2Kc zF!lLY*VG|jSF{R{R@3qmdfqu=o17{V5iZ{yfawYdPgKIw5lV%_r13Rx%F@w#c)}{O4#KZhdRDVFF=xd5^~9;9!IerXOgZLxt7&f#v|l z6Aht?A*8PoX_Pp%iI3QUWg?}{v+LoOUULEn1`9>f!UQr61X`<<8G#01tW4lcW?T-1 zt*O1mq}2HAatEksBoT-n4znS8Yut*aAtNqckH9vXNPlqA=Sr35Tl2HM`}L_IozaS| z-U9n4dwrgIl5X!>3@MyPBijbWgvGo~ECqM1BT9L}6fSFd&b;?+Yz*>Q`4#o&IW@qB zeV%+aQ^L;ZvYbMTG-5Z=GI=PeKo0%UA!D`L*Y3EY5M^T~q15C?7#)#C1Bxh8U!dED zt`~u7O${fXO(NaeKu8)dz;1m&qu2rS0_zC64%dN60}=f*eoglisi)^G%?j1)O`Y0+ zy!*JzNSg~vZl>22BM=$y*DJEsKc1bIjHc1A!#UVbtlURsV+g~6d|`3j@dfEi ziG*w>T$cRg^XAw*Cn>#2+5RnRS2M#yK%ExXV7sJoY%Uv1t29kxN{pZaKg9FI#6);7(9_C6< zL{=xL1U7)~g<}EJ(Kbw>_EIOMaHuSz#R?1=`vX_P)<0sT1!JdCW&ClhY!CrJT!M|U zZ4w9xW`1GVhO~je*Ecv2AOXc=)@ll+Gdwb!fyfi;*+Tpk{hvDl~%(A`lPEH9UwY;B1jaD48Ti8!$3i8m&pG{uiFRa62+YBLBnCE1RVmP z4L9P_qHXR*@M(yRWHjZG)lm5rlkzOz+UAKo>X``5^}69m6XMg!=Q^cJ@Kd#?9)X@K6kkh2~WAtv_g=ofz)%UIuDLQu_Xk=Zj z)zGF#q=C~zDj6eAsF5@PicM>eQ$X*_WCg4b-6BnD_bRTLr=yf1&_W*x2ZHkQDg@s9 z_+CGk{i?lFVY;qg_v)Pxxt&uyb(W%MujH0!3CDY`)aKL^ydbwwe7oRT2R~O2zCAV@ zLf|+k4GF1@4>T?n-ix*;3mYOhD?-Ql-uQw#H(3Vklh^BT6%|6z(kwdx{TfOZ4$l5w zTxSa%d)EaJwuv=mfTGxK=r782#Ao)AQH_kz7y?WIDaL@3wMc+y?O7g?EChrD((diX z_L;oXG9hPv`2sgo(aht&{!{EDe)u|(ux)gnm7bKF|~(A+Cm;TY4lf<5_gUy(OEV{7%3Hf|M3ij#bkUkbkSeeb(zjR zcox8r@-!Qh(Tj{8DDbOLzQv?z5LIe_M(Ilh?AsY*WFJh&l? z-adIf4)rmrfihk|tTuIBzp6qcuO-aJ8w5?y^QWsq=Mz()r;0v|2rgp*r0G`auUt2t zMTIM81XTCd>wn-Uh-~GU;UigpoF~gpv~M=0l+P-n$i1)%oJckHTk~EPY%(Va((ctb zpE?=}Y3V$ieyg~!W0#ERdvmlkp+8XZ;p5^&(^Id%9xIn#pF?iAO{u(SThNo`Az+$C z^T=w%XXE15H10t12Od{U>lxmot*-MS=_Y@z4np4BcaHu^kaT0SDs$c0$#}Apv0biJY*-@8qA%SN|~R)dD`cM{3Rnqlj~-Bj|liP8sFg|NrIF4WxHka z+e%#E+-_h_s6f+1=mwuAIZX}E;%!qXif+eH?l0w8)y!L$PueoR4tMw~00{?*0`MZ-^D1-YC}ARv^bz!>2qF(tp#(b753nSQJI1 zE#PEvSih_1u57H#wI5_|7+{(=oy1%v$grNB%_Meekw^nTbYG4{aXeaB)3T=T9Kv5c-fY*}q#6t|wU%cI)~|BE0>% zqR8Shii$6ad<9yN{*^1K+4&ZFGF_0%mSf)}@xq0UnztP;>91O-RCrzfds4PrfrLC# zKrV1OKe za)w<%n?xV(=SVy1y!6jD?@$EYnLfH8jk7DYkEkv>two24X2?4yf!4PU0_ruLeC6fx z@~Xg}@qiicn&@iV#cbd0uEJLD2jO|+8iszOn-KXkv}#sN3Hgx#g}9a3i66{@xUIW( znS@cJQCld!eUb^B0RrHxP99(tyYu;avkz>Y`hjjgIc$cy47@RkjMzP~T=|b;@bu zQ}H-K?#>le^}JR!GZ*zBe6nI{#Gl@K$H9wbvQU^ECq2#M6mxG-rPgQ(+_PXe3or`ctIk6fcOvcyTmr3QL?xGuJc zN)pAw-crlRK49Ty!z|L#|3#qds^YP{3i?ZUzM zQu_4v#;umQr&Yo2$lsqY1H5|On)bYB4h?-@P2^}U9DEB&Gp`R&?^p;?u|ujo3(meL zI&|kv_4;RFF|nqGE$4Bl;a+R{!CdWxyT#v?&+WaIW7}DY$#-z1oGx?{WQL+YR!?3D zUs?I7y^H#c^Fx%A&PXkuHa+;cv{Zln$Lda0cci_PwAC>q-@m+!f8T`YtNCK%nenox zUZTSuip)zx8~?IWxl@HZhU9*qy7KT!=#Ybs7wLp{B1=#|%Ew0&U}f7-Bd)Eqh#{Nm zxR)keKU4U4J|x|lsY;m{)BSeIbtZTH-aPQ9RC=~s(@Y?9inolcY;I{li>Hz&N-!IJ zCJc#gTKk-5Jras zzP#)2VG(fI@g`M_i-8bH)_qV$5=V`FK@LYT69xR&nIQ6fpxAhH>Q?|BwHOo61lyPl zPH$k&C|6!cnttfU_emUNZkNMufvL5Zki$y3TI3>SMwSi;%m*!_2RyF_ssx%(Rz_S5 zzkLI{TKv)b=WQI7=OOgur+jJR%JWK$R)LuZ0Y*qc^nA9n%gC!iYcr#eSJ#)#VyYbT6{as-e9Nz7JI$L~-`=e0H#yNCxK;Bm;H8WA z#+ESOw?Tj~wder+g#*D=aNlag0vrggO5uyMM@OQj3W;5AG_?N_HM<-&TQWL<LZQUc9 zj9?O+WW<1xFF^yt#v`UfmTljO{P>C#3Y9NNoJHH-qP=iQCxxVNvGJ8y=I`HL1$8RZ zX1P1^lNgtRqyxIcdjkQ2D%qu!jBzp~4F?G~_P%E@MyX?+Jp?>7TFLGBD}JZ`ZnW4B z|CP3Y-DS(Gq&{<5LdoUZzud+5-+K?O$ZjUbe3mVKU)=O(;Cr*~!piff-o=fI5-hF! zp-(+>o6lwLmgz=`)Vs-C_Pp1aHQM9lmfT<)`5JS(UR!YU+AZ<}uKB%{PIF)yIN}+5 zV0SWzR#=%0<@_ce$R7_v$k$0_>V0I#u($Klb=^`%r3}GE$?eO4V5LS#wJBVz%$RA> zIV@WPIz~|=Uz{8Rxu=DZFChp8gozU&1vpSd3q8BUh*9WkO7?rxa;T543dCV*l9Fsp z4rC+*d`gJ=(zC>41JZB-2y`Do^ja)j>ql*IgFP7?X3%g30QQt7vJ)zMN@u$19PgEw zQEjiDQ+(dbswrY+GXhSOn-bu=qh1{2F_FAmLIFXK z`A1*!K5~1ppqN$DS!K13XMQ)S6_PVJiorh;@U-TtQ4$s_f~M)< zO@AvNS-xtg+PG$k)4VqQRA}njKoOgtd3b(ku4~wvM9?+SYY@s!xA;)8UeV1rt*~h` zHR!FTu6q05$uy(Zg-yLWNR^fOOU|G5!jvWM8r=G^uIkCL1Mi0Ws6RQEKZ@?9-&$r5 zRiMEd_Od_Jcyi`yP@2MsTIAz0Pf|AcVaqJ0AXrM$7e!UgEy>L1bcaGkP&wJm=b?zs z?GL*dnpIkF%#j}-mp9{9JrK&}Tl5b-7nBDI!u2g+b1To;&o{1YL zE-5Ak9i+rsh2F-;G4jOp=j<8E-JDS$1w|*atS8lgEK#N`=;cyFGog%ogD$%TDxB7; zo;cBkq%z+*UbE*bD}Q``E2enaNr^D^d=PdHrbL@2)8cc?U81->@X+}MkES^vGZU*Z z|5*B=^-ytj9UiDs?@7M)IqyMT%(Hyky4Uos+G!?fD$ORXye1fTqR7xU`A8Cu3ds9& ze!Zs#m)4tQ1t3gm3>ySNNTS9Ust?~ytFU(d$1@M7pO_}Cl#g31WgS9_l&AB`kOXau z6H2I{xDes`Ogw$HYC zQGiV5E5O#emX}V?S?bjPSUs(LZ^06z!5#Nt&+gsMZ}E-jSC#b)ebBUJ=x{m3c)}=E zvL^pvayOT{?0pTow78fa0~C&3gkw!@7-;}GjUJMx7P-kmAKnZ5?0VmR8hiKg6Lp$V zvaA%tIV0|V3>2^AOiXLx%{SMSwO<~Q%v$oMZ$HyFXMm0!Ro7+Ms}mzN_*cL9WuuWn;)!-QN?&K9~#LaXI!;fgZh< zhWx$J_TZ>gR-;?1Z_BG{c3-{yRZhcXik0-c_0WdfT@K>cpl+ zb&{X9RP&Ijl(m3Mj;*ldyM||HEHtW#?tV31v^V=_Mj(h%B{)!Pkz{-BkbGV|)t4pR zl&?y^Ww>yUzE{mOAuvnWX^oy*uhz~;D}&~Z`JF;DUvzwo+lX$QqrRpiQ(cTU$HhaB zWHn=5e%snVG3nW+#`A3#Y8e(A(_o7zva$M)l>-&M93puf#v<2jhOxV8`^QY4yByN* zAgt~nCzT>f(>c0h7@mS^eOJp1 zYxE!aUv%B9#R32G&mtCfs)jd;{|lY}zjfc#0B;iGL3A}>0N}qXmH#ux|7vK-|Ci3c vI$^b&8s-0u&hG!!`G3L3$mj;c|KRgK1N@)2|Eu%gd+a}m{LhX56MX&$wq&_} literal 0 HcmV?d00001 diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_audio_file_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_audio_file_async.py index 8e73f72d5a64..72b750c213a0 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_audio_file_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_audio_file_async.py @@ -32,10 +32,18 @@ async def sample_transcribe_audio_file_async(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # Path to your audio file import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_from_url_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_from_url_async.py index d4f8fbbc83b6..ce71ae7d4a67 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_from_url_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_from_url_async.py @@ -32,10 +32,18 @@ async def sample_transcribe_from_url_async(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # URL to your audio file (must be publicly accessible) audio_url = "https://example.com/path/to/audio.wav" diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_multiple_languages_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_multiple_languages_async.py index 431398c6c2fd..7d5d384ef465 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_multiple_languages_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_multiple_languages_async.py @@ -9,9 +9,21 @@ FILE: sample_transcribe_multiple_languages_async.py DESCRIPTION: - This sample demonstrates how to asynchronously transcribe an audio file with - multiple language detection using the Azure AI Transcription client. - This is useful for multilingual content. + This sample demonstrates how to transcribe audio with multilingual content + using the asynchronous Azure AI Transcription client. + + When your audio contains multilingual content that switches between different + languages, use the multilingual transcription model by NOT specifying any + locales. The service will automatically detect and transcribe each language + segment. + + Supported locales: + de-DE, en-AU, en-CA, en-GB, en-IN, en-US, es-ES, es-MX, fr-CA, fr-FR, + it-IT, ja-JP, ko-KR, zh-CN + + Note: This feature is currently in preview. The multilingual model outputs + the "major locale" for each language (e.g., always "en-US" for English + regardless of accent). USAGE: python sample_transcribe_multiple_languages_async.py @@ -19,34 +31,50 @@ Set the environment variables with your own values before running the sample: 1) AZURE_SPEECH_ENDPOINT - the endpoint to your Speech resource. 2) AZURE_SPEECH_API_KEY - your Speech API key. + +RELATED RESOURCES: + - Fast transcription - Multilingual transcription: + https://learn.microsoft.com/azure/ai-services/speech-service/fast-transcription-create?tabs=multilingual-transcription-on """ import asyncio import os +import pathlib -async def sample_transcribe_multiple_languages_async(): - # [START transcribe_multiple_languages_async] +async def sample_transcribe_multilingual_async(): + """Transcribe audio with multilingual content (Preview). + + For multilingual content, do not specify any locales. The service will + automatically detect and transcribe each language segment. + """ + # [START transcribe_multilingual_async] from azure.core.credentials import AzureKeyCredential from azure.ai.transcription.aio import TranscriptionClient from azure.ai.transcription.models import TranscriptionContent, TranscriptionOptions # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] - # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: - # Path to your audio file with multiple languages - import pathlib + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + credential = DefaultAzureCredential() + + # Create the transcription client + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: + # Path to your audio file with multilingual content audio_file_path = pathlib.Path(__file__).parent.parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create transcription options with multiple language candidates - # The service will detect which language is being spoken - options = TranscriptionOptions(locales=["en-US", "es-ES", "fr-FR", "de-DE"]) # Multiple candidates + # For multilingual content, do NOT specify any locales + # The service will automatically detect and transcribe each language + options = TranscriptionOptions() # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -55,15 +83,12 @@ async def sample_transcribe_multiple_languages_async(): result = await client.transcribe(request_content) # Print the transcription result with locale information - print("Transcription with language detection:\n") - if result.phrases: - for phrase in result.phrases: - locale = phrase.locale if hasattr(phrase, "locale") and phrase.locale else "detected" - print(f"[{locale}] {phrase.text}") - else: - print(f"Full transcription: {result.combined_phrases[0].text}") - # [END transcribe_multiple_languages_async] + print("Multilingual Transcription:\n") + for phrase in result.phrases: + locale = phrase.locale if phrase.locale else "auto-detected" + print(f"[{locale}] {phrase.text}") + # [END transcribe_multilingual_async] if __name__ == "__main__": - asyncio.run(sample_transcribe_multiple_languages_async()) + asyncio.run(sample_transcribe_multilingual_async()) diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_diarization_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_diarization_async.py index 447d70ba3f77..0f791a858567 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_diarization_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_diarization_async.py @@ -37,10 +37,18 @@ async def sample_transcribe_with_diarization_async(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # Path to your audio file with multiple speakers import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_enhanced_mode_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_enhanced_mode_async.py index 4fc51688bf13..5ae02b13ac5e 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_enhanced_mode_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_enhanced_mode_async.py @@ -9,9 +9,29 @@ FILE: sample_transcribe_with_enhanced_mode_async.py DESCRIPTION: - This sample demonstrates how to transcribe an audio file with enhanced mode enabled - using the asynchronous Azure AI Transcription client. Enhanced mode provides - advanced capabilities such as translation or summarization during transcription. + This sample demonstrates how to use LLM-powered Enhanced Mode for transcription + and translation using the asynchronous Azure AI Transcription client. Enhanced + Mode uses LLM-powered speech recognition to provide improved transcription + accuracy, real-time translation, prompt-based customization, and multilingual + support with GPU acceleration. + + Supported Tasks: + +-------------+--------------------------------------------------------------+ + | Task | Description | + +-------------+--------------------------------------------------------------+ + | transcribe | Transcribe audio in the input language (auto-detected or | + | | specified) | + | translate | Translate audio to a specified target language | + +-------------+--------------------------------------------------------------+ + + Limitations: + - `confidence` is not available and always returns 0 + - Word-level timing (offset_milliseconds, duration_milliseconds) is not + supported for the `translate` task + - Diarization is not supported for the `translate` task (only speaker1 + label is returned) + - `locales` and `phrase_lists` options are not required or applicable + with Enhanced Mode USAGE: python sample_transcribe_with_enhanced_mode_async.py @@ -19,13 +39,25 @@ Set the environment variables with your own values before running the sample: 1) AZURE_SPEECH_ENDPOINT - the endpoint to your Speech resource. 2) AZURE_SPEECH_API_KEY - your Speech API key. + +RELATED RESOURCES: + - LLM speech for speech transcription and translation (preview): + https://learn.microsoft.com/azure/ai-services/speech-service/llm-speech + - Fast transcription: + https://learn.microsoft.com/azure/ai-services/speech-service/fast-transcription-create """ import asyncio import os +import pathlib async def sample_transcribe_with_enhanced_mode_async(): + """Transcribe audio using Enhanced Mode for improved quality. + + Use Enhanced Mode for improved transcription quality with LLM-powered + speech recognition. + """ # [START transcribe_with_enhanced_mode_async] from azure.core.credentials import AzureKeyCredential from azure.ai.transcription.aio import TranscriptionClient @@ -37,30 +69,139 @@ async def sample_transcribe_with_enhanced_mode_async(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # Path to your audio file - import pathlib - audio_file_path = pathlib.Path(__file__).parent.parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create enhanced mode properties - # Enable enhanced mode for advanced processing capabilities + # Enhanced mode is automatically enabled when task is specified + enhanced_mode = EnhancedModeProperties(task="transcribe") + + # Create transcription options with enhanced mode + options = TranscriptionOptions(enhanced_mode=enhanced_mode) + + # Create the request content + request_content = TranscriptionContent(definition=options, audio=audio_file) + + # Transcribe the audio with enhanced mode + result = await client.transcribe(request_content) + + # Print the transcription result + print(result.combined_phrases[0].text) + # [END transcribe_with_enhanced_mode_async] + + +async def sample_translate_with_enhanced_mode_async(): + """Translate speech to another language using Enhanced Mode. + + Translate speech to a target language during transcription. Specify the + target language using the language code (e.g., `en` for English, `ko` for + Korean, `es` for Spanish). + """ + # [START translate_with_enhanced_mode_async] + from azure.core.credentials import AzureKeyCredential + from azure.ai.transcription.aio import TranscriptionClient + from azure.ai.transcription.models import ( + TranscriptionContent, + TranscriptionOptions, + EnhancedModeProperties, + ) + + # Get configuration from environment variables + endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() + + # Create the transcription client + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: + # Path to your audio file (e.g., Chinese audio) + audio_file_path = pathlib.Path(__file__).parent.parent / "assets" / "sample-howstheweather-cn.wav" + + # Open and read the audio file + with open(audio_file_path, "rb") as audio_file: + # Translate Chinese speech to Korean enhanced_mode = EnhancedModeProperties( - task="translation", # Specify the task type (e.g., "translation", "summarization") - target_language="es-ES", # Target language for translation - prompt=[ - "Translate the following audio to Spanish", - "Focus on technical terminology", - ], # Optional prompts to guide the enhanced mode + task="translate", + target_language="ko", # Translate to Korean ) # Create transcription options with enhanced mode - options = TranscriptionOptions(locales=["en-US"], enhanced_mode=enhanced_mode) + options = TranscriptionOptions(enhanced_mode=enhanced_mode) + + # Create the request content + request_content = TranscriptionContent(definition=options, audio=audio_file) + + # Transcribe and translate the audio + result = await client.transcribe(request_content) + + # Print the translated result + print("Translated to Korean:") + print(result.combined_phrases[0].text) + # [END translate_with_enhanced_mode_async] + + +async def sample_enhanced_mode_with_prompts_async(): + """Use prompts to guide output format and improve recognition. + + Provide prompts to improve recognition or control output format. Prompts + are optional text that guides the output style for `transcribe` or + `translate` tasks. + """ + # [START enhanced_mode_with_prompts_async] + from azure.core.credentials import AzureKeyCredential + from azure.ai.transcription.aio import TranscriptionClient + from azure.ai.transcription.models import ( + TranscriptionContent, + TranscriptionOptions, + EnhancedModeProperties, + ) + + # Get configuration from environment variables + endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() + + # Create the transcription client + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: + # Path to your audio file + audio_file_path = pathlib.Path(__file__).parent.parent / "assets" / "sample-whatstheweatherlike-en.mp3" + + # Open and read the audio file + with open(audio_file_path, "rb") as audio_file: + # Guide output formatting using prompts + enhanced_mode = EnhancedModeProperties( + task="transcribe", + prompt=["Output must be in lexical format."], + ) + + # Create transcription options with enhanced mode + options = TranscriptionOptions(enhanced_mode=enhanced_mode) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -69,16 +210,99 @@ async def sample_transcribe_with_enhanced_mode_async(): result = await client.transcribe(request_content) # Print the transcription result - print("Transcription with enhanced mode:") - print(f"{result.combined_phrases[0].text}") - - # Print individual phrases if available - if result.phrases: - print("\nDetailed phrases:") - for phrase in result.phrases: - print(f" [{phrase.offset_milliseconds}ms]: {phrase.text}") - # [END transcribe_with_enhanced_mode_async] + print(result.combined_phrases[0].text) + # [END enhanced_mode_with_prompts_async] + + +async def sample_enhanced_mode_with_diarization_async(): + """Combine Enhanced Mode with diarization and profanity filtering. + + Enhanced Mode can be combined with other transcription options like + `diarization`, `profanity_filter_mode`, and `channels` for comprehensive + transcription scenarios such as meeting transcription. + + Note: Diarization is only supported for the `transcribe` task, not for + `translate`. + """ + # [START enhanced_mode_with_diarization_async] + from azure.core.credentials import AzureKeyCredential + from azure.ai.transcription.aio import TranscriptionClient + from azure.ai.transcription.models import ( + TranscriptionContent, + TranscriptionOptions, + EnhancedModeProperties, + TranscriptionDiarizationOptions, + ) + + # Get configuration from environment variables + endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() + + # Create the transcription client + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: + # Path to your audio file (e.g., a meeting recording) + audio_file_path = pathlib.Path(__file__).parent.parent / "assets" / "audio.wav" + + # Open and read the audio file + with open(audio_file_path, "rb") as audio_file: + # Configure enhanced mode with prompts + enhanced_mode = EnhancedModeProperties( + task="transcribe", + prompt=["Output must be in lexical format."], + ) + + # Configure diarization to identify different speakers + diarization_options = TranscriptionDiarizationOptions(max_speakers=2) + + # Create transcription options with enhanced mode, diarization, and profanity filter + options = TranscriptionOptions( + enhanced_mode=enhanced_mode, + profanity_filter_mode="Masked", + diarization_options=diarization_options, + ) + + # Create the request content + request_content = TranscriptionContent(definition=options, audio=audio_file) + + # Transcribe the audio with enhanced mode + result = await client.transcribe(request_content) + + # Print transcription with speaker information + for phrase in result.phrases: + speaker = phrase.speaker if phrase.speaker is not None else "Unknown" + print(f"[Speaker {speaker}] {phrase.text}") + # [END enhanced_mode_with_diarization_async] + + +async def main(): + print("=" * 60) + print("Sample 1: Transcribe with Enhanced Mode (Async)") + print("=" * 60) + await sample_transcribe_with_enhanced_mode_async() + + print("\n" + "=" * 60) + print("Sample 2: Translate with Enhanced Mode (Async)") + print("=" * 60) + await sample_translate_with_enhanced_mode_async() + + print("\n" + "=" * 60) + print("Sample 3: Enhanced Mode with Prompt Tuning (Async)") + print("=" * 60) + await sample_enhanced_mode_with_prompts_async() + + print("\n" + "=" * 60) + print("Sample 4: Combine Enhanced Mode with Other Options (Async)") + print("=" * 60) + await sample_enhanced_mode_with_diarization_async() if __name__ == "__main__": - asyncio.run(sample_transcribe_with_enhanced_mode_async()) + asyncio.run(main()) diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_phrase_list_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_phrase_list_async.py index bf04baf2c8c4..fdbc989ae325 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_phrase_list_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_phrase_list_async.py @@ -9,9 +9,17 @@ FILE: sample_transcribe_with_phrase_list_async.py DESCRIPTION: - This sample demonstrates how to asynchronously transcribe an audio file with a - custom phrase list to improve recognition accuracy for domain-specific terminology - using the Azure AI Transcription client. + This sample demonstrates how to use custom phrase lists to improve transcription + accuracy with the asynchronous Azure AI Transcription client. + + A phrase list allows you to provide domain-specific terms, product names, + technical jargon, or other words that may not be well-recognized by the + default speech model. This improves accuracy for specialized content. + + For example, without a phrase list: + - "Jessie" might be recognized as "Jesse" + - "Rehaan" might be recognized as "everyone" + - "Contoso" might be recognized as "can't do so" USAGE: python sample_transcribe_with_phrase_list_async.py @@ -23,9 +31,11 @@ import asyncio import os +import pathlib async def sample_transcribe_with_phrase_list_async(): + """Transcribe audio with a custom phrase list to improve recognition accuracy.""" # [START transcribe_with_phrase_list_async] from azure.core.credentials import AzureKeyCredential from azure.ai.transcription.aio import TranscriptionClient @@ -37,33 +47,31 @@ async def sample_transcribe_with_phrase_list_async(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # Path to your audio file with domain-specific terminology - import pathlib - audio_file_path = pathlib.Path(__file__).parent.parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create a phrase list with custom terminology - # This helps improve recognition accuracy for specific words + # Add custom phrases to improve recognition of names and domain-specific terms + # For example, "Jessie" might be recognized as "Jesse", or "Contoso" as "can't do so" phrase_list = PhraseListProperties( - phrases=[ - "Azure", - "Cognitive Services", - "Speech SDK", - "TranscriptionClient", - "Kubernetes", - "microservices", - ], - biasing_weight=5.0, # Weight between 1.0 and 20.0 (higher = more bias) + phrases=["Contoso", "Jessie", "Rehaan"] ) # Create transcription options with phrase list - options = TranscriptionOptions(locales=["en-US"], phrase_list=phrase_list) + options = TranscriptionOptions(phrase_list=phrase_list) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -73,13 +81,7 @@ async def sample_transcribe_with_phrase_list_async(): # Print the transcription result print("Transcription with custom phrase list:") - print(f"{result.combined_phrases[0].text}") - - # Print individual phrases if available - if result.phrases: - print("\nDetailed phrases:") - for phrase in result.phrases: - print(f" [{phrase.offset_milliseconds}ms]: {phrase.text}") + print(result.combined_phrases[0].text) # [END transcribe_with_phrase_list_async] diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_profanity_filter_async.py b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_profanity_filter_async.py index 2b7a953d5d65..bd34e984e21c 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_profanity_filter_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/async_samples/sample_transcribe_with_profanity_filter_async.py @@ -33,10 +33,18 @@ async def sample_transcribe_with_profanity_filter_async(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity.aio import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - async with TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) as client: + async with TranscriptionClient(endpoint=endpoint, credential=credential) as client: # Path to your audio file import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_audio_file.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_audio_file.py index 78c037ddc011..1156c2fc7acc 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_audio_file.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_audio_file.py @@ -31,10 +31,18 @@ def sample_transcribe_audio_file(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_from_url.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_from_url.py index 4bb8c18479f9..5832739a4063 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_from_url.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_from_url.py @@ -31,10 +31,18 @@ def sample_transcribe_from_url(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + client = TranscriptionClient(endpoint=endpoint, credential=credential) # URL to your audio file (must be publicly accessible) audio_url = "https://example.com/path/to/audio.wav" diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_multiple_languages.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_multiple_languages.py index 46af6dcdd09e..d83580877c5c 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_multiple_languages.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_multiple_languages.py @@ -9,9 +9,21 @@ FILE: sample_transcribe_multiple_languages.py DESCRIPTION: - This sample demonstrates how to transcribe an audio file with multiple language - detection using the Azure AI Transcription client. This is useful for - multilingual content. + This sample demonstrates how to transcribe audio with multilingual content + using the Azure AI Transcription client. + + When your audio contains multilingual content that switches between different + languages, use the multilingual transcription model by NOT specifying any + locales. The service will automatically detect and transcribe each language + segment. + + Supported locales: + de-DE, en-AU, en-CA, en-GB, en-IN, en-US, es-ES, es-MX, fr-CA, fr-FR, + it-IT, ja-JP, ko-KR, zh-CN + + Note: This feature is currently in preview. The multilingual model outputs + the "major locale" for each language (e.g., always "en-US" for English + regardless of accent). USAGE: python sample_transcribe_multiple_languages.py @@ -19,34 +31,50 @@ Set the environment variables with your own values before running the sample: 1) AZURE_SPEECH_ENDPOINT - the endpoint to your Speech resource. 2) AZURE_SPEECH_API_KEY - your Speech API key. + +RELATED RESOURCES: + - Fast transcription - Multilingual transcription: + https://learn.microsoft.com/azure/ai-services/speech-service/fast-transcription-create?tabs=multilingual-transcription-on """ import os +import pathlib -def sample_transcribe_multiple_languages(): - # [START transcribe_multiple_languages] +def sample_transcribe_multilingual(): + """Transcribe audio with multilingual content (Preview). + + For multilingual content, do not specify any locales. The service will + automatically detect and transcribe each language segment. + """ + # [START transcribe_multilingual] from azure.core.credentials import AzureKeyCredential from azure.ai.transcription import TranscriptionClient from azure.ai.transcription.models import TranscriptionContent, TranscriptionOptions # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] - # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential - # Path to your audio file with multiple languages - import pathlib + credential = DefaultAzureCredential() + + # Create the transcription client + client = TranscriptionClient(endpoint=endpoint, credential=credential) + # Path to your audio file with multilingual content audio_file_path = pathlib.Path(__file__).parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create transcription options with multiple language candidates - # The service will detect which language is being spoken - options = TranscriptionOptions(locales=["en-US", "es-ES", "fr-FR", "de-DE"]) # Multiple language candidates + # For multilingual content, do NOT specify any locales + # The service will automatically detect and transcribe each language + options = TranscriptionOptions() # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -55,15 +83,12 @@ def sample_transcribe_multiple_languages(): result = client.transcribe(request_content) # Print the transcription result with locale information - print("Transcription with language detection:\n") - if result.phrases: - for phrase in result.phrases: - locale = phrase.locale if hasattr(phrase, "locale") and phrase.locale else "detected" - print(f"[{locale}] {phrase.text}") - else: - print(f"Full transcription: {result.combined_phrases[0].text}") - # [END transcribe_multiple_languages] + print("Multilingual Transcription:\n") + for phrase in result.phrases: + locale = phrase.locale if phrase.locale else "auto-detected" + print(f"[{locale}] {phrase.text}") + # [END transcribe_multilingual] if __name__ == "__main__": - sample_transcribe_multiple_languages() + sample_transcribe_multilingual() diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_diarization.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_diarization.py index 8cf35504bb61..4ffe2c28d133 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_diarization.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_diarization.py @@ -36,10 +36,18 @@ def sample_transcribe_with_diarization(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file with multiple speakers import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_enhanced_mode.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_enhanced_mode.py index 5eed28c6b5df..1d6b2899580a 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_enhanced_mode.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_enhanced_mode.py @@ -9,9 +9,29 @@ FILE: sample_transcribe_with_enhanced_mode.py DESCRIPTION: - This sample demonstrates how to transcribe an audio file with enhanced mode enabled. - Enhanced mode provides advanced capabilities such as translation or summarization - during transcription using the Azure AI Transcription client. + This sample demonstrates how to use LLM-powered Enhanced Mode for transcription + and translation using the Azure AI Transcription client. Enhanced Mode uses + LLM-powered speech recognition to provide improved transcription accuracy, + real-time translation, prompt-based customization, and multilingual support + with GPU acceleration. + + Supported Tasks: + +-------------+--------------------------------------------------------------+ + | Task | Description | + +-------------+--------------------------------------------------------------+ + | transcribe | Transcribe audio in the input language (auto-detected or | + | | specified) | + | translate | Translate audio to a specified target language | + +-------------+--------------------------------------------------------------+ + + Limitations: + - `confidence` is not available and always returns 0 + - Word-level timing (offset_milliseconds, duration_milliseconds) is not + supported for the `translate` task + - Diarization is not supported for the `translate` task (only speaker1 + label is returned) + - `locales` and `phrase_lists` options are not required or applicable + with Enhanced Mode USAGE: python sample_transcribe_with_enhanced_mode.py @@ -19,12 +39,24 @@ Set the environment variables with your own values before running the sample: 1) AZURE_SPEECH_ENDPOINT - the endpoint to your Speech resource. 2) AZURE_SPEECH_API_KEY - your Speech API key. + +RELATED RESOURCES: + - LLM speech for speech transcription and translation (preview): + https://learn.microsoft.com/azure/ai-services/speech-service/llm-speech + - Fast transcription: + https://learn.microsoft.com/azure/ai-services/speech-service/fast-transcription-create """ import os +import pathlib def sample_transcribe_with_enhanced_mode(): + """Transcribe audio using Enhanced Mode for improved quality. + + Use Enhanced Mode for improved transcription quality with LLM-powered + speech recognition. + """ # [START transcribe_with_enhanced_mode] from azure.core.credentials import AzureKeyCredential from azure.ai.transcription import TranscriptionClient @@ -36,31 +68,142 @@ def sample_transcribe_with_enhanced_mode(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file - import pathlib - audio_file_path = pathlib.Path(__file__).parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create enhanced mode properties - # Enable enhanced mode for advanced processing capabilities + # Enhanced mode is automatically enabled when task is specified + enhanced_mode = EnhancedModeProperties(task="transcribe") + + # Create transcription options with enhanced mode + options = TranscriptionOptions(enhanced_mode=enhanced_mode) + + # Create the request content + request_content = TranscriptionContent(definition=options, audio=audio_file) + + # Transcribe the audio with enhanced mode + result = client.transcribe(request_content) + + # Print the transcription result + print(result.combined_phrases[0].text) + # [END transcribe_with_enhanced_mode] + + +def sample_translate_with_enhanced_mode(): + """Translate speech to another language using Enhanced Mode. + + Translate speech to a target language during transcription. Specify the + target language using the language code (e.g., `en` for English, `ko` for + Korean, `es` for Spanish). + """ + # [START translate_with_enhanced_mode] + from azure.core.credentials import AzureKeyCredential + from azure.ai.transcription import TranscriptionClient + from azure.ai.transcription.models import ( + TranscriptionContent, + TranscriptionOptions, + EnhancedModeProperties, + ) + + # Get configuration from environment variables + endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() + + # Create the transcription client + client = TranscriptionClient(endpoint=endpoint, credential=credential) + + # Path to your audio file (e.g., Chinese audio) + audio_file_path = pathlib.Path(__file__).parent / "assets" / "sample-howstheweather-cn.wav" + + # Open and read the audio file + with open(audio_file_path, "rb") as audio_file: + # Translate Chinese speech to Korean + enhanced_mode = EnhancedModeProperties( + task="translate", + target_language="ko", # Translate to Korean + ) + + # Create transcription options with enhanced mode + options = TranscriptionOptions(enhanced_mode=enhanced_mode) + + # Create the request content + request_content = TranscriptionContent(definition=options, audio=audio_file) + + # Transcribe and translate the audio + result = client.transcribe(request_content) + + # Print the translated result + print("Translated to Korean:") + print(result.combined_phrases[0].text) + # [END translate_with_enhanced_mode] + + +def sample_enhanced_mode_with_prompts(): + """Use prompts to guide output format and improve recognition. + + Provide prompts to improve recognition or control output format. Prompts + are optional text that guides the output style for `transcribe` or + `translate` tasks. + """ + # [START enhanced_mode_with_prompts] + from azure.core.credentials import AzureKeyCredential + from azure.ai.transcription import TranscriptionClient + from azure.ai.transcription.models import ( + TranscriptionContent, + TranscriptionOptions, + EnhancedModeProperties, + ) + + # Get configuration from environment variables + endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() + + # Create the transcription client + client = TranscriptionClient(endpoint=endpoint, credential=credential) + + # Path to your audio file + audio_file_path = pathlib.Path(__file__).parent / "assets" / "sample-whatstheweatherlike-en.mp3" + + # Open and read the audio file + with open(audio_file_path, "rb") as audio_file: + # Guide output formatting using prompts enhanced_mode = EnhancedModeProperties( - task="translation", # Specify the task type (e.g., "translation", "summarization") - target_language="es-ES", # Target language for translation - prompt=[ - "Translate the following audio to Spanish", - "Focus on technical terminology", - ], # Optional prompts to guide the enhanced mode + task="transcribe", + prompt=["Output must be in lexical format."], ) # Create transcription options with enhanced mode - options = TranscriptionOptions(locales=["en-US"], enhanced_mode=enhanced_mode) + options = TranscriptionOptions(enhanced_mode=enhanced_mode) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -69,16 +212,96 @@ def sample_transcribe_with_enhanced_mode(): result = client.transcribe(request_content) # Print the transcription result - print("Transcription with enhanced mode:") - print(f"{result.combined_phrases[0].text}") - - # Print individual phrases if available - if result.phrases: - print("\nDetailed phrases:") - for phrase in result.phrases: - print(f" [{phrase.offset_milliseconds}ms]: {phrase.text}") - # [END transcribe_with_enhanced_mode] + print(result.combined_phrases[0].text) + # [END enhanced_mode_with_prompts] + + +def sample_enhanced_mode_with_diarization(): + """Combine Enhanced Mode with diarization and profanity filtering. + + Enhanced Mode can be combined with other transcription options like + `diarization`, `profanity_filter_mode`, and `channels` for comprehensive + transcription scenarios such as meeting transcription. + + Note: Diarization is only supported for the `transcribe` task, not for + `translate`. + """ + # [START enhanced_mode_with_diarization] + from azure.core.credentials import AzureKeyCredential + from azure.ai.transcription import TranscriptionClient + from azure.ai.transcription.models import ( + TranscriptionContent, + TranscriptionOptions, + EnhancedModeProperties, + TranscriptionDiarizationOptions, + ) + + # Get configuration from environment variables + endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() + + # Create the transcription client + client = TranscriptionClient(endpoint=endpoint, credential=credential) + + # Path to your audio file (e.g., a meeting recording) + audio_file_path = pathlib.Path(__file__).parent / "assets" / "audio.wav" + + # Open and read the audio file + with open(audio_file_path, "rb") as audio_file: + # Configure enhanced mode with prompts + enhanced_mode = EnhancedModeProperties( + task="transcribe", + prompt=["Output must be in lexical format."], + ) + + # Configure diarization to identify different speakers + diarization_options = TranscriptionDiarizationOptions(max_speakers=2) + + # Create transcription options with enhanced mode, diarization, and profanity filter + options = TranscriptionOptions( + enhanced_mode=enhanced_mode, + profanity_filter_mode="Masked", + diarization_options=diarization_options, + ) + + # Create the request content + request_content = TranscriptionContent(definition=options, audio=audio_file) + + # Transcribe the audio with enhanced mode + result = client.transcribe(request_content) + + # Print transcription with speaker information + for phrase in result.phrases: + speaker = phrase.speaker if phrase.speaker is not None else "Unknown" + print(f"[Speaker {speaker}] {phrase.text}") + # [END enhanced_mode_with_diarization] if __name__ == "__main__": + print("=" * 60) + print("Sample 1: Transcribe with Enhanced Mode") + print("=" * 60) sample_transcribe_with_enhanced_mode() + + print("\n" + "=" * 60) + print("Sample 2: Translate with Enhanced Mode") + print("=" * 60) + sample_translate_with_enhanced_mode() + + print("\n" + "=" * 60) + print("Sample 3: Enhanced Mode with Prompt Tuning") + print("=" * 60) + sample_enhanced_mode_with_prompts() + + print("\n" + "=" * 60) + print("Sample 4: Combine Enhanced Mode with Other Options") + print("=" * 60) + sample_enhanced_mode_with_diarization() diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_phrase_list.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_phrase_list.py index d76ed0b72646..f0dc94d06684 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_phrase_list.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_phrase_list.py @@ -9,8 +9,17 @@ FILE: sample_transcribe_with_phrase_list.py DESCRIPTION: - This sample demonstrates how to transcribe an audio file with a custom phrase list - to improve recognition accuracy for domain-specific terminology using the Azure AI Transcription client. + This sample demonstrates how to use custom phrase lists to improve transcription + accuracy with the Azure AI Transcription client. + + A phrase list allows you to provide domain-specific terms, product names, + technical jargon, or other words that may not be well-recognized by the + default speech model. This improves accuracy for specialized content. + + For example, without a phrase list: + - "Jessie" might be recognized as "Jesse" + - "Rehaan" might be recognized as "everyone" + - "Contoso" might be recognized as "can't do so" USAGE: python sample_transcribe_with_phrase_list.py @@ -21,9 +30,11 @@ """ import os +import pathlib def sample_transcribe_with_phrase_list(): + """Transcribe audio with a custom phrase list to improve recognition accuracy.""" # [START transcribe_with_phrase_list] from azure.core.credentials import AzureKeyCredential from azure.ai.transcription import TranscriptionClient @@ -35,27 +46,32 @@ def sample_transcribe_with_phrase_list(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file with domain-specific terminology - import pathlib - audio_file_path = pathlib.Path(__file__).parent / "assets" / "audio.wav" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: - # Create a phrase list with custom terminology - # This helps improve recognition accuracy for specific words + # Add custom phrases to improve recognition of names and domain-specific terms + # For example, "Jessie" might be recognized as "Jesse", or "Contoso" as "can't do so" phrase_list = PhraseListProperties( - phrases=["Azure", "Cognitive Services", "Speech SDK", "TranscriptionClient", "Kubernetes", "microservices"], - biasing_weight=5.0, # Weight between 1.0 and 20.0 (higher = more bias) + phrases=["Contoso", "Jessie", "Rehaan"] ) # Create transcription options with phrase list - options = TranscriptionOptions(locales=["en-US"], phrase_list=phrase_list) + options = TranscriptionOptions(phrase_list=phrase_list) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) @@ -65,13 +81,7 @@ def sample_transcribe_with_phrase_list(): # Print the transcription result print("Transcription with custom phrase list:") - print(f"{result.combined_phrases[0].text}") - - # Print individual phrases if available - if result.phrases: - print("\nDetailed phrases:") - for phrase in result.phrases: - print(f" [{phrase.offset_milliseconds}ms]: {phrase.text}") + print(result.combined_phrases[0].text) # [END transcribe_with_phrase_list] diff --git a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_profanity_filter.py b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_profanity_filter.py index 6826139d7061..0018551e6abf 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_profanity_filter.py +++ b/sdk/cognitiveservices/azure-ai-transcription/samples/sample_transcribe_with_profanity_filter.py @@ -32,10 +32,18 @@ def sample_transcribe_with_profanity_filter(): # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] - api_key = os.environ["AZURE_SPEECH_API_KEY"] + + # We recommend using role-based access control (RBAC) for production scenarios + api_key = os.environ.get("AZURE_SPEECH_API_KEY") + if api_key: + credential = AzureKeyCredential(api_key) + else: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() # Create the transcription client - client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) + client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file import pathlib diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/assets/sample-howstheweather-cn.wav b/sdk/cognitiveservices/azure-ai-transcription/tests/assets/sample-howstheweather-cn.wav new file mode 100644 index 0000000000000000000000000000000000000000..65d23513004ba6be2eca6c2bbb10438753795911 GIT binary patch literal 53652 zcmeFYWpo_L5+<5i)y&;$G0T#fnVFf{mYJEEVaz;c9y2quWqZsdTec*NS?X3ZRb_6p zbiFfo-=5uH@6S6=d0JJKm6Z??8I|>Ykv%)KZM*RkLj79wZ8K)_tOy-K2t!)d6iyZ+ z#2^ivj2b>`_!ubl|Ns4eQ376lGbLL0p8c=MJ7Qci?0?_+C%5#hv_wg<|M~Bq@}*h- zyE6Z?@c;GX|Mc|#>7KXZ|J(h4H%?3byg8JX=9lLD{{Qc?|8JlF?!oVNO0R$C{_fF# z=l(AH`{>oe|N8e&Ua5|}_q}IcEAakGuS)MRkn_K@j(?XaZQ*yVrN`e_rR7R{@ZWj= z-Og_t{O^+9Cw|}g{d8&GKjliV|H=L5?4Le*OMCPGJLjKV@7eEr|2{9R>$e0-kKX_6 zf286)|9$oQZs|Q1%6OAES5R{NedR4*n*Z;of9L&k$J=&ko!-3P=l>qvzkB@O`K4p{ zfBygPQr_DC{a32T(wtJMm-g_V{L=n--wUOEDxD?&-1k2F?`KNKz=8z4xus())k0~h ze=O^FKmOfA@45G{bnK;l^;-S!vZcrWZXF>)`I1B^DVZXKa*(`v-Wl$>6!P+U6NCp=Y6vDtTeau+FPf$yqmg8l9M{9y(C$wnOdk7k_FC+A(`OlJv08# zD-+~-lewgv_pbNc0;x3D`=s~G2+4c=U5DjAEqLqq{z_Z4QE&2|J4$+CgFB_y-W+F1 zAMGVic%QNTr<4Qw?d`QUc}u&XoOd+de0NE0-jUf$%9ob&*5s9xcig4YES0g>3TTOR zG3eN#ENdnG9;@4X{~CuC5kwB+b5BQD8Pl++-H|H_h|2I(NF;Y#(N+P%l$ zSKc0ZOUj_fBBi@mh`%`tXD?fr@eE>Tk5x!vn6$v&b!jOyz{|3n@T0^Ehm5$*%F<2rS6?Y z-dfm_=^`k}A@EG8S1QRYDf9dJ(i!-BwwBIWug-q|ypr^`?3J~5Y+ea@bG)M|9iR8g zD-rLNx0O=edh@)cyvaLe3EV5KrBr978u9AcD}Qg&l;~SkqIa+6y~%sORO{lBnoDh} zR7&3Vyw_fRl*+!eJ@1%>(4GYTmyX&iC9mAPR$DsTy_Q}&Yn(7EyooEZXs-`JP^VY- z%91*~Jt(yUA>vEsiq|`M=S-=eKu{_Km4Uu`=d&-Wh^nA?bf5WyIgdu8MAQ)3i^k9%WH2$&O(=uB z^6d7srfSBQDUU`G6S;$(Y#ws}ts@-&fU-;ovy>j<{J4Cw1*cFW*U1yceIje=DXxrr zfTtsQN>1=mTu&~V?4Z*qPiB$IWHkMb4x#BZi|Pz2}4bs);*-j(0+G(wV3} z)O4S2K;zLK__%mOQ^|fb0SnQ2noJ)cmMIJ8E73a~%&fpc_yoF&Dq#=0gg2mJh@czT zh&y8ex{m5GRES#AGh{P0pk*irqH(=|Gb45Ar`qfKI{bl=HWS@m)+ZCXY3& z`G{hflXM1O5f$NfbR9)F3M4k15_}T9C0|Jl%$)gj1-XeBu;zC33CRX; z8OMjC_skdafUAYt!n|xkTGDlR3Vud6(kt{WibBI_ED8ZFN6=h448`$AVq{vNail*D z!ZuWcsK8(3p%Fw(rwEQ=yQeyJF+I?BQcQW2M%|9JOznp9~i-G@;Al! zB<+l5;VNh=>WTTu9^&)p7~GOr`7Vr^sgEl2@9=QpZTg%~!!hi8dYL1%4qKBB=U?Kg>{hyk z^T7iIQDnGh8lEc<5af}g&&+Gum}?79u=pr{m@Z_>qH|;uYQU!8j(j~DBPfT2TsE!E ztfPtibX1?YLZ6Wn=ro>7cJb43JEnm4C2a`8H$b+&{9H1cNykCN%@0Cta2)vZ=BN|s z|8LXzcpFz`bEV@L7(>*AQyrS{63z-OZRUd1aHZ+;9 zhV)E#G>LAb>o5%|Jlav8CBE2%^(Q(vYk zcJK%2Pr8zhW+E7dKH`_4L}mtVPon8Yya|=1YiK)k9hO^_2uGuEHY%d8p(g?0VF#e) zs0vk56&eAW@lb!VpFe|_Gacv;J`-%^Dt6J!$V#V>Y2ZaF;wRu=mg92xHtE7|AZ}ER zHsOEL8)yO9N^;OS^o_4brR*VQJ$UEw>}SCM^psL^O!XHi!>y&xR>s#u5=fKGY-jk_@Co6Q!YYT#LlT1W0?PWibdA(o z6t88C#JiYqdX96sF4>QouNoQ_{>{o)KyUT zm!*pS5Iz!kK!20m4hOOiu(mdv4bg??3;grHX6;L>_3Lz!GgXj#J^N_t-1PN@A+`aw zV$)ztDBnvIFFq}LEfJ{C>z#g5-y+?3-_L;&!8iTe`s~q$>EnINYOBeXNk+=2DV@^g z%yJsYjuXB{XWY|W-`%U-L!9w8YE~BSDY{coDX(qj$>hyRh1tGE4YEI`EX*2bIqizG zMOx)94m%`)@>jCMvMK67|DS;(KZiD1e>|vNaEk9m^$*od-8fxU)Vtu>N&oDgxn9_qkpY?7BD;Hu74fPL{(dDxGq^aTryasl!VB(N_Gp{ z!+SN4Imw7n7k-^*mAkI{v~z>?o^f5lqTCmm(Z9z0te(-oU}xso!q!vCq;V95TzNmF$;nyEa-oNGfFqu?NIr*#gO5>{aB# zV};{H0_F=B>zT%z`K_+g=8r|FFd;WNwNb)?#2I;03W8Hc|16&~%&o)+of|AG_%_Pn z`j6Tl>eZT!dUx=Lu(5%+H5=5Cev<+Vv<*ecY^qG4dMfruM@fCbBx!F67RYclCQpzk z+$Ly`hI&@GoA8yn1j~v1=;D^pS>1Z?bXx zF^`)&z%_FGD(aP;p58d6dBV?lQ(8>klhhfB{d3B@35p?yJ@3#(WjX(w{xSL|+KN6g z!GDF<@E@nFqFAo^q3xt-%s!%pg544{$f`Nzpx@^8LrJ_Wb|UGA37 z?WTzAzKMD9n?FxV_?$U5W5tiK#4m*hsgZ4oUXfri)|Uyc9IWwkY2vk)1Dk|~=_iQu z1>WZtdB4qQlw2d?z%o&?T7qY2djq2D~atW%st|l zle15_Mu|7b0wgZ+B-J4QbPL#`12u2#ruUkh>47wlC-u(erw;5yi5zCF>Oj z6jPPwG=J!?`_1ut>eEuKQ9J^lutIQ$Q(LPRjmh~tt=rG^kB{Gd_)#;fen!8PUD>DY zDT1HU&EjE_bagfVHUVS&mTT857-f*!AipN~NaOg%v=fcz_Hm(fE%S$dZbLd=q_@J}K&4WnV>Ei7&Fb^p1+=A-Q*wUw&))`B40&)Qt2lzrOxDl^5g56s#9M zX4;5%YM=Q&)0fd+Q+Ah!D?TU&O1d!xBo)4ko5FX|34SkLE%+$9D%mLCt7@b@1FhWg z3-&e*M_+`Nr3BX=8E*WS&nST~O2gPEb=U6P*zc zSGd*Xb-6zCR7IkD?g_5Y`ks&WbEeS+YqDSGA2Z^j4mk(1BMr&6 zOvg@ZocWAh#bwam_#E;lcj1e!n>bC}hiyvV(Sw4!qTWI^d!0Ql8Z8~D*r+rqd#l!| zW3{b)&iIVbd{Io12g&0ld4dJF6VbUpTkjawQNPBjm8 z7(6!!;p06v(DilptMHP*h9{zy%mm>G@dD8xp+Iy(vRbiE6{)VE4p$ebk85LmQncMv zZROjf@se5MgMusQfk);jZwV}pG}+9u;_-!53fCHf%^J%}v%}OCpm2x1gL}9q)1`5p z^K3`k*$DP6-hwYPMS>fmPhz7uTKqw>O;JbPTzyV8LS0eg0BirOZlZcFFOWt^R*Q7P zvW$}_PQ9(RaXgi>XWKw>P$^{?JG5}=q%qQ8zFUyjl!<%bK1}I%W=#8 zx3h|~skOi9M)5;)o+Z+9*Ywl)#K@YY)?oW=o7@^~9qL%;=|m8{0$(8Ia3?`yv02<% z+*Z6nI!(D-ouJ;Oo~6!K2WW(n z9MA-4q#CWJm1d=;y=J;PQn_EYLV7`3RoYwh5TD=~ZX#EnyW;9^zX?*xG(RwRH1#n~ zDSA}c*wD9lpXpPv%h<%!%=*G1aqB!Ixm3O-ieafRU))2IA_8gt`gZDH^f* znsTe6iabWzK-7d?jB1i3ZjdM6Ilvxk{b7D-8c@8+@S(7{z*#V}aC%V{!zsgPV}9{n z_|7PBes-Vdf~kth7DS8hNxn(P$?q#0Xg+DD=q~G$bXuPue-`a2Y+aZOW2j^h7l4)Rus-QKvl?cZjrl{GsX7J($oC5IM$d| z)UNPML4LuTLe_A}fQ|ZMx!G#Xa-4U`JOchH4PfsI%Zmp|;-wPBCeU)lk>`S6xX z(cRZ^+WVTa>U+wAigNM?lF!0N3@|5TJU7uD;k<84u=Ft_(>J51XhUIe;i^ z6qS=Kl8WU6m5bCLG|#oQb^Ud1bz0pz?IsOY4_Dgdf5|RMRHA0=B2<~o<<7hBJO8w| zv_3a)F^w)BWxP_fu~1nQVpwO~Qhc}gfhpJ0!2Z;E%pJ>ZBNtE^_JDA+I83@$RzXou zCDF9gnzR8xVm;7?Y1?TO>TOD`;+)JR`5=lF+{feSD*l@1gX>SnP}@7pc(cM3XRL3i zQZ%T@P$V+u8Cw^3HkG%;+O9bIy1uwY{1zI`%n)=Jl?NG(m-kd!Royj#+ELo$+AG=y z+6|hm>TxPR^#+hV6zGARm#b zv3Ztdu`S&Z?|S7q#h<0+nel?oB2L^{`c^hgQLOB)cB_?|YMNs8R<&7`s=TZiBbUf- zOTxspg%)NzI!m2kkPkTW_oWrVjga}Zhdd}IE!IE zHzD=W0%oINi0F+tM7lGkzqSyootzFzG2dv+{Lk`m!@gv29{uJU)u|Nedin3Y)>Oz3!Fm|vq0b$ zE*Afigvlz%-^-^c-YXs`4l0H!GUe0cZ)L1(kaV^L)}_L$g39bQ+#1~_G5irvQ+KlS zh2x2RtIcGcYc*KXEyPmBdf8gfmSlTi-{)B2-0q5VhjS}=2YB(DSj+Ym>=3>ay%aB& zRF>Y9>Sb*JcZrbk(r41?(lm)!!izeHmI;>$#zOmcxx=x+ z5$kB~`0n`ZSnP;*h@I=4f4G{twVvmm&fIW*GC4p6*q4#9U)f=T6hUiY1z|biT;VC< zdf|NGpTc>Bh8Y0+}y(F=m-{yg7_%qA7cKE5lUy05tpTx~!izLKu=1aM?B^a^;I$AE{% z)9WzSU|=;y122$|=ApCN)5wtQB`jgBj@i`ExaFBn@k0wdvBe?}!K_(Fa0;+~G>wrNRKo`nAI&fb$dWjAO?M2ZZz(!S~3uqN|7_|qa_Xu50n*i||M*`?E zV6^7Y6~G)+f%@*CQNWfO0U5soC~q&clpdtV(GJLY3fS*^U@8Xy|J4okL;lc481!cy ziYGGwv+sgZ!A^we3~+h=@Qss1A0Z#~gpQ-l=ry_wSg|+sExiofTxV1p{|&OWBWVBHdcpX)(W=viPpqJce&#xmRjWueA^ST_N#s5;>8 zf71qJDB29xbA|?x1rRl|fF2+&+6L8vUff4*pxihb3XFIUrW^v+6RklSS3TCMen3f#c3b@@h@Vz$^*hfTj(O}vEU!_ZFTYL+B zqtB2ECz9jzH7cZQfd$$|n<8JF3mUmbm(YCD1lqN84^aregGM4F83)WzC*b)In#~-c zr_nZ)4En8vR-?Kw$`4eBZa`~y=q=PAX96SG71>A>P6bYDEzKk{nuGRWf3lbK2B!WD z2}Z|YzFWbThS6P>PiBxqklzFBcrec7YvQB0Kd_Rsfmfc#PX_MU55{Z<&$AAF zgc0`UyJ0=;k6+@Nq!rT)rIQFo1B~f?ngF(wNm{bLbRSuW`_V(-L(W1(K?5`r7{Ib1 z#RkAyR$&^Wg(Mn3AP<3KJqJEPhRO?;kO#~pbO2d#GcuNna7UPr7LZQ{s!Nh#28!{0 z+=CSJPjCp+pYA6ufu~9b_OBgy&a>FXPbI~8F1|&D{9#;%2>_;a6!BwPFi~_T+C`Ia zHSh)5_#3)R`vLE;jQI}U=r(@@G;@hGCK6!TJzO4rf%~8?AiEAQlTPA^d>F89-|;be zmgvw^eh`zu%z$qtEg6XA_y};(Z%7q<{n0nD>XnS0_TmST!`KfkL>GBK zULg31UIPm?2G?gWu;mWmd0E^In6IF4w;j^sM<^##k(C$fq!CLM7U^MT{JFN`nt=M%w8 z4B}qE%)O69EQ3aHeepZ-abn)= z9$D#bLGszJBpz_G)%@Rh54FL&@(=QYT}Z#7e7ur0!}rMwvzRol$W=xvDr0A~4!|p3=t5YyLEOLwg7c$WpEcXsDh@g=Ts_LA=EUegodb$e7X8 z#P6d&a4x>%X$Q8fMZ?H3dXC+Od}sweg!g5^&%1{)Qw8mq_MYV^7uO|n#>&+ogCuYH zNABuu7I{j`;7>#aaU!pHj!VVs*e0G?*d>`l6yz22gnq&In1x(6znhti8j*hVJ~nxV z0B_cr1PErM<8I0&vvu%8ZV}!`I`O?l%h3`vk9o)E@o%wSe8`>3sbOY$gj?`gz7_d} zJEP^E6v0q*$kT$YP2WO{N+n)}bWAQ<=Dx#k7UhFw&BkTmO)mpHvn98QJR|k7_W%xFPVl z0my-mGXrUFasxl&Q^_9oJ~I**!HR1K^H5kHZF2)HBQTP|?vvy@{{lGKV16jN0yFIh z{f^@Wd0Y%%z<$G#Y>qboih0B+_}T7B%zN-{V*$B)ge~L`t`~}D4x%eAh7J*%=|=Y% z?h>6R_#0pK^r2DgJmw?Wj9-eP*d1gyc;_ALF5H<lwZ!`kB@ zUW~Sp^`47J&33>`Jj*;5#Ib?QCGaXgm_oc1d}ePpoOT26+6-4`ZgBy854IXRnC7{= z(swA0-;Lj)F!%?hC=OdDezG08+F`p+m zg)Z|datxoveq<`O=QJp34LATMV&iN5l4oGZzD<~6gDl;vvx^ZN&0joRZG zjFcbAy!iBgu zUjt$~_QMJ#i&Uf^$W)q4rbDC!#}lH*b(s6a>6ykf7qmdfxqW;!HkwW6WBGk3omoP) z{93e>X@q@gRfvAL2k-U1xDfAT?_*4dLrlO;JPiFJHR&RVM%hH0(}{rD59QxM^M9IqT(jwr%WgO5qD)*G9R%& zPJ}Z9M6OImgXjf3gef9xxVPMR+VQ#W&hC1yem0w_i}`@%jn&88r)XKx4bxP!Z*g%^oN>J6fUU26uCokRz?n#6 zK~2eaSxbdL-Na|Q?-1X0zT^FC1#JsT4LIy4_7(U(^GVVmVhMc7I;VBoA zBa&i%RQf*a`|+QtzZ(7uOpZ&n=foL!a}#TX;|&=mIxIV0o@Hw|Iqet4})QKsbljr=D zCw%$7{--{5QF>HbyR`l}#^N2ee4Eq(HY*e=T*{8>fx12ZO+ry*->ByiVUgd-4Qd_)zllhz3H1LK53P43?r>(Wl9hNX;4YWDNuk9$8( zB|c0$ml>Urkv==Ghc(_c#<|Bi6b+QMS8r71tH1ch2QLe&5`Hz}Q`EjPhsp?|_e4Dm zD+s;eGml!`xmQz;WIGcSV(q+FnVN^Ga@l6F=l^E$H*BWq9Aq1 zz@P;_PDN{JN69PETinxK#rD*)#r(u@JAY`-qfFlnK6Oyax#Yy3V-x26xc;kBmLU6Q z`ku@;1_NMX3C<%Po#2k5o#vTlp{}uCyP$dDC&~;cb35Wl#KSU`%a)7o66y$u3+xmm z^0TV$NKcB(i6Yqxe6pjT^}ESwyjoN@e{J^JjLzw+(uSv`Brf@}>qq-!l3~x9lVQ%d zUJzz4bPaLkxL=^P(%mY5O;6o!{U(1|$hU};sCALg!~cvJQ)XDSf5hpa2?1&Tul?M* zddkL<)50I@6|{z%?l7497RMV_6e$Xt?AP#Yb?*Jlvzb*3 zAK7<%#=6J2yW>`}Ys%j0uew3L)%*_zrG@*J`54KD$A+gzH7~O{Y(bzRV5EPMzOUvl zxkS28w162(5DQQKCMiF;d{)2Q3E8%+$ikks zn(lip>`p`FB>Uw{ly^0M_;mHv1|A4)84(*E6gnX6S!C77*pTA^;{&ew|MDrT>7fje z_Z5$aH?^J;_iVe}a?HH3curBdf~|SIbDWvNOuvlgsVKQHNtUrBFDbWsmNLg^6gc`g zkt@Y>4c`-~r4nU#?FQWeUATY4kcpwgLpz473uzP9AS^ccK;Sq3Q+k=ssF|ahE3=E7 zOaQ(>e|q*ivaH=Ki%qYLy$rsE#d(3bud`QWH_UvUT05mM4dwY1w#dJoGpwMwb*W41 z>FlY=|Bc!T)5DT2?dSmNl{c2$?3rq(L$pzYitb9{mKJ3hN z%RGCyzOeQ_DvXvtQtnpNlt-y{`AqW<_HW@wefRiY@m=O09#G%!p>DdWDX?H8R4xcy zzYgy%3EDx1d73+?0;cb0<*chMcZ)v*_P5h8vZ!yqD|>m~0AnXphvHcVjd8Vkx4n@o z#@)wr#naalOTP+`R3kYrGKu%dyKCC&e&}B44B8A$u+Ip;j(+`oShZ7;s*F>a6a~`1 zMGx5J*!#6PfUum&`P0EWPhuz23-P0c4J^{Rr-oyp$dSPerM#&w?Yw1FHvO=w_tB8>wm8HtQ z%c{sWN~=iri&hCU1XjU2K?*wnR(7>mE!&BC0f^9Pti=7$RQes(#cq$o6Ua$Ca(7>6 zBj+%OzeDO6Vs~2aSsz%^EKX}vTU*-^+j_glvCI|jN#!;Ik~kWVW-dWg*mdDR(G<}J z2-lw|{!5%JmI0G5mvolwkXR-8k~xw=lB1G6k|pAr;xy5EQ6rHQ-jKP19l*f72W007 zi6%mRB^T)_a`kg%IqEsK*k{gj>?^q-X)7HeZ7A(1?I2~O$0T*2{gz^#xVmVu zuozZsaqx996AuA2LrcDMC%DU=V)sJ#NteItlykKcIX62VI^H=1PR40j3V#agi-e*`QHUs4 z_*QsN*hiQu_*>9MkO*tNk4!Ga>^ad|_^#hh8&L^eL$djF-pViJKXbJ?gQqrdXZ~D< zr!v=sYssyLZ@@sln7ayJP?Pynd;(ttoZKpiM!i5KfSpc<$iIR363)TNI0=x~cFZ#7 z9`g~>J?1B4VggtXMCXlxulDMYLO}al@NV1 zszNMmHCP$mC%efb_+p$!Hj)cu0;x*|k+nof6@dJ?0ezeSSlh zFgM;n-ZvPD85sLiXgvq^l*FI{K;z_y1I)`0a6mu64J*M8l(MK1ssX*4fTNk z)l2j^6m;p2YNF<#mnbMNfpxhCuu30@{nkKjiO`>X=uaWk`vH3NH%)*(8sYo_eL>UV z?iY}o5q7;`*dOD7F%T+(NLU_rLRe`z7jJ*iTd3Wzr zgPkw$KrRJPE)n`@gr1AR-r}JDUTJuDIORcYejtfjaE_prVA!=$6?CIVH(>|P0MMBX z^hZFxGH62&EJIyX8`ksnpx+FjzxyGQ`7e+|Q;=;}$jN}67pX8h7oZAu$oJaPZID?@ z=x-K%4rsjuzE+Y!SD7>rILtnqbE|k^4J%z*WAu;H91*9F+Zs(@fp6FYyhwdifh;0z!KMWCD|ot_;19M?D>5U3E5p0O zffnMUj94IL*8)zm6!k$9X%Xz@$|rju7BL*Gx(w_`3qXN1fM3AhrYf31w4@eT;7s(H zoBl-hGhjI_dpt}}1pZ4&`=uNaMCC{6%QY$LD{bI@?+Gj?Jh<^{TmHsPl1GeHNz z5EyL)$aMs+#}+YlFav0Qe|ir+$Jfw2+J@}&Omfxr%;LXsi#;=(AMFlDS7$fJR7WcZ zvJEnCFyFHdwfi|b+DFK{aXD*pG`h%^jq}% zd@P!3szBvk`AMlxdRh8e!ivtZQ<;9uSSApUrGrQ@=W=gwFZBHIl<_=r)pHJX$Q|=+ z8J3Hdhvr7c^Z5s|UFnB@9r}?Izwn19L!H;RV4-onwWEV^$D?+#{n}uCRegZp(7?k% zsX_BYiozy_{uwaMSEJAOnWtN*3RWzZDa2FQvrMc&BKQo_31H)ot-l;xDmhj}eE==ubg3vCecC`1~T6XuGz6*)h=cko%?7n=F%?dsl2o1_Y0 z<^y48&^p-37LS5qk7Whs3M&-$7l+FCsO;+Qng~r@ja)llyH`6++eST0{zUv)@CnZ% zNp69ot65ZN%IurspL{e4C-(my_j%8|O)vL8-TA!5yNL;{(^}`PFl}@0=f4TAsA*u8 zh`%Bgk@4Y;!u&%%2fqq=8T8s`lcJ$?oWv?_D8485le7}{z-7=$28*hQLnUve9c7!O z$abI-gnhzBX$y=9oBE4_= z-Sni?K1r_l@*h9GK`-aUJ$*CeTkNj}+0n&M9iO;MY&*p`zgpqZkpsi~h1CeF5#k?I z9GL1qLsv^VLHbDYT~=1!Sb9hD6{0Yv3h#(a(zc4;3Y9!rwn-7Bid215Ro3Qc1)30* zRJ8(j7aUQyhv>eF(yPL;g8f3X@D7v3XFGRWyPC!tl!bHhW@Wbc#Uyq~di*Ob=~Vp9 z_g`KWJ&Ah!_=V)lnG`nfw9&`86z`Gt)v;lT{!6o6)m&a(a!W)-Z^dK9mxQO-{!9m) z20YXd#)7VKjhr)WgRKWGy-ewa_j2lGG)rBQx;On?hB@^{!t4*r{=OYo=Xpll=(q3V zpQMHt&b2?G$0ftGV}oXv5muO2aYy-OF;gSz20!y_sS8(~mTnLvz$$e#{=n9Sh@_>` zIr2fu1?rZ%c;B%BwE}wiAMsn`TS?zhw@1@Yty8X-wiMX}k-`STSm7gxj%g#9!;WSz zvO+-ta}?S5H}0;EY-=^^AB}CA6$Q5d_kYhc~SR$ z*#tfw#YbD+TuT+pi5*CP@#7R{)xRm92;WguT)WQDx>&L08cq z;;NEb;v7M9CI|NH&VsjCf3Bs=X)9-T6yf~o+13odj6X8EXFN-LlQJ)P=g*7Z5bYpyeG`R*)c@rfKARJ*Y**yQtu(8DZ}OVtvM|H!Hfx?n%E&>q&kH z8w)oJRpRGTqhhmWkdIJr)?L?K*Z<*{=y${asDBgR(b{p!N3zq>V#zr16k&`&%)UkE zXce5wE)@0>ZWLT$n=&uy5q=F{2YAIK_j+fJeVw(FX@FsW!HwLUtmPS#(l=!Mow+je zW%`7aVTql;fA|vqIsQxd&(`U({N5(BV-Tqv6R2clgf0VwNR;f-= z@v7RYnTqAI&eCw{d+8$iVP&)i>rQIBYi_CsYN~4QXf;0j^j-D!bV~JX#SMt=TPA)f z+9*mBrm=ruDe4N}-Sc7HSq|1ki^ynhr2Cw!vum9*&au#uX|HK}Zmv+gyJ%#=syvk2 zCue8Q?VP$f#_ZNPJ~<<@mSrTS9Z&6(wkC6K9%o3hR(JEfAI1>HI9b|M5vwNJhd%4{ zKYecL60{#RiRv|KnP#(Q2t@0RQa4wHD|aa#DkMr@Wt1{hc~{X-5vVvUZzYeG%jE|l zq+y`+tmK^dz9>$3NAQ{TW1BI{u^Y{URjePxZY}4Vae7Z3_ej?Z=SZj4dCJkpQQr~d zNV2cD_lC61&e=OUT00buMfT;kGS=nhxMGFzbWvR4#ll)e6%Bf0g7Ika9@BYqoaMZA ziEV}blcT#U*S&|^N&Z47nEha3M)6c>lB}I#z4E5&lDd`Vl_pHvOS=ku;ce{^?PP6# zZMfE`iPMbJc;HRfUaeEVRvlE0Qz-x$i~uCmEpI6wBWo&^NYX_2gewFM*$h}YtLbSz zgxl=)bsce(v2V3n%ss(VN{l@XtBd9oRxS9PH#fI#4$Vr>tdRLW<4%S$b7N+utZ!LQ zvr}`v<|^|~6tpi2Gy0e&S#oU6ohJ7MzAK7ku|b ztrny)&G0!IM)q?-p3|dYw_RWg=k=rccM?#b$xt8@=#ue*>2HhHzRg+2^Nv4>=CTt-Q>2X* zta`gP+lTXg?%yqNdC>6SS|OK0n9#l&D% zsKR*#arvS7ee;&)UdqYKUY#A2y&y}TCCloYWzM>qeK@B_F3PKzKe6CMq26%77;9=^ z>0~?ZAg*;>e^_Tqg>s2Q_E_0Xb6Iy!zs4^rU|Ha*px9t($l#FJkYOQ>LJYyHg42UE zK{VjI{|CQ|zU%eld^Ec6n)B*~s!_^7#WUGzX*)?raShQ+!6?><=b>==k-y0u_iS{} zcB!570gb+GnQty{dTtyJ_&O7>Ide-*rX*pGL zKj)s!JCc8+z_)0VA)@%B>4AmXx;QVmhr*7a!%VC&Qeu~#fSB}Wx(xjRzmR~KKz-2b zpoziCkhUSULZl(vfyKHIBnoO87!+Xe%kh1pzwEO~*GpRuB7uvPpA-w^m1RYe^Wrt4 zHo^?x?XwXefQ0AXd-l5rxXL+`?Hg?MtuJ6#LAzqN;bYO;!nA_Wf(iLadCl{7<_71U zhF)LI?v>prdm>mvR?gAf5qTl`U-R<{Y8D+f_!RFn4FVa@aYVV6d*1L;!1KHuy?VEtXs?hrZ>hd zhChq07TzoPnlH~^kf+Yuky|bIQBK92xa?EeH?oVe2j{fNjm&$VwKT%Euf@Gx<%cp%FN12Ew^^u9R?fR-JQW20S1@B-KC-3%Cp?nmk)(l-`xR z6rW-jGqY$dRY1HE{fti#md5rX6$Kl?Z>?P9Yv@66D~uWQeFr=>-OrsP9rf%X>mF{5 zrIvYs$z|MYY-hY=aOel>&ANBG_qv&IMMiafb#3%r4JpRY#$Bcz=F65BoZ7Y)Y+3GB zdXxMef(OE7z>BIg=E9GW6`6_Rz0wu(^2%wd9qPN93vj)77k4LaL0p}R+4t)%s4NUac@xAxV zb2oGS1>V+Do1P0>Xp77|)b!3c1}u7rAxpnXUtiDY@9JjguEUv^V8}KsF^(~{2H*8& z+zjh`+X4sT+UTz6<@r|z9pQ$&(*hDp#e0!AXc+jAewH0lSdfE zxmBD_TUk3#^Fkd|wNlkrq6(kviS#De#$W7R(6a*cyhAh#|50d0ha+G3gLp8m5?&A* z9V{Pk`!0B!cwDYOoHOBSthE`qG|OuwK@*W|@Ya44*&d!88W-#yK>fG9 zojrxFm(JaeesPwxrXkBpAF@Vtcf;DEaf;C z_u4A64|nWzeuh}COWtAra=`}S2H;J)8A-=#ibjw<=t*oVh)kX$f2iP;xvI%(Rx?Gj zNpoFuKr>Jy(X3Om>OQJI%1MeT@_w?m($W%{*v6csH&JWIImBR*6u*LvL{&&3_zBgA z-jf-j*1^Pp#dp`c&C}PdcDWqS?Z4T2SsQYlEIZ6`<{PFyCcp6(NZs7%H{3NGGwe3} zVUQW08t<73%%3c0x&78_HlCxZvx#e&+wD2yTOF7j+8p`76Cs_kW%wE5F?EJnF0LXy zFKeP$sBEBmubQNmXy$8{XzFVU)Q8jy)aBL7RL7Nv6?^38Wk;nOB`d_^*e-DY%Ok%K zk3{=%i0;M;k=X)1|8TT3^nct5{u=1)m%|grboVe{|)p%;c%7P9h?;y;urZ0p1mOR6lZ6+HcM>p zIX>6Gvfn)3T-S`6pPR;-;!H1$+l{{(I~dh)uz zp7B0BP#A0&nZo-lNP!5#HN+-rBvV1WU(!wXUd~t6P-UqWsN*y}LCZ5VV$CJBSUpLV zt1P4Js;B|+ksl=Q#qZfS%prO;HH(}#V zwtlhk9U5mPS8aDaPkZk+-!SluS`_)jtA{MaF5^amp+7-1&PPdm*#&t>Ayx6!d(^n* zN6lDGTa8Km1KdZ%s>aI6iplZ`vX0Wal5XM#EXxF`Y%+()gh<23FnZk(-ko0Z*TWUV z6+Ral5>!IG%VqC&&m#ADS6}CMjtce`w#n8F+@EkiIc1&-(OL>~mg&0bv}uQFh$(8k zZoFnJYeLMOEN3{Gt)sm!#5XQ-U3Gu-Jrmcd_-cG zHjqzO99C{qRZ(wM=c^lPe$XVtxp!CPP_|btQ*4wEmJw1;45SZM!lY4q$uUH2QB6Ei zs6+Q64Fy@?9o;b^3ZD%&34HY(_wMklcdv9Uf{4_McBieHZH)B*=eEqSs4bc1yXO1m z2j=VM!{+topUid4GIM?NA@fGdJ&tcHW3S=p>s;bG=6>OEdz<=C2HJ;`B1&Ej!7y}< z@TBMtd4(Ry9ut3-u(B@l!HUw#zm!!~6ICZvCsoT;byatj6_h_H*2y12%-$EtJMkCR z$^>Z~KY+fY56=y;!PEZkKEC&|dzovlbB<$)eXH%Z6|rvS zhI8$?I4;`)XP9N0Ww~XaWxhpXnPg5g4K`^_T}}5*i_JYPHMkbm-8S6u$T`RJD$s;i zRal8UPHm^h(p{OMl1H*fvaQmAk_Y05_=aSTbcAf9yp)24_rYYv0R^t;FS{zaBkm_I zWY@9B*wgGtwgJ1BO%c1;M@$2HK6w}7&_xy$N#FkFB6*b6_w*E?hqM#Akqo{$S{{6y&4J(j>wIUt8t*wzYtJor zvOC*V#{Cm4mE12}OI@8@$*xRif9EF0arP{N~IO(N@ zjEnw6U!#vgR9SWKP-!lnBiRDckeh+u@=&@`a+qyE8;H^PEwsBp3_h|KgPi}8@2j_l z_lakMr?aQI=X+0mPb1G1&rQ!Q&koOYkH=lcT@NDL);ng~=h*IAD}aR{+*r$Kv&eMV z&_~bcY8C!a*hZIN(3`}z=dQ4SM|3#0hTO{LNNGhSWkexU%$6;bRAcigIeA~?z^CFz z@J^y?1WV?T+bE2#LRX+M`Xn`&s!6q`PEq~nRuE@CK-^LCL}HTsB3UNp7zv$Dw8aOa zWBIotZ;~G?vC?p@KD~%;5o9+cg(lcSI2kJ%k!3ox2iPfSBJsQ z*jw7RTl2Y0%NcVY({n>(eP-dP!jpv;b(aj7rMx}Utq9)cjTKg)G-5_pPLZpauIM38 zmG%)or#FGji}1C=HsJfx1LUqpd`D8$F6s{Tg!(|8q?$sX#TKeIjWHFWr*@lUh%_qI z%GOGoOBS(p=+(q!;U^@M7YR=YHufL&&h@->|LE@LUg_rCi#^HSJzmnc*yr?h^7r&t z_aE_n^g28mPZRe*S4U@kM-#Y8Pqhx^5-clB(+xdzR|{U|d-Dql%IQa&R#_Li;sZk7 zpV(jICHABAuKc_rPH{u#lx$$LsfC0QKP$YAt;I%yuS`?X1mYBVh(hUlbQ@YsABLV5 znyN%?qh`~$AnJFUGmvB3lg~nlDF&y6{3J|3! zKedA1MK`B^r9$LH(nqMsBji1*JoAY?Bq<|nBEKnLFW(|FNXD}Zs9K^-==tm#ITuWY zev3Zdn%-&N9Pel!;a~6n=-2zR{7?O>{eArv{I7h?ecQZmz`FgekP|{s?OJ<3+X<_I zGh0rYO~xF3eqqIe=K1~e4;N_kIi`2EQ=ShYEfPm)Sx(wpaaK7?X_C*B{?5(-k1tfX z53PnyK~G{s@Y>L8RFzI*1~77_H{F%$Pi`Tq5WR@<w35T_enfaM?0`z4>zO*K}xhFsf%0e%}%Id-|M zr*gOIrK+m3uguPFr#gtX!#&rF>_ER@f8rO2-qg=@9D^~<=p@QRd=ym>k)kW20wROz z$EHhg`9Zi#j#I`d-b)MFnp6k;05XyH24Wh5fz-gxz=uF`ux?Nnm=MtU>-*RGD*Iaa z4*3Q{yr?3$E;u&$HE_Vs^ZDHQPM>|0t()}%x0>6>?c|a;kGa0-ong4{M!r4wRBkA5 za$$kdW%GLZ(eH#w%oy1nWgqoI^=;)vnLyl&^5VlWHHx4(mMQd#a>y2R1Ev?VpPou- z$Wx-0_%&fj$cpw8B>j;cE!`zAtxQ*TRu;Jz7?qB7*@15#B=Uw94;m;3D4V?m-Bo$GIn+Es!Qr({&D{Oyo&n#Ch7r1xObBNf_ z+say1<{|q0{5Ls*Y+3g6+}64}mUFJ5VH-A{$&_2vPvGstqZ%y7#5%Gbz71`HJVYc| zfsjuKsRp!=o=uG>vqcW!S!^|Cgg)jO#1%SM{8lztX;PI}Qz}H^kxXVh#BE_|w1Z$K zzY^cZ69Wrt3-9~ro^V>Q&@b^l_AKz6_MGx|_Kys94}Xokh0*+-k$Is%{j)sXo$G8v zImYtByw_sn>e^P?+c;j>*IL_{C+jQbkI$~2`CI0g?7jIFOq-ltLl$%>b48x3?xhuJ zhpGi<3&@xE zVf?pe^iAl5f1c;AbA$b?wSZ%+C#}P6^X%^&x1AfDOB_mjbFPn3T-YWzn0Y2WDWgmF z<$?!hg~uLM5NVP)bt?3>cs2EuO(h!Ysjw!z75#yv2+I>6s2s+?%Gu}CS^9MaT_kI$T%)R~>ZCxVZJGPTD`7e+LwBRMuw=Y9crtSMBP>mDF1j%E7WyEj)lPAmXXf zRA=%c-VbfgD;28eH+d((d-9-AljuEQJ=R2~3wH4&krBbF{zC5XL5wT9C0MZ>TxfJ02;;_Ec9&=#p45 zK2znEe5T%srsB(i2X&clCl*Myi_bH0WM>TFUjx=lqo_)-TKEU0m4swX6`d4&WlzMX zfiYkreusPLU8)|lkC{)mB$M&RNV({hpdw)N*AG??+oPuhmC=@{4&D>*Mp}mE2Gac9 z0~>>6cuM4Z@b)MS9rRCd*S6QPJTy$xzt#tgM=ULD105m99Q%38Rek@weHrf0`Ja-% zs&jZo(tVBBh>DkaRBbg?)uk01BvsfZ%vfePdq@06a$ho+MX4X~rO0&fN!SH%2nw_( zK8f5+w`QlXBbgKQFZ6ACB@z`k$Sedh3*^9jrJba3YIOVW~Ps(@|Hnd zcdo!}GMp`tWIy;4`aJYYtE^BV-*GBD6aUJdmk(4b6}4rHC8NY%aYJcO*;AQ977-Ux z-SLmeP<|44GVT&A!E*6bcn+LO>cA7W5>bP^OrH|>leJOk6lVDo3C&z4t_po<1Bk{K zVl}ae=uW{L-kwOa@UhT}@N9_Z?SPa+U%)%#QHZ(Xh1-Qrgp}c3;TvI5xElCqKXLtF zXSgFK(sX`q2dqa}qN?e;JgXnA2Y0$!-Zo&{O0cwv(hK&|+vw z1!j$mc*v&2}YlJpvk88rmY ziF#~*ssYgq?m(@G*P;u!R(J==1Gen6@bJi1-W@?rGy`3T(nu=L8@U!~4^gEA#2=01 zbI}3eq(CcgKlfedLU_X7W_!)$nCF_@MzgUe^d)pKB^y8J{>-12T{&Y}dO^mnysPGF z9$6H_j)>lnrzsdK75gNQlI7ryun(P$Bx4_iRYa3TV}#eyj?jOo7pR0B zF_h^q9wKQhX(fKatf3#$b=gMZYwRlEyLBVhVwa%@x+8ywpa#+iF$oq64)g0kg!>5a z%V~+cMh+mKfmnSm+7tYBK8H3#@9C95e?R5z?wW5O#631ugx;m;rc=->I@0VkcGiE+ zm*t2uU!)()kmt$_skUX_apA7~tH?OvBVqw#ksecq)PJfOWeaI}W*E7Lh=>*uc4D5W zj<5mp1S0W|@T&sttUX*Oext6ChsYb$L*^{JvmcgzCmkWaLsufNi8L^#+D^Cudx*A2 z;`zUWH!e`B`LhH|5DK*+=L9YIX)vnX0`5eMz-v$$c^Ta9e*{d5%kC`aa(gRlXA5TD zY|1rdnl^yOPv~bBY|CAry(DvCdh4uSg}+!5U3vb;;nMsG=v%xZU0T{y^+KHn{rI(H zDL_z(XIC=|fxmTL)EK)jXd~Dt$P!#dE5hh+d+adwmv8}boxa0v5%&SJ}0M8QnK0i-%ALE?b3+&4M`;-60e0Ra_cLX>j(us75n{G?8XvqHIn zEN{F!&RNC2#=4a&wDhnnHcvC1F_h7r%fFD@B70e;H{)E^ocwe{H>=W3)Ol z5V!!hLze?{{o8$<_lno#>Eo^gUj2>XxjN!N9j)w(Y?;>P)-l`_%R=+d#<65*5jxL|5^NqQS&R z!2gfImBOxA6SS$|9dAc;M3@)c>`U`Z^qh4cc53V$tgAQ$^zZhD-crK+*i^|h%@{Fk z*Y_%XR#?tB$}$}8=*PHW_J^)Z-p2k5f!X1qKnz`re!zE=v*5k^F|$iDR=!m+OyQ9e zicyM7isOnk@@vu>lB(jBY)u%azfKr%moP;*4_kz8MBWQV0a4_jU_PQlh9SL?rRZr) zDHOtpcL+-pz7w7TLRw`Y@NN^hd99;|!_z{wgL%Fyo^I~V&Vlw?)&-Vp=JU|2yUFlL zS5J4SP*h;aUkK(=Ti;#(#W2az(muv<%CX%=`zwd@ftkM(*(sa}Y@SYxNqkF|D*qtw zsVt+uq;9FMs4A_h17pHZ6h~xrr9VpkWVoe+4vNEw&qG3HTtmC0HZ)UeHi5 zL-0@_LYgC!knTubq#V)|X^e~qvi@8kS=%F%!gGRI{x9$}?R777uCX_=u~w4XYkp?D zYba;X=zlD%3bAT_-8uaW-Cf-S<85xY?U-$YeX_e#00H{RhsZ&}T)YfvCl}M_#O0tj zaf7m)>L>L!jahS0GgR|P{aEEwc2YX!b!CJ^27Uys=$qthQEy>iED<}0jzjkISs=w! z5Lkd{X9o||W&EG`S{Qe)4c^P!qN~E!gHwZ>gL>!>o##n`KAAhN7LKvjPTVwZ1UKG1 z(ojl&T%W3cs9UYut2?jT1(8*iENPa5)aERLi`^1`YR9&8wl1UC62-j-go$M0_C+UX!2uk6!pi@9@_o0d|R<0hW* ziGG3MqtRvPsPAi7W?s(C>`Crd*@y zrv6JkNmE&ypuG!y;30KKHL2vY2Lty*b(Ib%YX)p0=mSk(vKNB8&9e!7sg!M$qL2OMoegXJxjtX~xa{~=# z`Z?b?-wp397%`pe%7V#oG>)*XoJ|X?xJuks%XsMfd1AuMqs&2*-&7OM=Qyj{_PssF z(Zp@`n7z~ep5R6xh4&JCL0$_9@)1>*ImtejG?xFQc%(2W%Bj|>6V;{RJTWM9mAe#Y zWRs;;q2tl%>EinocjjeHDM4u<{9{TF?My%D#^)yt)I z^>q=}XUX{E}F9%9u7l{aHq9+wRMLWgs$|Mz~bjS4ssfvdg*?=nw&&uiCUc*n}KceCHJ(YA`#c3i+h zaT6@0Wszky^j)vvme{V_hFK%_Y3^(81?~dRuYtVKZxG4;mbVD`i0%@`i+lve9AHuL z81Z|_2)R?f6P{8N6-|{nvZm4ovY%j#aGZDndzP6%*QA<~FGNZ_0VZ~l0JF}(lY&1) z&q#$(gP?+8Y0l!QPQ&(Z6^Opt`me-V)Uzhf`bW*$gF~DH$xOFOdN4?0_^wVv!U| z>Oj9QU+iG^(MPDdR97-nG#Yf&Ul@-~0DrBY`KjRhT?ZnuMg~v$&-mm%uV;?ywzILT zvvZK$45O!*U1ObPv2lsE5!SI>wsn`iHAtG~JPm!NUp%e+!a!B%L1+fE8O#>6Mm54_ z_+wE#wUVZpZOm47v$&c>D|sz;iRVccN}9lv&sa7BPXsKzhrCUUCelSM@ZH!_ECbz% ztP@n^4+P);v~X(ZDm(=w`tO6UlhCuuH5tZ!o%Uh&R<`%ncGgAKoz_R(1M5`V2-{+N zdB-c~ELW0C>&f=72;BDX47GvhwkP~ANRsd(o=k3~Zc=aQpV{N$cj8ZC2gor{x%I%A+%d zlSw_uF^OKoK9}^D4wVc9CfyNfCus-i6v=0H0DG9N&Tgan6IY1m#AN7We~z9(hoY^K zL40}iNTgZRAMOyG>M!(7^7zj5KTto@1gHS{|nM@dk*eWh7>#8^{|6P_S-z^uw{iU1iuw*UU zk6p;>Xg#q?bWJo+v_Uu$9gF-4%>G`y^$}4-8_5eT3(WFW_xASQ^Hz8FbmZAGtY5j8 zAi+@c3u8~C$JE(;)^y8k<}$1=ZFc(z*DCKd-!FmMk!AcBNNHgWVk*6vohNA^tD+dL zbSMc`C6!Ed6ud4@$(^8y(c+WLG~h3GC;q~}2%ln&Ag1!EK+dlR@jvaO!iXothUj2c zAk#nB+t-76@?1k5`?y=CafS?CzVV}Ji0)1P@A}CwDq=9MGxf7RckX~uN3DN$NFg{O zJWXVfh4cwYqVk+3LEB$lT{9)_MVwAEQCUg;v;23tO8Sbf0o>ACBA2i;`n})~u%PzB zTg=sn7$z>N0p9jV*cfp8TL-@es|TujA?n)k%9?0NGBnYNjjs%S3ckyKTUgidPCvt7 zH5FPq+ef&M`ZfgXMq48ayf6J!OiPz4dTZAu{F)G#P$n@YX?MbW?Pk>;1$fg-db4@d zAW;V_2*i{+KtviEP72?TTn7IbBD6GoByu~vK6EoUFt|AQLomg^*Y&}gW*%(ZS1`7K z(;qJwmYtHbq~M*dps=*Qt=VI};Oyo-80gDS7e2t-Qd4DnG#9`}XI4ULin!>$3TtMnR~ys&OV@1nQK~}n&YiQycF*zp@v*UHeeX#yxyJ zPm+?$EG=6zWoVpD^{b+o_asj~Kz>WOpW567>I%TU~5W{PSGRl;s4%q1604_=6~H_e5p!Kaf?xXUYjx1G3KJ=rF-_U;5*x8FVEKW+DR zXnLOlJE!+8h)hFuvZke1l;={KB@Rv+UFxsoOmzzD5bhWJ5KW9EhA;aTx(E2@Mi0Wc zI7Z~Ka}+N1bIk$poe8N(`DMvTHYEDYe;H~VsO#O}C~ZA!@ffP)J;+SXnVz4VUFuWs z7dIcSeLbi^;+*M82#gh+XO)Q)%MYo5r%-X3>L0;M+KbmwyscB8Ugd1q^PskPKV+E4D zDVbN_VvqA*_0mlb^cO5frV6)9`XphMwUx`39;dx0$)a8pLxrWncIPJBTl;zUuR$Kt ziJ%$3_>rnca-dB0((1UM<$pUGq1-f-VB_dw4Bm&kG1@x^;d zFhWAa`x8ee7~=;ghf3KKCn>9vR>2#7L&0vre8G7^E$EN9%-;*#mq4JqlQ#Ft&&+6> zZpdIV_I&E`_K%mHUz)y%Y`;W0<9V_jiG`*6l`mC(Nn)WSfn>46L4kdQajbcvyD%Kb zePUqfrleD3l2CCuEhGrh+9YM&b!UWd-otyEpL9pkzsxk@1^hgJD_ia+S+?)+qL>uBsF zp-0q(3?{3p50txIC9ZsG{6@uf=|EN~LivkB%|mH|R7x+dBuQgtQ>%rC!V?|6^^%-Q z=_5bSefQhDQeQh4EHp^+-hY1dX}V!Nwob!O^d{7SGkK0ms_sQ6hnu+jxb{0fI;8&5 z{GWwkqO16nl1UVn)~582OHe))FBE;`{{nLtZA0UTT=uiPx3Z1AH9HsI6P7u~7s}HM z-Y{Hh)xo*C>qGhmYK>pRVoKH&%l#zMzg$bV$C&V4pq-m4Yn`i-VfG^@+=W)7@ zIluU(AOSicpQX8+a3w{YQa*mOd^NKKKfrq$$_lLze4xTGLh!RZ%03WP=BN0~7BX*J z+WvQs-X?w7o8Qu8Ft0HA3L1au_4Zu$<-kkvvG@l`S5w-S>XYl}3GG_DuNtCNxw%PuZ;IsTwx4ttTjD6GgMg9F2>(ILzz)xr2Wadl-2L_MNCJu59s z@&=~$ef#~}5ubVan6;I2n7yIVkvaL@lMh?Wm$Au;KNH(l>{?}93NG#^aD;CLYPxH3 zJxu$o%YAJygT$90u9#oxXz3lwXH;|iIns!K0%ji@BFMl;uu;{mC3!4#B|tJ*V)-+vTx9z{WSi0->>gI>EvE@yRzM?RjF`63GZ*N)$SjB zbKT4Ac8A&*FQ~u{k4r4~tm3`WWdLG9h0h1~g~#xh;=S01^54`0wZ6D(aeb9*32Eq^ zt+sw{&h@WnzHZGfqvzSKx~#4XHo5sk{>u-_$8BF-HDK;iPNV*)iNSPo_p?!FH zG!P!*er?>Co0^@HS4r2?+{{JzmpL06`scj=YIw8!X-3)vPYr3K(g&;Ft^c`pBw=P~ zdj58pi0SA2QI_k$W+Fn`K=o4HKfzw=mr{=vZG`7Si2E1k#XvP;iv};b_73$b%9#$qug%8Q=L+8)4w&&v9GCndue#|M>^l1Cs|psOe0>y z(xngKi@BSbPcjbW4A)D19mw~R-z7_AZIL7ZESr_oRuR0pqt6Dv#xL9AfwXD09e_?>}H*?G^==+X&D0}^r4vpSYO{zYs z@g%q%Y52X(PqOc4w8&rV$QLkdfZ5Aj6Bn>OnIG7dlH2SQ(FwtFUL8R%(Rgt)b-Tnb z2~X7nB`i@J?jThl{<4dg@(g!sY&R@9;Kw)5{KR_A(ZGRl2?Z%>72a3Oy6ISsrNs$r zUZ``tY>IeT;Do+XM)wR};S~2w zzI1Yp#NSnUba!-Rc(KQCH`=<`o%XX1x8sUEY(;Ikw$6_I&hm~QOho37?<=QwF~0Nf zl3c2+_^x)v+KRK$-9|@xyRWqhhq%Y0*>o+j9Y!4jgjl2`D=_sKA+-fJATtF{m8D%LoH9>k&k9FRUBAzJ-#hZ^ zc#=gKNtJ4bt2NNH=8LRtb3$JaWKXmmLQb>!&?}fup`t73Ol+M<&WOeH$xKX%RTSon zve{qN-4f#CC#kc=0pXiy_2B+MM_`*Q3QY}c_AYXEvo5iO&2_CKool>PeSF7(0tCjn z))oZaEHNX+RPA+z$+8BK#ayTCXJ1F<)G|E@+C+E7FC<$Ssi-k}Oz<45Nq-U7XX_Jp zg(I<9=z9?(4XQuK?bn3lD;YE9jqD5L1|9+_FFCv?v?-A2(b~InGr0!#HLm;a$rkT{m+R1U$7 zEbGI-UTh=jrkapzvFb=VatJkH&xvJp53;9dF!b{JVfLM5RjS6LY%1F&ZciQ%tP6)j zi=r0(V(cwZmzs@#7k%k9JI-=_%qUmQdC48`+-+T9dR17ZKnPc`?ZG{wY}pD$BS|i5 zb4}MR%&rf^96sk7!3DwwUU0{W8K{!Co{ysKg#AP{h`r=rl%4vCc8Xgn-YE-|uhs3< zanb?A1!OO;MI=7L@)cMm@Rl5kN|E+FK@fb)oZaoGIg!N=qXN%$l?r+oR$0GyjSjv= z50Z(Zwn$Pq+j)fBZeD7>#MN+b3Gt&EK_#pKb^Lqj8$(K;9)U1G(uOyH|2v zvQpYZ{!GzPK1sS(Y7l><0=N@1Bk4fyz9MiVrO-5FC;xFM)BPj#W$ff8Tf;D;LZWT4 zAuoTH&S6~6b@QTVCvr9Z4$(vc&Rr&3gj=e12#*zm}mgw z*A?j%G|5z8?c&SQ0{I1{QMp2qB=01B!b~QHzwMo zYYi9+^gRuWOsFN(n5I`5cbRKi=ePz(c-U`fZ$am16W=(lmoBrQlTK$^>^>H4g_k1B zkzI+U!kaLD|2;Mme^bgV5*iBZ2qa1YW2$+yGh!CjqF%ENBoo=y5ZkV$22vFngQSjPpt8C0pklCm zw`3}_lA1`$iHrCxVH!3aMPMwWG&%|0g4JHnBSz=mCrS@xF0o`q9!XM?tzc%asC}-6BZDD6%`VVMGLWN$Vpz)aQi^A zPw(F3Tm<81lx>N1K9^~xO=S%EI;SDPwQ`~UW?`6>HJt7J(e=ch0Y2LA-LHaAqhY}+ zRFBw!L2ctrLnh%eiev`@n5hS|g}g$HhJNjO;*0VQs&`6O{;N2SIxd`!8qgf!LD2)E zDQObI>mf>R zPk49eoqv+2ooj<@hi8X>RrnQuAZkQ11@{Fz1n&h#bb+V^bq}Urr`ZQ|Pncz`DcJ<( zxtJh+Cpjj)ASuO;rnKPcR0msz{UqEb><7^p50NT>651X<96BCK01|$FaBtw5ucN1L zEQZ_J&^ZA9hC3{_8P;c9J?m4O!BNWd%-{mw}|aT9*h(!$)02o#yXRzUSuso4jx-ZfmARbCN>|> zuLDf2)%>=+Tao23Q)Gf~fOiE@=yONIzMdY(OM} zfB9!2gKx#Fi84fC5h2i!vmhckl>c!>frF;=-}hvppZZ0 zfq5{pfjUzN#IW+<(bgZv>oWL*1uq4qk>$ue@ZH*rtU=l$I-r_4!Fno*x@PxE_e>C7zAP!ssrgM4@gE7FB6DdYk={V9ytQDC{2tEjjWG6 z1$JBr=xq>#0jaORD`*^Wo@BuLY6H|Qn)d>@`wgRIU=y6ETc1^6Coc1oAdE< zc^_d8cM@iCXv}W|_4V?e0|TWa5SIubo?QFJM>+z`sT)88$^kM^GO&+Y!f{cc6Rn1t zy#|`wGMF{@=g1f6D?bD>jt2tU5}=FIKq&eN$Ti;sjb$&8e98jBdogHWH4u?z@g_o) z{S=tTygRV5q&yCIIoZH9Y6N9}{3eYANFqCd5XC|)_MhNyxF1MY_kcteV{nxMyXX$H zMo$KPeGg10574e2fUM_0+Uvmlxe0`-dmyhVDgoWK2HH*!AfLr%We5S$=^1c_9s`L= z3N)lXz(!gC1pV&tn*i;;1g=ma5VRTqF>L~G8q}p5?56?ZP%iA519=wEfgJckHQ^lT z1VpZmz)GqHbQlIkFinvEHTo8)RW@K>DS_P36t=1l-&!EZ7(vRnKrTvywhRGpO9@1{ zvY=-zu)t(cIuD3a?r4n07JxbeDjZm3F3<@d*jEH>9V3)!;2VMZIzSE+Y|V!paL9)R zgYqpf_8g--`G98?2S=_5BsMj)Q~ywz@CE6@_`H$0c~p_Cl3Cz zAP)+>Dj`Ux02$Pfrhrrm78dlUg|;XQ1hz7eih|@Z{#Q20U%{iA4&iq5lCl*ZQn!LA7QUtsILoZ90EEOs1S68gFVG$tO%^KGQjm$z_Dm3GXd7? zf*rJgzlP9$<-l@Ou*763&#Ma3ln0%~!QKRL(+H4M0=e<9pBChy;K)JHof~w(gZvmV zE*_RRI6edGvHD{09otI=H7KfcJe)6Opxi1z4yy}GZLpOJP)gFbeG|UrmVczxOy0B5@XbfKtJMdt%E~Otd>?dE`-s-pZS|TxS-xJ!7m(> zgA_fqcMe!XI#@_1ELpH_0PC{Bwl>H&f@HanngMw^V0i|R7y6H3U)#5BVpbTlvDnrz zJB|_cV%F#WX7{mrcp={kspfCFu`Oc14Br<0H_I)AGKw@1Ti1WfF@D>+$g=<5s;Cwm z9FKz~rWf0{-$lP-GCRS7ifZVF@1nJsbP((glK4QYevl~$`ig)yV;?}ff$n0zVrOSe zhcR2nq3y_Tnl9FM%#K8`#Izo3%h(bl2gcer*21wr{{PA;$}egq42~9Sbpnn^d~3Iu zMKaJ%MN90QXQ18KZ|f|4OTZ>$OYs)5wAdCD{Kc*j;Dq%}x|js91^u5^R#cCoI>qW$ zyubuK-)ada@xMMXiIHzI$C6_8FV2eD6c5hX@ITUu@`@}i1o|slV(lCI<^QJH*jmw2 zlpBIG`R^qrK}?R=-l1>5VtOzB6zMRwR#bXSmqqPSq}SLPRJ0VW$7KI|iLJ$S5Nny( zQgpV(+UB22tc>DqidrqU9y=3bpQ09w9lhui(??OMMVgB39s9)O`se3wNsA`X2?c1+Tkj4@j-k}hVyMJchgSpNS`4@K$4S}xW{@p`OXiq4W) z3;bU{|EkmC@{3A~RWVj_acWU*V>K!|L;pTn@iu>_{M%ne<@{}(|2Ds9{a>Z|-*5Bp zr^f1DRR3bDEY{cG)>ovLBKs~%Ez(f&7P0S`mH(@}v9;n)Q7QkL63hL2i{dT+dwdtQ z<$n)ZN~HMzRs;W88~xAj_aD{v|BYk*N9Fxz^8Qbd@jp|q|8w^F=XLhKht&U`ME^GZ zpSJVQ-~X(|f3#2WcK>#p;`Ea5|Nm;>|4Ezwd$#por=9<_4@iYFvEv}`ak~{%Tt^m zTQBU(Ljj?N;FWSff5ar zXrM#`B^oHvK#2xQG*F^}5)G7SphN>D8Ys~~i3UnEP@;hn4U}l0L<1!nDA7QP21+zg zqJa_(lxUzt10@D8u-s? G;C}#px^@@< literal 0 HcmV?d00001 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/conftest.py b/sdk/cognitiveservices/azure-ai-transcription/tests/conftest.py index 2062175edbe0..bff6314d9826 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/conftest.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/conftest.py @@ -23,10 +23,7 @@ @pytest.fixture(scope="session") def transcription_endpoint(): """Fixture providing the transcription endpoint.""" - return os.environ.get( - "TRANSCRIPTION_ENDPOINT", - "https://fakeendpoint.cognitiveservices.azure.com" - ) + return os.environ.get("TRANSCRIPTION_ENDPOINT", "https://fakeendpoint.cognitiveservices.azure.com") @pytest.fixture(scope="session") @@ -38,10 +35,7 @@ def transcription_api_key(): @pytest.fixture(scope="session") def transcription_test_audio_url(): """Fixture providing a test audio URL.""" - return os.environ.get( - "TRANSCRIPTION_TEST_AUDIO_URL", - "https://example.com/test-audio.wav" - ) + return os.environ.get("TRANSCRIPTION_TEST_AUDIO_URL", "https://example.com/test-audio.wav") # autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method @@ -58,38 +52,26 @@ def add_sanitizers(test_proxy): # This allows recordings made with API key auth to work with AAD auth in CI set_custom_default_matcher( excluded_headers="Authorization,Ocp-Apim-Subscription-Key", - ignored_headers="Authorization,Ocp-Apim-Subscription-Key" + ignored_headers="Authorization,Ocp-Apim-Subscription-Key", ) - + # Sanitize subscription and tenant IDs if they exist # Only sanitize if the values are actually set (not default fake values) transcription_subscription_id = os.environ.get("TRANSCRIPTION_SUBSCRIPTION_ID", "") if transcription_subscription_id and transcription_subscription_id != "00000000-0000-0000-0000-000000000000": - add_general_regex_sanitizer( - regex=transcription_subscription_id, - value="00000000-0000-0000-0000-000000000000" - ) - + add_general_regex_sanitizer(regex=transcription_subscription_id, value="00000000-0000-0000-0000-000000000000") + transcription_tenant_id = os.environ.get("TRANSCRIPTION_TENANT_ID", "") if transcription_tenant_id and transcription_tenant_id != "00000000-0000-0000-0000-000000000000": - add_general_regex_sanitizer( - regex=transcription_tenant_id, - value="00000000-0000-0000-0000-000000000000" - ) - + add_general_regex_sanitizer(regex=transcription_tenant_id, value="00000000-0000-0000-0000-000000000000") + transcription_client_id = os.environ.get("TRANSCRIPTION_CLIENT_ID", "") if transcription_client_id and transcription_client_id != "00000000-0000-0000-0000-000000000000": - add_general_regex_sanitizer( - regex=transcription_client_id, - value="00000000-0000-0000-0000-000000000000" - ) - + add_general_regex_sanitizer(regex=transcription_client_id, value="00000000-0000-0000-0000-000000000000") + transcription_client_secret = os.environ.get("TRANSCRIPTION_CLIENT_SECRET", "") if transcription_client_secret and transcription_client_secret != "00000000-0000-0000-0000-000000000000": - add_general_regex_sanitizer( - regex=transcription_client_secret, - value="00000000-0000-0000-0000-000000000000" - ) + add_general_regex_sanitizer(regex=transcription_client_secret, value="00000000-0000-0000-0000-000000000000") # Sanitize endpoint URLs transcription_endpoint = os.environ.get( @@ -97,8 +79,7 @@ def add_sanitizers(test_proxy): ) if transcription_endpoint and "fake" not in transcription_endpoint.lower(): add_general_string_sanitizer( - target=transcription_endpoint, - value="https://fake-transcription-endpoint.cognitiveservices.azure.com/" + target=transcription_endpoint, value="https://fake-transcription-endpoint.cognitiveservices.azure.com/" ) # Sanitize API keys in headers @@ -115,17 +96,18 @@ def add_sanitizers(test_proxy): # Sanitize audio URLs in request/response bodies add_body_key_sanitizer(json_path="$..audioUrl", value="https://fake-audio-url.blob.core.windows.net/audio/test.wav") - add_body_key_sanitizer(json_path="$..audio_url", value="https://fake-audio-url.blob.core.windows.net/audio/test.wav") + add_body_key_sanitizer( + json_path="$..audio_url", value="https://fake-audio-url.blob.core.windows.net/audio/test.wav" + ) # Sanitize storage account names and blob URLs add_uri_regex_sanitizer( - regex=r"https://[a-z0-9]+\.blob\.core\.windows\.net", - value="https://fakeaccount.blob.core.windows.net" + regex=r"https://[a-z0-9]+\.blob\.core\.windows\.net", value="https://fakeaccount.blob.core.windows.net" ) - + # Sanitize cognitive services hostnames to handle different endpoint formats # This handles both api.cognitive.microsoft.com and cognitiveservices.azure.com add_uri_regex_sanitizer( regex=r"https://[^/]+\.(api\.cognitive\.microsoft\.com|cognitiveservices\.azure\.com)", - value="https://Sanitized.cognitiveservices.azure.com" + value="https://Sanitized.cognitiveservices.azure.com", ) diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/preparer.py b/sdk/cognitiveservices/azure-ai-transcription/tests/preparer.py index 44c2ce052593..c710153e9f90 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/preparer.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/preparer.py @@ -17,39 +17,33 @@ class TranscriptionClientTestBase(AzureRecordedTestCase): def create_client(self, endpoint, **kwargs): """Create a synchronous TranscriptionClient for testing.""" # Try to get API key from environment or kwargs - api_key = kwargs.pop('transcription_api_key', os.environ.get('TRANSCRIPTION_API_KEY')) - + api_key = kwargs.pop("transcription_api_key", os.environ.get("TRANSCRIPTION_API_KEY")) + if api_key: # Use API key authentication credential = AzureKeyCredential(api_key) else: # Fall back to default credential credential = self.get_credential(TranscriptionClient) - + return self.create_client_from_credential( - TranscriptionClient, - credential=credential, - endpoint=endpoint, - **kwargs + TranscriptionClient, credential=credential, endpoint=endpoint, **kwargs ) def create_async_client(self, endpoint, **kwargs): """Create an asynchronous TranscriptionClient for testing.""" # Try to get API key from environment or kwargs - api_key = kwargs.pop('transcription_api_key', os.environ.get('TRANSCRIPTION_API_KEY')) - + api_key = kwargs.pop("transcription_api_key", os.environ.get("TRANSCRIPTION_API_KEY")) + if api_key: # Use API key authentication credential = AzureKeyCredential(api_key) else: # Fall back to default credential credential = self.get_credential(AsyncTranscriptionClient, is_async=True) - + return self.create_client_from_credential( - AsyncTranscriptionClient, - credential=credential, - endpoint=endpoint, - **kwargs + AsyncTranscriptionClient, credential=credential, endpoint=endpoint, **kwargs ) @@ -59,5 +53,5 @@ def create_async_client(self, endpoint, **kwargs): "transcription", transcription_endpoint="https://fakeendpoint.cognitiveservices.azure.com", transcription_api_key="fake-api-key", - transcription_test_audio_url="https://example.com/test-audio.wav" + transcription_test_audio_url="https://example.com/test-audio.wav", ) diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic.py index a6c8f8d51c60..e7975722d09d 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic.py @@ -17,10 +17,10 @@ class TestTranscriptionBasic(TranscriptionClientTestBase): def test_transcribe_url_basic(self, transcription_endpoint, transcription_test_audio_url): """Test basic transcription from a URL.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url result = client.transcribe_from_url(audio_url) - + # Verify response structure assert result is not None assert result.combined_phrases is not None @@ -32,15 +32,12 @@ def test_transcribe_url_basic(self, transcription_endpoint, transcription_test_a def test_transcribe_with_custom_locale(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with a specific locale.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"] - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US"]) + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -50,22 +47,22 @@ def test_transcribe_with_custom_locale(self, transcription_endpoint, transcripti def test_transcribe_result_structure(self, transcription_endpoint, transcription_test_audio_url): """Test that the transcription result has the expected structure.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url result = client.transcribe_from_url(audio_url) - + # Verify result structure assert result is not None - assert hasattr(result, 'combined_phrases') - assert hasattr(result, 'phrases') - assert hasattr(result, 'duration_milliseconds') - + assert hasattr(result, "combined_phrases") + assert hasattr(result, "phrases") + assert hasattr(result, "duration_milliseconds") + # Verify combined_phrases structure assert len(result.combined_phrases) > 0 - assert hasattr(result.combined_phrases[0], 'text') + assert hasattr(result.combined_phrases[0], "text") assert result.combined_phrases[0].text is not None - + # If phrases exist, verify their structure if result.phrases: phrase = result.phrases[0] - assert hasattr(phrase, 'text') + assert hasattr(phrase, "text") diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic_async.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic_async.py index 2cbf4edba578..f18bd9cbc002 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_basic_async.py @@ -17,12 +17,12 @@ class TestTranscriptionBasicAsync(TranscriptionClientTestBase): async def test_transcribe_url_basic_async(self, transcription_endpoint, transcription_test_audio_url): """Test basic async transcription from a URL.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: audio_url = transcription_test_audio_url - + result = await client.transcribe_from_url(audio_url) - + # Verify response structure assert result is not None assert result.combined_phrases is not None @@ -34,18 +34,15 @@ async def test_transcribe_url_basic_async(self, transcription_endpoint, transcri async def test_transcribe_with_custom_locale_async(self, transcription_endpoint, transcription_test_audio_url): """Test async transcription from URL with custom locale.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: audio_url = transcription_test_audio_url - + # Create transcription options - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"] - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US"]) + result = await client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -56,24 +53,24 @@ async def test_transcribe_with_custom_locale_async(self, transcription_endpoint, async def test_transcribe_result_structure_async(self, transcription_endpoint, transcription_test_audio_url): """Test that async transcription result has expected structure.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: audio_url = transcription_test_audio_url - + result = await client.transcribe_from_url(audio_url) - + # Verify result structure assert result is not None - assert hasattr(result, 'combined_phrases') - assert hasattr(result, 'phrases') - assert hasattr(result, 'duration_milliseconds') - + assert hasattr(result, "combined_phrases") + assert hasattr(result, "phrases") + assert hasattr(result, "duration_milliseconds") + # Verify combined_phrases structure assert len(result.combined_phrases) > 0 - assert hasattr(result.combined_phrases[0], 'text') + assert hasattr(result.combined_phrases[0], "text") assert result.combined_phrases[0].text is not None - + # If phrases exist, verify their structure if result.phrases: phrase = result.phrases[0] - assert hasattr(phrase, 'text') + assert hasattr(phrase, "text") diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management.py index d2227b0eb6f6..049ffc40ac3e 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management.py @@ -18,7 +18,7 @@ def test_client_context_manager(self, transcription_endpoint, transcription_test with self.create_client(endpoint=transcription_endpoint) as client: audio_url = transcription_test_audio_url result = client.transcribe_from_url(audio_url) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -28,11 +28,11 @@ def test_client_context_manager(self, transcription_endpoint, transcription_test def test_client_close(self, transcription_endpoint, transcription_test_audio_url): """Test explicit client close.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url result = client.transcribe_from_url(audio_url) - + assert result is not None - + # Explicitly close the client client.close() diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management_async.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management_async.py index 56556f4d7e14..f27755e8cc29 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_client_management_async.py @@ -18,8 +18,8 @@ async def test_client_context_manager_async(self, transcription_endpoint, transc # Test creating and using client with context manager async with self.create_async_client(endpoint=transcription_endpoint) as client: audio_url = transcription_test_audio_url - + result = await client.transcribe_from_url(audio_url) - + assert result is not None assert result.combined_phrases is not None diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization.py index 5db09bdcbf18..0820a9cbea36 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization.py @@ -17,18 +17,16 @@ class TestTranscriptionDiarization(TranscriptionClientTestBase): def test_transcribe_with_diarization_enabled(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with speaker diarization enabled.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - + # Enable diarization options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"], - diarization_options=TranscriptionDiarizationOptions(max_speakers=2) + audio_url=audio_url, locales=["en-US"], diarization_options=TranscriptionDiarizationOptions(max_speakers=2) ) - + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert result.phrases is not None diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization_async.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization_async.py index 65ac87621ac5..fe862b88d34a 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_diarization_async.py @@ -14,23 +14,25 @@ class TestTranscriptionDiarizationAsync(TranscriptionClientTestBase): @TranscriptionPreparer() @recorded_by_proxy_async - async def test_transcribe_with_diarization_enabled_async(self, transcription_endpoint, transcription_test_audio_url): + async def test_transcribe_with_diarization_enabled_async( + self, transcription_endpoint, transcription_test_audio_url + ): """Test async transcription with speaker diarization enabled.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: # For diarization, ideally use multi-speaker audio, but single-speaker works for testing audio_url = transcription_test_audio_url - + # Enable diarization options = TranscriptionOptions( audio_url=audio_url, locales=["en-US"], - diarization_options=TranscriptionDiarizationOptions(max_speakers=2) + diarization_options=TranscriptionDiarizationOptions(max_speakers=2), ) - + result = await client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert result.phrases is not None diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_enhanced_mode.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_enhanced_mode.py index ca0e72489ccc..391eac7a2d10 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_enhanced_mode.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_enhanced_mode.py @@ -17,21 +17,20 @@ class TestTranscriptionEnhancedMode(TranscriptionClientTestBase): def test_transcribe_enhanced_mode_with_prompt(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with enhanced mode and prompt.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - + # Use enhanced mode with prompts options = TranscriptionOptions( audio_url=audio_url, locales=["en-US"], enhanced_mode=EnhancedModeProperties( - prompt=["This is a technical discussion about Azure services"], - task="transcribe" - ) + prompt=["This is a technical discussion about Azure services"], task="transcribe" + ), ) - + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file.py index d5065bacdfd9..3974dfdf95f8 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file.py @@ -18,23 +18,20 @@ class TestTranscriptionFile(TranscriptionClientTestBase): def test_transcribe_wav_file(self, transcription_endpoint): """Test transcription from a local WAV file.""" client = self.create_client(endpoint=transcription_endpoint) - + # Path to test audio file test_audio_path = os.path.join(os.path.dirname(__file__), "assets", "audio.wav") - + # Skip test if audio file doesn't exist if not os.path.exists(test_audio_path): pytest.skip(f"Test audio file not found: {test_audio_path}") - + with open(test_audio_path, "rb") as audio_file: # Create transcription content with audio file and options - content = TranscriptionContent( - definition=TranscriptionOptions(locales=["en-US"]), - audio=audio_file - ) - + content = TranscriptionContent(definition=TranscriptionOptions(locales=["en-US"]), audio=audio_file) + result = client.transcribe(body=content) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file_async.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file_async.py index 259bde4f9d24..cb31674c9f24 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_file_async.py @@ -18,24 +18,21 @@ class TestTranscriptionFileAsync(TranscriptionClientTestBase): async def test_transcribe_wav_file_async(self, transcription_endpoint): """Test async transcription with a local WAV audio file.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: # Path to test audio file test_audio_path = os.path.join(os.path.dirname(__file__), "assets", "audio.wav") - + # Skip test if audio file doesn't exist (for initial setup) if not os.path.exists(test_audio_path): pytest.skip(f"Test audio file not found: {test_audio_path}") - + with open(test_audio_path, "rb") as audio_file: # Create transcription content with audio file and options - content = TranscriptionContent( - definition=TranscriptionOptions(locales=["en-US"]), - audio=audio_file - ) - + content = TranscriptionContent(definition=TranscriptionOptions(locales=["en-US"]), audio=audio_file) + result = await client.transcribe(body=content) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options.py index 42fba23dda07..4eabfeefe920 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options.py @@ -17,16 +17,12 @@ class TestTranscriptionOptions(TranscriptionClientTestBase): def test_transcribe_profanity_filter_raw(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with no profanity filtering.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"], - profanity_filter_mode="None" - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US"], profanity_filter_mode="None") + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -36,16 +32,12 @@ def test_transcribe_profanity_filter_raw(self, transcription_endpoint, transcrip def test_transcribe_profanity_filter_masked(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with profanity masking.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"], - profanity_filter_mode="Masked" - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US"], profanity_filter_mode="Masked") + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert result.combined_phrases[0].text is not None @@ -55,16 +47,12 @@ def test_transcribe_profanity_filter_masked(self, transcription_endpoint, transc def test_transcribe_profanity_filter_removed(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with profanity filter set to Removed.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"], - profanity_filter_mode="Removed" - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US"], profanity_filter_mode="Removed") + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None @@ -73,21 +61,18 @@ def test_transcribe_profanity_filter_removed(self, transcription_endpoint, trans def test_transcribe_with_phrase_list(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with a custom phrase list for better recognition.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - + # Add custom phrases for better recognition options = TranscriptionOptions( audio_url=audio_url, locales=["en-US"], - phrase_list=PhraseListProperties( - phrases=["Azure", "Cognitive Services", "Speech SDK"], - biasing_weight=1.0 - ) + phrase_list=PhraseListProperties(phrases=["Azure", "Cognitive Services", "Speech SDK"], biasing_weight=1.0), ) - + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -98,17 +83,14 @@ def test_transcribe_with_phrase_list(self, transcription_endpoint, transcription def test_transcribe_multiple_locales(self, transcription_endpoint, transcription_test_audio_url): """Test transcription with multiple locales specified.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url - + # Specify multiple locales for auto-detection - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US", "es-ES", "fr-FR"] - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US", "es-ES", "fr-FR"]) + result = client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options_async.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options_async.py index e15d5691149a..3b83268da4b1 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_options_async.py @@ -17,18 +17,14 @@ class TestTranscriptionOptionsAsync(TranscriptionClientTestBase): async def test_transcribe_profanity_filter_masked_async(self, transcription_endpoint, transcription_test_audio_url): """Test async transcription with masked profanity filter.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: audio_url = transcription_test_audio_url - - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US"], - profanity_filter_mode="Masked" - ) - + + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US"], profanity_filter_mode="Masked") + result = await client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -38,22 +34,21 @@ async def test_transcribe_profanity_filter_masked_async(self, transcription_endp async def test_transcribe_with_phrase_list_async(self, transcription_endpoint, transcription_test_audio_url): """Test async transcription with custom phrase list.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: audio_url = transcription_test_audio_url - + # Add custom phrases for better recognition options = TranscriptionOptions( audio_url=audio_url, locales=["en-US"], phrase_list=PhraseListProperties( - phrases=["Azure", "Cognitive Services", "Speech SDK"], - biasing_weight=1.0 - ) + phrases=["Azure", "Cognitive Services", "Speech SDK"], biasing_weight=1.0 + ), ) - + result = await client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 @@ -64,19 +59,16 @@ async def test_transcribe_with_phrase_list_async(self, transcription_endpoint, t async def test_transcribe_multiple_locales_async(self, transcription_endpoint, transcription_test_audio_url): """Test async transcription with multiple language locales.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: # For multi-locale, ideally use multilingual audio, but single language works for testing audio_url = transcription_test_audio_url - + # Specify multiple locales for auto-detection - options = TranscriptionOptions( - audio_url=audio_url, - locales=["en-US", "es-ES", "fr-FR"] - ) - + options = TranscriptionOptions(audio_url=audio_url, locales=["en-US", "es-ES", "fr-FR"]) + result = await client.transcribe_from_url(audio_url, options=options) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url.py index 971767fc39be..bccd243bb905 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url.py @@ -16,10 +16,10 @@ class TestTranscriptionUrl(TranscriptionClientTestBase): def test_transcribe_from_public_url(self, transcription_endpoint, transcription_test_audio_url): """Test transcription from a publicly accessible URL.""" client = self.create_client(endpoint=transcription_endpoint) - + audio_url = transcription_test_audio_url result = client.transcribe_from_url(audio_url) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url_async.py b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url_async.py index d46e53b47aee..ecdda3468b2b 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url_async.py +++ b/sdk/cognitiveservices/azure-ai-transcription/tests/test_transcription_url_async.py @@ -16,12 +16,12 @@ class TestTranscriptionUrlAsync(TranscriptionClientTestBase): async def test_transcribe_from_public_url_async(self, transcription_endpoint, transcription_test_audio_url): """Test async transcription from a public URL.""" client = self.create_async_client(endpoint=transcription_endpoint) - + async with client: audio_url = transcription_test_audio_url - + result = await client.transcribe_from_url(audio_url) - + assert result is not None assert result.combined_phrases is not None assert len(result.combined_phrases) > 0 diff --git a/sdk/cognitiveservices/azure-ai-transcription/tsp-location.yaml b/sdk/cognitiveservices/azure-ai-transcription/tsp-location.yaml index 845205d658bc..bb0f9e351615 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/tsp-location.yaml +++ b/sdk/cognitiveservices/azure-ai-transcription/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/cognitiveservices/Speech.Transcription -commit: 5f88489f000c7471e9517b5f1f27f2fb61aacc50 +commit: 6bd84f27b7a056fc6e916e2e9fefa9fdba1d72d2 repo: Azure/azure-rest-api-specs additionalDirectories: From 29ce7609a256abc7d06557c99d5d641483dfc8bb Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Wed, 4 Feb 2026 13:14:15 -0800 Subject: [PATCH 47/84] Increment package version after release of azure-monitor-opentelemetry (#45001) Co-authored-by: rads-1996 --- sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md | 10 ++++++++++ .../azure/monitor/opentelemetry/_version.py | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md index 235820ac94d0..96ce10a71e7e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.8.7 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.8.6 (2026-02-05) ### Features Added diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_version.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_version.py index 5fe552ec7aae..967e4297be34 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_version.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_version.py @@ -4,4 +4,4 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "1.8.6" +VERSION = "1.8.7" From 61c6ddee1e6c3800311ed498f505c5c8c04b9b5a Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Wed, 4 Feb 2026 14:22:12 -0800 Subject: [PATCH 48/84] Fix CPU usage calculation logic for live metrics (#45005) * Fix CPU total usage calculation logic for live metrics * Modify CHANGELOG --- .../CHANGELOG.md | 2 ++ .../exporter/_quickpulse/_cpu.py | 6 +++-- .../tests/quickpulse/test_cpu.py | 27 ++++++++++++++++++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index bd9f2cbd852b..47e55f37f2ac 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -7,6 +7,8 @@ ### Breaking Changes ### Bugs Fixed +- Fix CPU usage calculation logic for live metrics + ([#45005](https://github.com/Azure/azure-sdk-for-python/pull/45005)) ### Other Changes - Fix Ingestion-Side Sampling Disk Persist Behavior diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_cpu.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_cpu.py index b8ab93b8b76c..1d5245cac7c4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_cpu.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_cpu.py @@ -41,7 +41,7 @@ def _get_process_time_normalized_old(options: CallbackOptions) -> Iterable[Obser # total process time is user + system in s total_time_s = cpu_times.user + cpu_times.system process_time_s = total_time_s - _get_quickpulse_last_process_time() - _set_quickpulse_last_process_time(process_time_s) + _set_quickpulse_last_process_time(total_time_s) # Find elapsed time in s since last collection current_time = datetime.now() elapsed_time_s = (current_time - _get_quickpulse_process_elapsed_time()).total_seconds() @@ -49,7 +49,9 @@ def _get_process_time_normalized_old(options: CallbackOptions) -> Iterable[Obser # Obtain cpu % by dividing by elapsed time cpu_percentage = process_time_s / elapsed_time_s # Normalize by dividing by amount of logical cpus - normalized_cpu_percentage = cpu_percentage / NUM_CPUS + normalized_cpu_percentage = (cpu_percentage / NUM_CPUS) * 100 + # Cap at 100% to avoid edge cases where the CPU usage goes over 100% + normalized_cpu_percentage = min(normalized_cpu_percentage, 100) _set_quickpulse_last_process_cpu(normalized_cpu_percentage) except (psutil.NoSuchProcess, psutil.AccessDenied, ZeroDivisionError): pass diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_cpu.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_cpu.py index 56a458c0a733..e4506eebf3d4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_cpu.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_cpu.py @@ -48,7 +48,32 @@ def test_process_time(self, process_mock, process_time_mock, elapsed_time_mock): time = _get_process_time_normalized_old(None) obs = next(time) num_cpus = psutil.cpu_count() - self.assertAlmostEqual(obs.value, 1.2 / num_cpus, delta=1) + expected_value = (1.2 / num_cpus) * 100 + self.assertAlmostEqual(obs.value, expected_value, delta=1) + + @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._cpu._get_quickpulse_process_elapsed_time") + @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._cpu._get_quickpulse_last_process_time") + @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._cpu.PROCESS") + def test_process_time_capped_at_100(self, process_mock, process_time_mock, elapsed_time_mock): + """Test that CPU percentage is capped at 100% even when raw calculation exceeds it.""" + current = datetime.now() + cpu = collections.namedtuple("cpu", ["user", "system"]) + # Simulate extreme CPU usage that would calculate > 100% + # Total CPU time: 200 seconds + cpu_times = cpu(user=100.0, system=100.0) + process_mock.cpu_times.return_value = cpu_times + # Previous total was 0 (first measurement) + process_time_mock.return_value = 0.0 + # Only 1 second elapsed + elapsed_time_mock.return_value = current - timedelta(seconds=1) + with mock.patch("datetime.datetime") as datetime_mock: + datetime_mock.now.return_value = current + time = _get_process_time_normalized_old(None) + obs = next(time) + num_cpus = psutil.cpu_count() + # Without cap: (200 / 1 / num_cpus) * 100 = (200 / 16) * 100 = 1250% + # With cap: Should be 100% + self.assertEqual(obs.value, 100) # cSpell:enable From 21ce002e2232a0e10ddf069703f1baf0c7819e10 Mon Sep 17 00:00:00 2001 From: Yuchao Yan Date: Thu, 5 Feb 2026 13:58:29 +0800 Subject: [PATCH 49/84] [pipeline] Add triggered pipeline link to auto-release PR body (#45026) * Add triggered pipeline link to auto-release PR body * Update scripts/auto_release/main.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update scripts/auto_release/main.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- scripts/auto_release/PythonSdkLiveTest.yml | 1 + scripts/auto_release/main.py | 10 ++++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/auto_release/PythonSdkLiveTest.yml b/scripts/auto_release/PythonSdkLiveTest.yml index ecda936267be..bebc4c1d587c 100644 --- a/scripts/auto_release/PythonSdkLiveTest.yml +++ b/scripts/auto_release/PythonSdkLiveTest.yml @@ -89,6 +89,7 @@ jobs: export SCRIPT_PATH=$script_path export BOT_TOKEN=$(azuresdk-github-pat) export GIT_TOKEN=$(Yuchao-GitToken) + export TRIGGERED_PIPELINE_LINK="$(System.CollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)" export PYTHON_TAG=$(PYTHON_TAG) export DEBUG_SDK_BRANCH=$(DEBUG_SDK_BRANCH) export TARGET_DATE=$(TARGET_DATE) diff --git a/scripts/auto_release/main.py b/scripts/auto_release/main.py index a027b50e34e6..845d2e32b210 100644 --- a/scripts/auto_release/main.py +++ b/scripts/auto_release/main.py @@ -71,7 +71,8 @@ class CodegenTestPR: def __init__(self): self.issue_link = os.getenv("ISSUE_LINK", "") - self.pipeline_link = os.getenv("PIPELINE_LINK", "") + self.release_pipeline_link = os.getenv("PIPELINE_LINK", "") + self.triggered_pipeline_link = os.getenv("TRIGGERED_PIPELINE_LINK", "") self.bot_token = os.getenv("BOT_TOKEN") self.spec_readme = os.getenv("SPEC_README", "") self.spec_repo = os.getenv("SPEC_REPO", "") @@ -328,9 +329,14 @@ def create_pr_proc(self): pr_title = "[AutoRelease] {}(can only be merged by SDK owner)".format(self.new_branch) pr_head = "{}:{}".format(os.getenv("USR_NAME"), self.new_branch) pr_base = "main" - pr_body = "{} \n{} \n{}".format(self.issue_link, self.test_result, self.pipeline_link) + pr_body = "{} \n{} \n After PR merged, trigger [release pipeline]({}) to release".format( + self.issue_link, self.test_result, self.release_pipeline_link + ) if self.has_multi_packages: pr_body += f"\nBuildTargetingString\n {self.whole_package_name}\nSkip.CreateApiReview" + pr_body += "\n\n (Just to record: this PR was created by this [pipeline]({}))".format( + self.triggered_pipeline_link + ) res_create = api.pulls.create(pr_title, pr_head, pr_base, pr_body) # Add issue link on PR From b6ee531099be57db85d221d85d9cc068e313b6c8 Mon Sep 17 00:00:00 2001 From: Yuchao Yan Date: Thu, 5 Feb 2026 15:30:59 +0800 Subject: [PATCH 50/84] bump typespec-python 0.60.0 (#45030) --- eng/emitter-package-lock.json | 42 +++++++++++++++++++++++------------ eng/emitter-package.json | 4 ++-- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index 7130d115e197..003f3c40dd28 100644 --- a/eng/emitter-package-lock.json +++ b/eng/emitter-package-lock.json @@ -6,7 +6,7 @@ "": { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.3" + "@azure-tools/typespec-python": "0.60.0" }, "devDependencies": { "@azure-tools/openai-typespec": "1.8.0", @@ -14,7 +14,7 @@ "@azure-tools/typespec-azure-core": "~0.64.0", "@azure-tools/typespec-azure-resource-manager": "~0.64.1", "@azure-tools/typespec-azure-rulesets": "~0.64.0", - "@azure-tools/typespec-client-generator-core": "~0.64.5", + "@azure-tools/typespec-client-generator-core": "~0.64.6", "@azure-tools/typespec-liftr-base": "0.11.0", "@typespec/compiler": "^1.8.0", "@typespec/events": "~0.78.0", @@ -43,6 +43,7 @@ "resolved": "https://registry.npmjs.org/@azure-tools/typespec-autorest/-/typespec-autorest-0.64.1.tgz", "integrity": "sha512-WzSRiX0XS7hCL+uiivLBYMbirEUenxNzPT4giF0J+r54CVNXq/u8PLnA/06F5EHkXPa92swF4BxB1vFWB2TKow==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -68,6 +69,7 @@ "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-core/-/typespec-azure-core-0.64.0.tgz", "integrity": "sha512-BXiHc5oayhMsG1dHFU1aFK/ZQX2Gl0dKB0FAFceapaFV9093J2obbsdhIDR3Tl0qei9g3Ha+iWKZ4KgnLdhv4w==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -82,6 +84,7 @@ "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-resource-manager/-/typespec-azure-resource-manager-0.64.1.tgz", "integrity": "sha512-qQV/+ZVF1h8PsTNKhmKYyb+vSCgnLA8SoGeEE1oOrevGrrp9VgtOMAZ2xIxj6DpU90QU/8t2+r5P/gcQUV1iqw==", "license": "MIT", + "peer": true, "dependencies": { "change-case": "~5.4.4", "pluralize": "^8.0.0" @@ -103,6 +106,7 @@ "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-rulesets/-/typespec-azure-rulesets-0.64.0.tgz", "integrity": "sha512-CvK5iolfsm8oAUZ5wegGVYp4Vvw2rwQa+rcUVoJkwi9c6QwEr+qT6/S4hIntuzEPLxybJSb/ZIWU9Qx3cDrzXg==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -114,10 +118,11 @@ } }, "node_modules/@azure-tools/typespec-client-generator-core": { - "version": "0.64.5", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.64.5.tgz", - "integrity": "sha512-RaATxsnc9ztdMPoIZ2SuyH97dIGY0BWGKcJBf0hBY+8J3de9o+QH796NA9OsiW+8J9ycCEooDbh/rkAspvA4xA==", + "version": "0.64.6", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.64.6.tgz", + "integrity": "sha512-S0OH5UmIltjPdj/rdMD8RBpAQWpFP+0jjXLZSi2ARCZkhzi6++E1fEsqLLNDW7oP0CDq3RYQgpuWyCLZVtVf/A==", "license": "MIT", + "peer": true, "dependencies": { "change-case": "~5.4.4", "pluralize": "^8.0.0", @@ -146,13 +151,13 @@ "dev": true }, "node_modules/@azure-tools/typespec-python": { - "version": "0.59.3", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.59.3.tgz", - "integrity": "sha512-aXnMmKaPz4nhxYLCPyK+DY9GpbcpXn5f56INfcnLpjw0/ukK/NkoVtENBuj6pJ8YO49zCoRXhU1cdwjwP0TMVw==", + "version": "0.60.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.60.0.tgz", + "integrity": "sha512-6675eTZ8vyRvimaH3NgAoYfpOm+ylnZBnB3L1UeNE+4N+GzyDayLmTZBYC9rWb+lH8jNUbh3BBK92Fh3qlf0kA==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "@typespec/http-client-python": "~0.26.3", + "@typespec/http-client-python": "~0.27.0", "fs-extra": "~11.2.0", "js-yaml": "~4.1.0", "semver": "~7.6.2", @@ -166,7 +171,7 @@ "@azure-tools/typespec-azure-core": ">=0.64.0 <1.0.0", "@azure-tools/typespec-azure-resource-manager": ">=0.64.1 <1.0.0", "@azure-tools/typespec-azure-rulesets": ">=0.64.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.64.5 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.64.6 <1.0.0", "@typespec/compiler": "^1.8.0", "@typespec/events": ">=0.78.0 <1.0.0", "@typespec/http": "^1.8.0", @@ -1009,6 +1014,7 @@ "resolved": "https://registry.npmjs.org/@typespec/compiler/-/compiler-1.8.0.tgz", "integrity": "sha512-FeLb7Q0z6Bh5dDpqtnU2RlWiIWWWF7rujx2xGMta5dcTuIOZ4jbdyz1hVdxk4iM4qadvaSV4ey/qrSuffNoh3w==", "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "~7.27.1", "@inquirer/prompts": "^8.0.1", @@ -1053,6 +1059,7 @@ "resolved": "https://registry.npmjs.org/@typespec/events/-/events-0.78.0.tgz", "integrity": "sha512-gSI4rAexxfYyZX0ZqYNRWQyuMb1UeakjAjOeh/2ntmxWCdYc+wSbJjxrxIArsZC+LwzTxq5WpdtD7+7OWzG4yw==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1065,6 +1072,7 @@ "resolved": "https://registry.npmjs.org/@typespec/http/-/http-1.8.0.tgz", "integrity": "sha512-ZKa4RISabwL8cUAmE3BkoNmtCYRjerO0+1Ba6XdDJKG+vJC5EGM2hkDf+ZmYsYZgrX0cvbhPXUKKh28zBV60hw==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1079,9 +1087,9 @@ } }, "node_modules/@typespec/http-client-python": { - "version": "0.26.3", - "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.26.3.tgz", - "integrity": "sha512-LKBi+giSTDbIc1UoAr1+8zGomhes9z68GyIGjxpuN+BxLbdFAUJurDFyDILSJw9rcS8WgYXnVXhHxmP33mqjvw==", + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@typespec/http-client-python/-/http-client-python-0.27.0.tgz", + "integrity": "sha512-B46cG+55BQrZDO/+TEU4qOb1vzgLYV3hVCqDdGps9Q7PvJcEzyW9mTfVPcAzUyWimOQ3OB50pcr0yrcK+t3u0A==", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -1099,7 +1107,7 @@ "@azure-tools/typespec-azure-core": ">=0.64.0 <1.0.0", "@azure-tools/typespec-azure-resource-manager": ">=0.64.1 <1.0.0", "@azure-tools/typespec-azure-rulesets": ">=0.64.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.64.5 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.64.6 <1.0.0", "@typespec/compiler": "^1.8.0", "@typespec/events": ">=0.78.0 <1.0.0", "@typespec/http": "^1.8.0", @@ -1116,6 +1124,7 @@ "resolved": "https://registry.npmjs.org/@typespec/openapi/-/openapi-1.8.0.tgz", "integrity": "sha512-v+RIJpx7vALBSGQmnUWemvXjnrk50HAVqJeg0RbaF3VUnh66Z4itsoNJJmIIc+HmBJng8Ie0V7xv3l02ek6HWA==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1129,6 +1138,7 @@ "resolved": "https://registry.npmjs.org/@typespec/rest/-/rest-0.78.0.tgz", "integrity": "sha512-1clnDw1JbBvjLcfFvEvHdIrnsQuQI5/Cl6mRIrzWWX0pKJ+R89rCdZD1KpidEXw4B4qscD48LsssyrEIFLtuPg==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1142,6 +1152,7 @@ "resolved": "https://registry.npmjs.org/@typespec/sse/-/sse-0.78.0.tgz", "integrity": "sha512-jPARl+e1e/nsDW/1uVsGTzvKmjqezVMyUa13igXxk5nV2ScMdFpH1HhBwTmAhUeaZgY3J81dFHNUnIY67HCrmw==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1157,6 +1168,7 @@ "resolved": "https://registry.npmjs.org/@typespec/streams/-/streams-0.78.0.tgz", "integrity": "sha512-wzh5bVdzh+K+pFQFs/EZkVsTH5TQGi12XwhjxJS0UKRwaW2UwSZeY1HqX07oMMPdYESTbjgMrXcxtn89AlzjvQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1169,6 +1181,7 @@ "resolved": "https://registry.npmjs.org/@typespec/versioning/-/versioning-0.78.0.tgz", "integrity": "sha512-I14X6+IMd0wFMNI8oMFSeFBi2nD4idub+geSO34vuCs4rwuEj3FNzy+rkNkDDvf0+gIUGxeyg7s+YDUcNyiqOA==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -1181,6 +1194,7 @@ "resolved": "https://registry.npmjs.org/@typespec/xml/-/xml-0.78.0.tgz", "integrity": "sha512-KSDhJX6A/Onsu9FKVZtR/xSy5va3k0y9/U4eiZUn91V/LQyMZNwmResPDHEVYk6JqaIH8bbd6ANWPu3nMd7mmw==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, diff --git a/eng/emitter-package.json b/eng/emitter-package.json index de4ffaf9f7c6..bd6673c3bfe8 100644 --- a/eng/emitter-package.json +++ b/eng/emitter-package.json @@ -1,7 +1,7 @@ { "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-python": "0.59.3" + "@azure-tools/typespec-python": "0.60.0" }, "devDependencies": { "@typespec/compiler": "^1.8.0", @@ -18,7 +18,7 @@ "@azure-tools/typespec-azure-core": "~0.64.0", "@azure-tools/typespec-azure-resource-manager": "~0.64.1", "@azure-tools/typespec-azure-rulesets": "~0.64.0", - "@azure-tools/typespec-client-generator-core": "~0.64.5", + "@azure-tools/typespec-client-generator-core": "~0.64.6", "@azure-tools/typespec-liftr-base": "0.11.0" } } \ No newline at end of file From 43ab8c16598b60fa6e348e7643ac5247c797f267 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:26:05 -0800 Subject: [PATCH 51/84] [AutoRelease] t2-resource-privatelinks-2026-02-05-35881(can only be merged by SDK owner) (#45024) * code and test * update --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 --- .../CHANGELOG.md | 7 + .../azure-mgmt-resource-privatelinks/LICENSE | 21 + .../MANIFEST.in | 8 + .../README.md | 61 + .../_metadata.json | 11 + .../apiview-properties.json | 35 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../mgmt/resource/privatelinks/__init__.py | 32 + .../resource/privatelinks/_configuration.py | 75 + .../mgmt/resource/privatelinks/_patch.py | 21 + .../_resource_private_link_client.py | 136 ++ .../resource/privatelinks/_utils/__init__.py | 6 + .../privatelinks/_utils/serialization.py | 2041 +++++++++++++++++ .../mgmt/resource/privatelinks/_version.py | 9 + .../resource/privatelinks/aio/__init__.py | 29 + .../privatelinks/aio/_configuration.py | 75 + .../mgmt/resource/privatelinks/aio/_patch.py | 21 + .../aio/_resource_private_link_client.py | 140 ++ .../privatelinks/aio/operations/__init__.py | 27 + .../aio/operations/_operations.py | 705 ++++++ .../privatelinks/aio/operations/_patch.py | 21 + .../resource/privatelinks/models/__init__.py | 52 + .../privatelinks/models/_models_py3.py | 371 +++ .../resource/privatelinks/models/_patch.py | 21 + .../_resource_private_link_client_enums.py | 17 + .../privatelinks/operations/__init__.py | 27 + .../privatelinks/operations/_operations.py | 985 ++++++++ .../privatelinks/operations/_patch.py | 21 + .../azure/mgmt/resource/privatelinks/py.typed | 1 + .../dev_requirements.txt | 5 + .../delete_private_link_association.py | 42 + ...delete_resource_management_private_link.py | 42 + .../get_private_link_association.py | 43 + .../get_resource_management_private_link.py | 43 + .../list_private_link_association.py | 42 + ..._group_resource_management_private_link.py | 42 + ...iption_resource_management_private_link.py | 40 + .../put_private_link_association.py | 46 + .../put_resource_management_private_link.py | 44 + .../generated_tests/conftest.py | 37 + ...ink_private_link_association_operations.py | 67 + ...ivate_link_association_operations_async.py | 68 + ...urce_management_private_link_operations.py | 77 + ...anagement_private_link_operations_async.py | 78 + .../pyproject.toml | 87 + .../tests/conftest.py | 37 + ...ment_private_link_operations_async_test.py | 36 + ...management_private_link_operations_test.py | 35 + 50 files changed, 5890 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/README.md create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_resource_private_link_client.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_private_link_association.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_resource_management_private_link.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_private_link_association.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_resource_management_private_link.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_private_link_association.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_resource_group_resource_management_private_link.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_subscription_resource_management_private_link.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_private_link_association.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_resource_management_private_link.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-privatelinks/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/LICENSE b/sdk/resources/azure-mgmt-resource-privatelinks/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/MANIFEST.in b/sdk/resources/azure-mgmt-resource-privatelinks/MANIFEST.in new file mode 100644 index 000000000000..eee656d1e77b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/privatelinks/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/README.md b/sdk/resources/azure-mgmt-resource-privatelinks/README.md new file mode 100644 index 000000000000..f0d23c563dfb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Privatelinks Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-privatelinks +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ResourcePrivateLinkClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Privatelinks Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/_metadata.json b/sdk/resources/azure-mgmt-resource-privatelinks/_metadata.json new file mode 100644 index 000000000000..ea9b94515ff1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Authorization/privatelinks/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-privatelinks-2020-05 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Authorization/privatelinks/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/apiview-properties.json b/sdk/resources/azure-mgmt-resource-privatelinks/apiview-properties.json new file mode 100644 index 000000000000..c174205f0778 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/apiview-properties.json @@ -0,0 +1,35 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.privatelinks.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.privatelinks.models.ErrorResponse": null, + "azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation": null, + "azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationGetResult": null, + "azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject": null, + "azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationProperties": null, + "azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationPropertiesExpanded": null, + "azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink": null, + "azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkEndpointConnections": null, + "azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult": null, + "azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation": null, + "azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions": null, + "azure.mgmt.resource.privatelinks.operations.PrivateLinkAssociationOperations.put": null, + "azure.mgmt.resource.privatelinks.aio.operations.PrivateLinkAssociationOperations.put": null, + "azure.mgmt.resource.privatelinks.operations.PrivateLinkAssociationOperations.get": null, + "azure.mgmt.resource.privatelinks.aio.operations.PrivateLinkAssociationOperations.get": null, + "azure.mgmt.resource.privatelinks.operations.PrivateLinkAssociationOperations.delete": null, + "azure.mgmt.resource.privatelinks.aio.operations.PrivateLinkAssociationOperations.delete": null, + "azure.mgmt.resource.privatelinks.operations.PrivateLinkAssociationOperations.list": null, + "azure.mgmt.resource.privatelinks.aio.operations.PrivateLinkAssociationOperations.list": null, + "azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations.put": null, + "azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations.put": null, + "azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations.get": null, + "azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations.get": null, + "azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations.delete": null, + "azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations.delete": null, + "azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations.list": null, + "azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations.list": null, + "azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations.list_by_resource_group": null, + "azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations.list_by_resource_group": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/__init__.py new file mode 100644 index 000000000000..afa2f3e705c9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._resource_private_link_client import ResourcePrivateLinkClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ResourcePrivateLinkClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_configuration.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_configuration.py new file mode 100644 index 000000000000..d758ea0ab950 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ResourcePrivateLinkClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ResourcePrivateLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2020-05-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-privatelinks/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_patch.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_resource_private_link_client.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_resource_private_link_client.py new file mode 100644 index 000000000000..f3cb893a096d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_resource_private_link_client.py @@ -0,0 +1,136 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import ResourcePrivateLinkClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import PrivateLinkAssociationOperations, ResourceManagementPrivateLinkOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ResourcePrivateLinkClient: + """ResourcePrivateLink Client. + + :ivar private_link_association: PrivateLinkAssociationOperations operations + :vartype private_link_association: + azure.mgmt.resource.privatelinks.operations.PrivateLinkAssociationOperations + :ivar resource_management_private_link: ResourceManagementPrivateLinkOperations operations + :vartype resource_management_private_link: + azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ResourcePrivateLinkClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.private_link_association = PrivateLinkAssociationOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.resource_management_private_link = ResourceManagementPrivateLinkOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_version.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/__init__.py new file mode 100644 index 000000000000..bea0c4df00b3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._resource_private_link_client import ResourcePrivateLinkClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ResourcePrivateLinkClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_configuration.py new file mode 100644 index 000000000000..75ef585ca82d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ResourcePrivateLinkClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ResourcePrivateLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2020-05-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-privatelinks/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_patch.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py new file mode 100644 index 000000000000..b20c2abcc9dc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ResourcePrivateLinkClientConfiguration +from .operations import PrivateLinkAssociationOperations, ResourceManagementPrivateLinkOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ResourcePrivateLinkClient: + """ResourcePrivateLink Client. + + :ivar private_link_association: PrivateLinkAssociationOperations operations + :vartype private_link_association: + azure.mgmt.resource.privatelinks.aio.operations.PrivateLinkAssociationOperations + :ivar resource_management_private_link: ResourceManagementPrivateLinkOperations operations + :vartype resource_management_private_link: + azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ResourcePrivateLinkClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.private_link_association = PrivateLinkAssociationOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.resource_management_private_link = ResourceManagementPrivateLinkOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/__init__.py new file mode 100644 index 000000000000..39e87c00bee0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PrivateLinkAssociationOperations # type: ignore +from ._operations import ResourceManagementPrivateLinkOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PrivateLinkAssociationOperations", + "ResourceManagementPrivateLinkOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_operations.py new file mode 100644 index 000000000000..f68acf267882 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_operations.py @@ -0,0 +1,705 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_private_link_association_delete_request, + build_private_link_association_get_request, + build_private_link_association_list_request, + build_private_link_association_put_request, + build_resource_management_private_link_delete_request, + build_resource_management_private_link_get_request, + build_resource_management_private_link_list_by_resource_group_request, + build_resource_management_private_link_list_request, + build_resource_management_private_link_put_request, +) +from .._configuration import ResourcePrivateLinkClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class PrivateLinkAssociationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.privatelinks.aio.ResourcePrivateLinkClient`'s + :attr:`private_link_association` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def put( + self, + group_id: str, + pla_id: str, + parameters: _models.PrivateLinkAssociationObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateLinkAssociation: + """Create a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :param parameters: Parameters supplied to create the private link association. Required. + :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, + group_id: str, + pla_id: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateLinkAssociation: + """Create a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :param parameters: Parameters supplied to create the private link association. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, + group_id: str, + pla_id: str, + parameters: Union[_models.PrivateLinkAssociationObject, IO[bytes]], + **kwargs: Any + ) -> _models.PrivateLinkAssociation: + """Create a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :param parameters: Parameters supplied to create the private link association. Is either a + PrivateLinkAssociationObject type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject or + IO[bytes] + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PrivateLinkAssociationObject") + + _request = build_private_link_association_put_request( + group_id=group_id, + pla_id=pla_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, group_id: str, pla_id: str, **kwargs: Any) -> _models.PrivateLinkAssociation: + """Get a single private link association. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) + + _request = build_private_link_association_get_request( + group_id=group_id, + pla_id=pla_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, group_id: str, pla_id: str, **kwargs: Any) -> None: + """Delete a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_private_link_association_delete_request( + group_id=group_id, + pla_id=pla_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def list(self, group_id: str, **kwargs: Any) -> _models.PrivateLinkAssociationGetResult: + """Get a private link association for a management group scope. + + :param group_id: The management group ID. Required. + :type group_id: str + :return: PrivateLinkAssociationGetResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationGetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkAssociationGetResult] = kwargs.pop("cls", None) + + _request = build_private_link_association_list_request( + group_id=group_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkAssociationGetResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ResourceManagementPrivateLinkOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.privatelinks.aio.ResourcePrivateLinkClient`'s + :attr:`resource_management_private_link` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def put( + self, + resource_group_name: str, + rmpl_name: str, + parameters: _models.ResourceManagementPrivateLinkLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Create a resource management group private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :param parameters: The region to create the Resource Management private link. Required. + :type parameters: + ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, + resource_group_name: str, + rmpl_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Create a resource management group private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :param parameters: The region to create the Resource Management private link. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, + resource_group_name: str, + rmpl_name: str, + parameters: Union[_models.ResourceManagementPrivateLinkLocation, IO[bytes]], + **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Create a resource management group private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :param parameters: The region to create the Resource Management private link. Is either a + ResourceManagementPrivateLinkLocation type or a IO[bytes] type. Required. + :type parameters: + ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation or IO[bytes] + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ResourceManagementPrivateLinkLocation") + + _request = build_resource_management_private_link_put_request( + resource_group_name=resource_group_name, + rmpl_name=rmpl_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get( + self, resource_group_name: str, rmpl_name: str, **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Get a resource management private link(resource-level). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_get_request( + resource_group_name=resource_group_name, + rmpl_name=rmpl_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, resource_group_name: str, rmpl_name: str, **kwargs: Any) -> None: + """Delete a resource management private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_delete_request( + resource_group_name=resource_group_name, + rmpl_name=rmpl_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def list(self, **kwargs: Any) -> _models.ResourceManagementPrivateLinkListResult: + """Get all the resource management private links in a subscription. + + :return: ResourceManagementPrivateLinkListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> _models.ResourceManagementPrivateLinkListResult: + """Get all the resource management private links in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: ResourceManagementPrivateLinkListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/__init__.py new file mode 100644 index 000000000000..f1a9ad64c7a5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/__init__.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ErrorAdditionalInfo, + ErrorResponse, + PrivateLinkAssociation, + PrivateLinkAssociationGetResult, + PrivateLinkAssociationObject, + PrivateLinkAssociationProperties, + PrivateLinkAssociationPropertiesExpanded, + ResourceManagementPrivateLink, + ResourceManagementPrivateLinkEndpointConnections, + ResourceManagementPrivateLinkListResult, + ResourceManagementPrivateLinkLocation, +) + +from ._resource_private_link_client_enums import ( # type: ignore + PublicNetworkAccessOptions, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ErrorAdditionalInfo", + "ErrorResponse", + "PrivateLinkAssociation", + "PrivateLinkAssociationGetResult", + "PrivateLinkAssociationObject", + "PrivateLinkAssociationProperties", + "PrivateLinkAssociationPropertiesExpanded", + "ResourceManagementPrivateLink", + "ResourceManagementPrivateLinkEndpointConnections", + "ResourceManagementPrivateLinkListResult", + "ResourceManagementPrivateLinkLocation", + "PublicNetworkAccessOptions", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_models_py3.py new file mode 100644 index 000000000000..8a37e0dd1261 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_models_py3.py @@ -0,0 +1,371 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.privatelinks.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.privatelinks.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorResponse"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class PrivateLinkAssociation(_serialization.Model): + """PrivateLinkAssociation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar properties: The private link association properties. + :vartype properties: + ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationPropertiesExpanded + :ivar id: The plaResourceID. + :vartype id: str + :ivar type: The operation type. + :vartype type: str + :ivar name: The pla name. + :vartype name: str + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + } + + _attribute_map = { + "properties": {"key": "properties", "type": "PrivateLinkAssociationPropertiesExpanded"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + } + + def __init__( + self, *, properties: Optional["_models.PrivateLinkAssociationPropertiesExpanded"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: The private link association properties. + :paramtype properties: + ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationPropertiesExpanded + """ + super().__init__(**kwargs) + self.properties = properties + self.id: Optional[str] = None + self.type: Optional[str] = None + self.name: Optional[str] = None + + +class PrivateLinkAssociationGetResult(_serialization.Model): + """Result of the request to get PLA for a MG scope. + + :ivar value: private link association information. + :vartype value: list[~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PrivateLinkAssociation]"}, + } + + def __init__(self, *, value: Optional[list["_models.PrivateLinkAssociation"]] = None, **kwargs: Any) -> None: + """ + :keyword value: private link association information. + :paramtype value: list[~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation] + """ + super().__init__(**kwargs) + self.value = value + + +class PrivateLinkAssociationObject(_serialization.Model): + """PrivateLinkAssociationObject. + + :ivar properties: The properties of the PrivateLinkAssociation. + :vartype properties: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "PrivateLinkAssociationProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.PrivateLinkAssociationProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: The properties of the PrivateLinkAssociation. + :paramtype properties: + ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class PrivateLinkAssociationProperties(_serialization.Model): + """PrivateLinkAssociationProperties. + + :ivar private_link: The rmpl Resource ID. + :vartype private_link: str + :ivar public_network_access: Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or + ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions + """ + + _attribute_map = { + "private_link": {"key": "privateLink", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + } + + def __init__( + self, + *, + private_link: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccessOptions"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword private_link: The rmpl Resource ID. + :paramtype private_link: str + :keyword public_network_access: Known values are: "Enabled" and "Disabled". + :paramtype public_network_access: str or + ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions + """ + super().__init__(**kwargs) + self.private_link = private_link + self.public_network_access = public_network_access + + +class PrivateLinkAssociationPropertiesExpanded(_serialization.Model): + """Private Link Association Properties. + + :ivar private_link: The rmpl Resource ID. + :vartype private_link: str + :ivar public_network_access: Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or + ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions + :ivar tenant_id: The TenantID. + :vartype tenant_id: str + :ivar scope: The scope of the private link association. + :vartype scope: str + """ + + _attribute_map = { + "private_link": {"key": "privateLink", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "tenant_id": {"key": "tenantID", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + } + + def __init__( + self, + *, + private_link: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccessOptions"]] = None, + tenant_id: Optional[str] = None, + scope: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword private_link: The rmpl Resource ID. + :paramtype private_link: str + :keyword public_network_access: Known values are: "Enabled" and "Disabled". + :paramtype public_network_access: str or + ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions + :keyword tenant_id: The TenantID. + :paramtype tenant_id: str + :keyword scope: The scope of the private link association. + :paramtype scope: str + """ + super().__init__(**kwargs) + self.private_link = private_link + self.public_network_access = public_network_access + self.tenant_id = tenant_id + self.scope = scope + + +class ResourceManagementPrivateLink(_serialization.Model): + """ResourceManagementPrivateLink. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar properties: + :vartype properties: + ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkEndpointConnections + :ivar id: The rmplResourceID. + :vartype id: str + :ivar name: The rmpl Name. + :vartype name: str + :ivar type: The operation type. + :vartype type: str + :ivar location: the region of the rmpl. + :vartype location: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "properties": {"key": "properties", "type": "ResourceManagementPrivateLinkEndpointConnections"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + } + + def __init__( + self, + *, + properties: Optional["_models.ResourceManagementPrivateLinkEndpointConnections"] = None, + location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword properties: + :paramtype properties: + ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkEndpointConnections + :keyword location: the region of the rmpl. + :paramtype location: str + """ + super().__init__(**kwargs) + self.properties = properties + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.location = location + + +class ResourceManagementPrivateLinkEndpointConnections(_serialization.Model): # pylint: disable=name-too-long + """ResourceManagementPrivateLinkEndpointConnections. + + :ivar private_endpoint_connections: The private endpoint connections. + :vartype private_endpoint_connections: list[str] + """ + + _attribute_map = { + "private_endpoint_connections": {"key": "privateEndpointConnections", "type": "[str]"}, + } + + def __init__(self, *, private_endpoint_connections: Optional[list[str]] = None, **kwargs: Any) -> None: + """ + :keyword private_endpoint_connections: The private endpoint connections. + :paramtype private_endpoint_connections: list[str] + """ + super().__init__(**kwargs) + self.private_endpoint_connections = private_endpoint_connections + + +class ResourceManagementPrivateLinkListResult(_serialization.Model): + """ResourceManagementPrivateLinkListResult. + + :ivar value: An array of resource management private links. + :vartype value: list[~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ResourceManagementPrivateLink]"}, + } + + def __init__(self, *, value: Optional[list["_models.ResourceManagementPrivateLink"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of resource management private links. + :paramtype value: list[~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink] + """ + super().__init__(**kwargs) + self.value = value + + +class ResourceManagementPrivateLinkLocation(_serialization.Model): + """ResourceManagementPrivateLinkLocation. + + :ivar location: the region to create private link association. + :vartype location: str + """ + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + } + + def __init__(self, *, location: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword location: the region to create private link association. + :paramtype location: str + """ + super().__init__(**kwargs) + self.location = location diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_patch.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py new file mode 100644 index 000000000000..bf713fd07ea6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py @@ -0,0 +1,17 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class PublicNetworkAccessOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PublicNetworkAccessOptions.""" + + ENABLED = "Enabled" + DISABLED = "Disabled" diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/__init__.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/__init__.py new file mode 100644 index 000000000000..39e87c00bee0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PrivateLinkAssociationOperations # type: ignore +from ._operations import ResourceManagementPrivateLinkOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PrivateLinkAssociationOperations", + "ResourceManagementPrivateLinkOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_operations.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_operations.py new file mode 100644 index 000000000000..d75648a21d51 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_operations.py @@ -0,0 +1,985 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import ResourcePrivateLinkClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_private_link_association_put_request( # pylint: disable=name-too-long + group_id: str, pla_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations/{plaId}", + ) + path_format_arguments = { + "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), + "plaId": _SERIALIZER.url("pla_id", pla_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_private_link_association_get_request( # pylint: disable=name-too-long + group_id: str, pla_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations/{plaId}", + ) + path_format_arguments = { + "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), + "plaId": _SERIALIZER.url("pla_id", pla_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_private_link_association_delete_request( # pylint: disable=name-too-long + group_id: str, pla_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations/{plaId}", + ) + path_format_arguments = { + "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), + "plaId": _SERIALIZER.url("pla_id", pla_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_private_link_association_list_request( # pylint: disable=name-too-long + group_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations", + ) + path_format_arguments = { + "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_management_private_link_put_request( # pylint: disable=name-too-long + resource_group_name: str, rmpl_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks/{rmplName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "rmplName": _SERIALIZER.url("rmpl_name", rmpl_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_management_private_link_get_request( # pylint: disable=name-too-long + resource_group_name: str, rmpl_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks/{rmplName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "rmplName": _SERIALIZER.url("rmpl_name", rmpl_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_management_private_link_delete_request( # pylint: disable=name-too-long + resource_group_name: str, rmpl_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks/{rmplName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "rmplName": _SERIALIZER.url("rmpl_name", rmpl_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_management_private_link_list_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/resourceManagementPrivateLinks", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_management_private_link_list_by_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PrivateLinkAssociationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.privatelinks.ResourcePrivateLinkClient`'s + :attr:`private_link_association` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def put( + self, + group_id: str, + pla_id: str, + parameters: _models.PrivateLinkAssociationObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateLinkAssociation: + """Create a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :param parameters: Parameters supplied to create the private link association. Required. + :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, + group_id: str, + pla_id: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateLinkAssociation: + """Create a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :param parameters: Parameters supplied to create the private link association. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, + group_id: str, + pla_id: str, + parameters: Union[_models.PrivateLinkAssociationObject, IO[bytes]], + **kwargs: Any + ) -> _models.PrivateLinkAssociation: + """Create a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :param parameters: Parameters supplied to create the private link association. Is either a + PrivateLinkAssociationObject type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject or + IO[bytes] + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PrivateLinkAssociationObject") + + _request = build_private_link_association_put_request( + group_id=group_id, + pla_id=pla_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, group_id: str, pla_id: str, **kwargs: Any) -> _models.PrivateLinkAssociation: + """Get a single private link association. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :return: PrivateLinkAssociation or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) + + _request = build_private_link_association_get_request( + group_id=group_id, + pla_id=pla_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, group_id: str, pla_id: str, **kwargs: Any + ) -> None: + """Delete a PrivateLinkAssociation. + + :param group_id: The management group ID. Required. + :type group_id: str + :param pla_id: The ID of the PLA. Required. + :type pla_id: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_private_link_association_delete_request( + group_id=group_id, + pla_id=pla_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list(self, group_id: str, **kwargs: Any) -> _models.PrivateLinkAssociationGetResult: + """Get a private link association for a management group scope. + + :param group_id: The management group ID. Required. + :type group_id: str + :return: PrivateLinkAssociationGetResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationGetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkAssociationGetResult] = kwargs.pop("cls", None) + + _request = build_private_link_association_list_request( + group_id=group_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkAssociationGetResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ResourceManagementPrivateLinkOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.privatelinks.ResourcePrivateLinkClient`'s + :attr:`resource_management_private_link` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def put( + self, + resource_group_name: str, + rmpl_name: str, + parameters: _models.ResourceManagementPrivateLinkLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Create a resource management group private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :param parameters: The region to create the Resource Management private link. Required. + :type parameters: + ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, + resource_group_name: str, + rmpl_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Create a resource management group private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :param parameters: The region to create the Resource Management private link. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, + resource_group_name: str, + rmpl_name: str, + parameters: Union[_models.ResourceManagementPrivateLinkLocation, IO[bytes]], + **kwargs: Any + ) -> _models.ResourceManagementPrivateLink: + """Create a resource management group private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :param parameters: The region to create the Resource Management private link. Is either a + ResourceManagementPrivateLinkLocation type or a IO[bytes] type. Required. + :type parameters: + ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation or IO[bytes] + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ResourceManagementPrivateLinkLocation") + + _request = build_resource_management_private_link_put_request( + resource_group_name=resource_group_name, + rmpl_name=rmpl_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, resource_group_name: str, rmpl_name: str, **kwargs: Any) -> _models.ResourceManagementPrivateLink: + """Get a resource management private link(resource-level). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :return: ResourceManagementPrivateLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_get_request( + resource_group_name=resource_group_name, + rmpl_name=rmpl_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, rmpl_name: str, **kwargs: Any + ) -> None: + """Delete a resource management private link. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param rmpl_name: The name of the resource management private link. Required. + :type rmpl_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_delete_request( + resource_group_name=resource_group_name, + rmpl_name=rmpl_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> _models.ResourceManagementPrivateLinkListResult: + """Get all the resource management private links in a subscription. + + :return: ResourceManagementPrivateLinkListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> _models.ResourceManagementPrivateLinkListResult: + """Get all the resource management private links in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: ResourceManagementPrivateLinkListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) + + _request = build_resource_management_private_link_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_patch.py b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/py.typed b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/azure/mgmt/resource/privatelinks/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-privatelinks/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_private_link_association.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_private_link_association.py new file mode 100644 index 000000000000..ffbe06e3e43a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_private_link_association.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python delete_private_link_association.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.private_link_association.delete( + group_id="my-management-group", + pla_id="00000000-0000-0000-0000-000000000000", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/DeletePrivateLinkAssociation.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_resource_management_private_link.py new file mode 100644 index 000000000000..8c1d115a72bc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/delete_resource_management_private_link.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python delete_resource_management_private_link.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + client.resource_management_private_link.delete( + resource_group_name="my-resource-group", + rmpl_name="my-rmplName", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/DeleteResourceManagementPrivateLink.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_private_link_association.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_private_link_association.py new file mode 100644 index 000000000000..ddab382a18ed --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_private_link_association.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python get_private_link_association.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.private_link_association.get( + group_id="my-management-group", + pla_id="00000000-0000-0000-0000-000000000000", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/GetPrivateLinkAssociation.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_resource_management_private_link.py new file mode 100644 index 000000000000..f9862da49559 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/get_resource_management_private_link.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python get_resource_management_private_link.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.resource_management_private_link.get( + resource_group_name="my-resource-group", + rmpl_name="my-rmplName", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/GetResourceManagementPrivateLink.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_private_link_association.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_private_link_association.py new file mode 100644 index 000000000000..264a9d941bdf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_private_link_association.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python list_private_link_association.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.private_link_association.list( + group_id="my-management-group", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/ListPrivateLinkAssociation.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_resource_group_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_resource_group_resource_management_private_link.py new file mode 100644 index 000000000000..736c988f7e3c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_resource_group_resource_management_private_link.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python list_resource_group_resource_management_private_link.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.resource_management_private_link.list_by_resource_group( + resource_group_name="my-resource-group", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/ListResourceGroupResourceManagementPrivateLink.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_subscription_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_subscription_resource_management_private_link.py new file mode 100644 index 000000000000..4f46b13717eb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/list_subscription_resource_management_private_link.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python list_subscription_resource_management_private_link.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.resource_management_private_link.list() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/ListSubscriptionResourceManagementPrivateLink.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_private_link_association.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_private_link_association.py new file mode 100644 index 000000000000..e1fbf4e58a27 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_private_link_association.py @@ -0,0 +1,46 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python put_private_link_association.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.private_link_association.put( + group_id="my-management-group", + pla_id="00000000-0000-0000-0000-000000000000", + parameters={ + "properties": {"privateLink": "00000000-0000-0000-0000-000000000000", "publicNetworkAccess": "Enabled"} + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/PutPrivateLinkAssociation.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_resource_management_private_link.py new file mode 100644 index 000000000000..ed13dc1c3e93 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_samples/put_resource_management_private_link.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-privatelinks +# USAGE + python put_resource_management_private_link.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ResourcePrivateLinkClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.resource_management_private_link.put( + resource_group_name="my-resource-group", + rmpl_name="my-rmplName", + parameters={"location": "eastus"}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/privatelinks/stable/2020-05-01/examples/PutResourceManagementPrivateLink.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/conftest.py new file mode 100644 index 000000000000..42fb1e30a3c0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/conftest.py @@ -0,0 +1,37 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + resourceprivatelink_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + resourceprivatelink_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + resourceprivatelink_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + resourceprivatelink_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations.py new file mode 100644 index 000000000000..376f6e410d0d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestResourcePrivateLinkPrivateLinkAssociationOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ResourcePrivateLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_private_link_association_put(self, resource_group): + response = self.client.private_link_association.put( + group_id="str", + pla_id="str", + parameters={"properties": {"privateLink": "str", "publicNetworkAccess": "str"}}, + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_private_link_association_get(self, resource_group): + response = self.client.private_link_association.get( + group_id="str", + pla_id="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_private_link_association_delete(self, resource_group): + response = self.client.private_link_association.delete( + group_id="str", + pla_id="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_private_link_association_list(self, resource_group): + response = self.client.private_link_association.list( + group_id="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations_async.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations_async.py new file mode 100644 index 000000000000..6b65996b500a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_private_link_association_operations_async.py @@ -0,0 +1,68 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.privatelinks.aio import ResourcePrivateLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestResourcePrivateLinkPrivateLinkAssociationOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ResourcePrivateLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_private_link_association_put(self, resource_group): + response = await self.client.private_link_association.put( + group_id="str", + pla_id="str", + parameters={"properties": {"privateLink": "str", "publicNetworkAccess": "str"}}, + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_private_link_association_get(self, resource_group): + response = await self.client.private_link_association.get( + group_id="str", + pla_id="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_private_link_association_delete(self, resource_group): + response = await self.client.private_link_association.delete( + group_id="str", + pla_id="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_private_link_association_list(self, resource_group): + response = await self.client.private_link_association.list( + group_id="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations.py new file mode 100644 index 000000000000..f6fd1f5fdd00 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations.py @@ -0,0 +1,77 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestResourcePrivateLinkResourceManagementPrivateLinkOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ResourcePrivateLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_put(self, resource_group): + response = self.client.resource_management_private_link.put( + resource_group_name=resource_group.name, + rmpl_name="str", + parameters={"location": "str"}, + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_get(self, resource_group): + response = self.client.resource_management_private_link.get( + resource_group_name=resource_group.name, + rmpl_name="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_delete(self, resource_group): + response = self.client.resource_management_private_link.delete( + resource_group_name=resource_group.name, + rmpl_name="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_list(self, resource_group): + response = self.client.resource_management_private_link.list( + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_list_by_resource_group(self, resource_group): + response = self.client.resource_management_private_link.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py new file mode 100644 index 000000000000..b21f7a1c97a5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py @@ -0,0 +1,78 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.privatelinks.aio import ResourcePrivateLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestResourcePrivateLinkResourceManagementPrivateLinkOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ResourcePrivateLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_put(self, resource_group): + response = await self.client.resource_management_private_link.put( + resource_group_name=resource_group.name, + rmpl_name="str", + parameters={"location": "str"}, + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_get(self, resource_group): + response = await self.client.resource_management_private_link.get( + resource_group_name=resource_group.name, + rmpl_name="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_delete(self, resource_group): + response = await self.client.resource_management_private_link.delete( + resource_group_name=resource_group.name, + rmpl_name="str", + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_list(self, resource_group): + response = await self.client.resource_management_private_link.list( + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_list_by_resource_group(self, resource_group): + response = await self.client.resource_management_private_link.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2020-05-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/pyproject.toml b/sdk/resources/azure-mgmt-resource-privatelinks/pyproject.toml new file mode 100644 index 000000000000..9fc2816c48d5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-privatelinks" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Privatelinks Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.privatelinks._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-privatelinks" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Privatelinks Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "ResourcePrivateLinkClient" diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/tests/conftest.py b/sdk/resources/azure-mgmt-resource-privatelinks/tests/conftest.py new file mode 100644 index 000000000000..42fb1e30a3c0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/tests/conftest.py @@ -0,0 +1,37 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + resourceprivatelink_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + resourceprivatelink_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + resourceprivatelink_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + resourceprivatelink_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourceprivatelink_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py b/sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py new file mode 100644 index 000000000000..860687c905f7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.privatelinks.aio import ResourcePrivateLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestResourcePrivateLinkResourceManagementPrivateLinkOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ResourcePrivateLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_list(self, resource_group): + response = await self.client.resource_management_private_link.list() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_management_private_link_list_by_resource_group(self, resource_group): + response = await self.client.resource_management_private_link.list_by_resource_group( + resource_group_name=resource_group.name, + ) + + assert response diff --git a/sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_test.py b/sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_test.py new file mode 100644 index 000000000000..f265ec4a76fe --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-privatelinks/tests/test_resource_private_link_resource_management_private_link_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestResourcePrivateLinkResourceManagementPrivateLinkOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ResourcePrivateLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_list(self, resource_group): + response = self.client.resource_management_private_link.list() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_management_private_link_list_by_resource_group(self, resource_group): + response = self.client.resource_management_private_link.list_by_resource_group( + resource_group_name=resource_group.name, + ) + + assert response From 8dc8858feb173c68222cc8eb3a9e804eead9da9d Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:26:18 -0800 Subject: [PATCH 52/84] [AutoRelease] t2-resource-features-2026-02-05-71286(can only be merged by SDK owner) (#45023) * code and test * update --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 --- .../azure-mgmt-resource-features/CHANGELOG.md | 7 + .../azure-mgmt-resource-features/LICENSE | 21 + .../azure-mgmt-resource-features/MANIFEST.in | 8 + .../azure-mgmt-resource-features/README.md | 61 + .../_metadata.json | 11 + .../apiview-properties.json | 42 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../azure/mgmt/resource/features/__init__.py | 32 + .../mgmt/resource/features/_configuration.py | 75 + .../mgmt/resource/features/_feature_client.py | 133 ++ .../azure/mgmt/resource/features/_patch.py | 21 + .../mgmt/resource/features/_utils/__init__.py | 6 + .../resource/features/_utils/serialization.py | 2041 +++++++++++++++++ .../mgmt/resource/features/_utils/utils.py | 25 + .../azure/mgmt/resource/features/_version.py | 9 + .../mgmt/resource/features/aio/__init__.py | 29 + .../resource/features/aio/_configuration.py | 75 + .../resource/features/aio/_feature_client.py | 137 ++ .../mgmt/resource/features/aio/_patch.py | 21 + .../features/aio/operations/__init__.py | 28 + .../features/aio/operations/_operations.py | 934 ++++++++ .../features/aio/operations/_patch.py | 21 + .../mgmt/resource/features/models/__init__.py | 58 + .../features/models/_feature_client_enums.py | 32 + .../resource/features/models/_models_py3.py | 522 +++++ .../mgmt/resource/features/models/_patch.py | 21 + .../resource/features/operations/__init__.py | 28 + .../features/operations/_operations.py | 1235 ++++++++++ .../resource/features/operations/_patch.py | 21 + .../azure/mgmt/resource/features/py.typed | 1 + .../dev_requirements.txt | 5 + ...ubscription_feature_registration_delete.py | 42 + .../subscription_feature_registration_get.py | 43 + .../subscription_feature_registration_list.py | 43 + ...bscription_feature_registration_listall.py | 41 + .../subscription_feature_registration_put.py | 43 + .../generated_samples/get_feature.py | 43 + .../list_features_operations.py | 41 + .../list_provider_features.py | 43 + .../list_subscription_features.py | 41 + .../generated_samples/register_feature.py | 43 + .../generated_samples/unregister_feature.py | 43 + .../generated_tests/conftest.py | 35 + .../generated_tests/test_feature.py | 29 + .../generated_tests/test_feature_async.py | 30 + .../test_feature_features_operations.py | 76 + .../test_feature_features_operations_async.py | 77 + ...iption_feature_registrations_operations.py | 76 + ..._feature_registrations_operations_async.py | 77 + .../pyproject.toml | 87 + .../tests/conftest.py | 35 + .../tests/test_feature_async_test.py | 27 + ..._feature_features_operations_async_test.py | 27 + .../test_feature_features_operations_test.py | 26 + ...ure_registrations_operations_async_test.py | 27 + ...n_feature_registrations_operations_test.py | 26 + .../tests/test_feature_test.py | 26 + 59 files changed, 6810 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-features/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-features/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-features/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-features/README.md create mode 100644 sdk/resources/azure-mgmt-resource-features/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-features/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_feature_client.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/utils.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_feature_client.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_feature_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-features/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_delete.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_get.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_list.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_listall.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_put.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/get_feature.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/list_features_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/list_provider_features.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/list_subscription_features.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/register_feature.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_samples/unregister_feature.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_async.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-features/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/test_feature_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-features/tests/test_feature_test.py diff --git a/sdk/resources/azure-mgmt-resource-features/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-features/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-features/LICENSE b/sdk/resources/azure-mgmt-resource-features/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-features/MANIFEST.in b/sdk/resources/azure-mgmt-resource-features/MANIFEST.in new file mode 100644 index 000000000000..4a164843fe35 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/features/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-features/README.md b/sdk/resources/azure-mgmt-resource-features/README.md new file mode 100644 index 000000000000..5db62fce30da --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Features Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-features +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.features import FeatureClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = FeatureClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Features Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-features/_metadata.json b/sdk/resources/azure-mgmt-resource-features/_metadata.json new file mode 100644 index 000000000000..e63298f4fe89 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Features/features/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-features-2021-07 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Features/features/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-features/apiview-properties.json b/sdk/resources/azure-mgmt-resource-features/apiview-properties.json new file mode 100644 index 000000000000..de5ed21165f1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/apiview-properties.json @@ -0,0 +1,42 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.features.models.AuthorizationProfile": null, + "azure.mgmt.resource.features.models.ErrorDefinition": null, + "azure.mgmt.resource.features.models.ErrorResponse": null, + "azure.mgmt.resource.features.models.FeatureOperationsListResult": null, + "azure.mgmt.resource.features.models.FeatureProperties": null, + "azure.mgmt.resource.features.models.FeatureResult": null, + "azure.mgmt.resource.features.models.Operation": null, + "azure.mgmt.resource.features.models.OperationDisplay": null, + "azure.mgmt.resource.features.models.OperationListResult": null, + "azure.mgmt.resource.features.models.ProxyResource": null, + "azure.mgmt.resource.features.models.SubscriptionFeatureRegistration": null, + "azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationList": null, + "azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationProperties": null, + "azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationState": null, + "azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationApprovalType": null, + "azure.mgmt.resource.features.FeatureClient.list_operations": null, + "azure.mgmt.resource.features.aio.FeatureClient.list_operations": null, + "azure.mgmt.resource.features.operations.FeaturesOperations.list_all": null, + "azure.mgmt.resource.features.aio.operations.FeaturesOperations.list_all": null, + "azure.mgmt.resource.features.operations.FeaturesOperations.list": null, + "azure.mgmt.resource.features.aio.operations.FeaturesOperations.list": null, + "azure.mgmt.resource.features.operations.FeaturesOperations.get": null, + "azure.mgmt.resource.features.aio.operations.FeaturesOperations.get": null, + "azure.mgmt.resource.features.operations.FeaturesOperations.register": null, + "azure.mgmt.resource.features.aio.operations.FeaturesOperations.register": null, + "azure.mgmt.resource.features.operations.FeaturesOperations.unregister": null, + "azure.mgmt.resource.features.aio.operations.FeaturesOperations.unregister": null, + "azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations.get": null, + "azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations.get": null, + "azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations.create_or_update": null, + "azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations.create_or_update": null, + "azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations.delete": null, + "azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations.delete": null, + "azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations.list_by_subscription": null, + "azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations.list_by_subscription": null, + "azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations.list_all_by_subscription": null, + "azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations.list_all_by_subscription": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-features/azure/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/__init__.py new file mode 100644 index 000000000000..5f396af91593 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._feature_client import FeatureClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_configuration.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_configuration.py new file mode 100644 index 000000000000..13ba02299ea6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class FeatureClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2021-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-features/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_feature_client.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_feature_client.py new file mode 100644 index 000000000000..260c5ba10f0f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_feature_client.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import FeatureClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import FeaturesOperations, SubscriptionFeatureRegistrationsOperations, _FeatureClientOperationsMixin + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class FeatureClient(_FeatureClientOperationsMixin): + """Feature Client. + + :ivar features: FeaturesOperations operations + :vartype features: azure.mgmt.resource.features.operations.FeaturesOperations + :ivar subscription_feature_registrations: SubscriptionFeatureRegistrationsOperations operations + :vartype subscription_feature_registrations: + azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = FeatureClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscription_feature_registrations = SubscriptionFeatureRegistrationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_patch.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/utils.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/utils.py new file mode 100644 index 000000000000..39b612f39a9b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_utils/utils.py @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, TYPE_CHECKING, TypeVar + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_version.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/__init__.py new file mode 100644 index 000000000000..3b17bd37a7b6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._feature_client import FeatureClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_configuration.py new file mode 100644 index 000000000000..ec2e1e0ba87a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class FeatureClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2021-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-features/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_feature_client.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_feature_client.py new file mode 100644 index 000000000000..b83b86a3d6ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_feature_client.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import FeatureClientConfiguration +from .operations import FeaturesOperations, SubscriptionFeatureRegistrationsOperations, _FeatureClientOperationsMixin + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class FeatureClient(_FeatureClientOperationsMixin): + """Feature Client. + + :ivar features: FeaturesOperations operations + :vartype features: azure.mgmt.resource.features.aio.operations.FeaturesOperations + :ivar subscription_feature_registrations: SubscriptionFeatureRegistrationsOperations operations + :vartype subscription_feature_registrations: + azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = FeatureClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscription_feature_registrations = SubscriptionFeatureRegistrationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_patch.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/__init__.py new file mode 100644 index 000000000000..89e139cf2f4f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/__init__.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _FeatureClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import FeaturesOperations # type: ignore +from ._operations import SubscriptionFeatureRegistrationsOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeaturesOperations", + "SubscriptionFeatureRegistrationsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_operations.py new file mode 100644 index 000000000000..dd4bd59216cb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_operations.py @@ -0,0 +1,934 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import ClientMixinABC +from ...operations._operations import ( + build_feature_list_operations_request, + build_features_get_request, + build_features_list_all_request, + build_features_list_request, + build_features_register_request, + build_features_unregister_request, + build_subscription_feature_registrations_create_or_update_request, + build_subscription_feature_registrations_delete_request, + build_subscription_feature_registrations_get_request, + build_subscription_feature_registrations_list_all_by_subscription_request, + build_subscription_feature_registrations_list_by_subscription_request, +) +from .._configuration import FeatureClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class _FeatureClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], FeatureClientConfiguration] +): + + @distributed_trace + def list_operations(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_feature_list_operations_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.aio.FeatureClient`'s + :attr:`features` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all(self, **kwargs: Any) -> AsyncItemPaged["_models.FeatureResult"]: + """Gets all the preview features that are available through AFEC for the subscription. + + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_features_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list(self, resource_provider_namespace: str, **kwargs: Any) -> AsyncItemPaged["_models.FeatureResult"]: + """Gets all the preview features in a provider namespace that are available through AFEC for the + subscription. + + :param resource_provider_namespace: The namespace of the resource provider for getting + features. Required. + :type resource_provider_namespace: str + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_features_list_request( + resource_provider_namespace=resource_provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Gets the preview feature with the specified name. + + :param resource_provider_namespace: The resource provider namespace for the feature. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to get. Required. + :type feature_name: str + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + _request = build_features_get_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def register( + self, resource_provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.FeatureResult: + """Registers the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to register. Required. + :type feature_name: str + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + _request = build_features_register_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def unregister( + self, resource_provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.FeatureResult: + """Unregisters the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to unregister. Required. + :type feature_name: str + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + _request = build_features_unregister_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SubscriptionFeatureRegistrationsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.aio.FeatureClient`'s + :attr:`subscription_feature_registrations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Returns a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + _request = build_subscription_feature_registrations_get_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[_models.SubscriptionFeatureRegistration] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[ + Union[_models.SubscriptionFeatureRegistration, IO[bytes]] + ] = None, + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Is either a SubscriptionFeatureRegistration type or a IO[bytes] type. Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration or IO[bytes] + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if subscription_feature_registration_type else None + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if subscription_feature_registration_type else None + _json = None + _content = None + if isinstance(subscription_feature_registration_type, (IOBase, bytes)): + _content = subscription_feature_registration_type + else: + if subscription_feature_registration_type is not None: + _json = self._serialize.body(subscription_feature_registration_type, "SubscriptionFeatureRegistration") + else: + _json = None + + _request = build_subscription_feature_registrations_create_or_update_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, provider_namespace: str, feature_name: str, **kwargs: Any) -> None: + """Deletes a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subscription_feature_registrations_delete_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_subscription( + self, provider_namespace: str, **kwargs: Any + ) -> AsyncItemPaged["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription and provider namespace. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscription_feature_registrations_list_by_subscription_request( + provider_namespace=provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_all_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription. + + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscription_feature_registrations_list_all_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/__init__.py new file mode 100644 index 000000000000..2c526158845f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/__init__.py @@ -0,0 +1,58 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AuthorizationProfile, + ErrorDefinition, + ErrorResponse, + FeatureOperationsListResult, + FeatureProperties, + FeatureResult, + Operation, + OperationDisplay, + OperationListResult, + ProxyResource, + SubscriptionFeatureRegistration, + SubscriptionFeatureRegistrationList, + SubscriptionFeatureRegistrationProperties, +) + +from ._feature_client_enums import ( # type: ignore + SubscriptionFeatureRegistrationApprovalType, + SubscriptionFeatureRegistrationState, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AuthorizationProfile", + "ErrorDefinition", + "ErrorResponse", + "FeatureOperationsListResult", + "FeatureProperties", + "FeatureResult", + "Operation", + "OperationDisplay", + "OperationListResult", + "ProxyResource", + "SubscriptionFeatureRegistration", + "SubscriptionFeatureRegistrationList", + "SubscriptionFeatureRegistrationProperties", + "SubscriptionFeatureRegistrationApprovalType", + "SubscriptionFeatureRegistrationState", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_feature_client_enums.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_feature_client_enums.py new file mode 100644 index 000000000000..4243d86e0f58 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_feature_client_enums.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class SubscriptionFeatureRegistrationApprovalType( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """The feature approval type.""" + + NOT_SPECIFIED = "NotSpecified" + APPROVAL_REQUIRED = "ApprovalRequired" + AUTO_APPROVAL = "AutoApproval" + + +class SubscriptionFeatureRegistrationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state.""" + + NOT_SPECIFIED = "NotSpecified" + NOT_REGISTERED = "NotRegistered" + PENDING = "Pending" + REGISTERING = "Registering" + REGISTERED = "Registered" + UNREGISTERING = "Unregistering" + UNREGISTERED = "Unregistered" diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_models_py3.py new file mode 100644 index 000000000000..a7afa258a18f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_models_py3.py @@ -0,0 +1,522 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models + + +class AuthorizationProfile(_serialization.Model): + """Authorization Profile. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar requested_time: The requested time. + :vartype requested_time: ~datetime.datetime + :ivar requester: The requester. + :vartype requester: str + :ivar requester_object_id: The requester object id. + :vartype requester_object_id: str + :ivar approved_time: The approved time. + :vartype approved_time: ~datetime.datetime + :ivar approver: The approver. + :vartype approver: str + """ + + _validation = { + "requested_time": {"readonly": True}, + "requester": {"readonly": True}, + "requester_object_id": {"readonly": True}, + "approved_time": {"readonly": True}, + "approver": {"readonly": True}, + } + + _attribute_map = { + "requested_time": {"key": "requestedTime", "type": "iso-8601"}, + "requester": {"key": "requester", "type": "str"}, + "requester_object_id": {"key": "requesterObjectId", "type": "str"}, + "approved_time": {"key": "approvedTime", "type": "iso-8601"}, + "approver": {"key": "approver", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.requested_time: Optional[datetime.datetime] = None + self.requester: Optional[str] = None + self.requester_object_id: Optional[str] = None + self.approved_time: Optional[datetime.datetime] = None + self.approver: Optional[str] = None + + +class ErrorDefinition(_serialization.Model): + """Error definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: Service specific error code which serves as the substatus for the HTTP error code. + :vartype code: str + :ivar message: Description of the error. + :vartype message: str + :ivar details: Internal error details. + :vartype details: list[~azure.mgmt.resource.features.models.ErrorDefinition] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDefinition]"}, + } + + def __init__(self, *, details: Optional[list["_models.ErrorDefinition"]] = None, **kwargs: Any) -> None: + """ + :keyword details: Internal error details. + :paramtype details: list[~azure.mgmt.resource.features.models.ErrorDefinition] + """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.details = details + + +class ErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. + + :ivar error: The error details. + :vartype error: ~azure.mgmt.resource.features.models.ErrorDefinition + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDefinition"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error details. + :paramtype error: ~azure.mgmt.resource.features.models.ErrorDefinition + """ + super().__init__(**kwargs) + self.error = error + + +class FeatureOperationsListResult(_serialization.Model): + """List of previewed features. + + :ivar value: The array of features. + :vartype value: list[~azure.mgmt.resource.features.models.FeatureResult] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[FeatureResult]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[list["_models.FeatureResult"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The array of features. + :paramtype value: list[~azure.mgmt.resource.features.models.FeatureResult] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class FeatureProperties(_serialization.Model): + """Information about feature. + + :ivar state: The registration state of the feature for the subscription. + :vartype state: str + """ + + _attribute_map = { + "state": {"key": "state", "type": "str"}, + } + + def __init__(self, *, state: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword state: The registration state of the feature for the subscription. + :paramtype state: str + """ + super().__init__(**kwargs) + self.state = state + + +class FeatureResult(_serialization.Model): + """Previewed feature information. + + :ivar name: The name of the feature. + :vartype name: str + :ivar properties: Properties of the previewed feature. + :vartype properties: ~azure.mgmt.resource.features.models.FeatureProperties + :ivar id: The resource ID of the feature. + :vartype id: str + :ivar type: The resource type of the feature. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "FeatureProperties"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + properties: Optional["_models.FeatureProperties"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + type: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the feature. + :paramtype name: str + :keyword properties: Properties of the previewed feature. + :paramtype properties: ~azure.mgmt.resource.features.models.FeatureProperties + :keyword id: The resource ID of the feature. + :paramtype id: str + :keyword type: The resource type of the feature. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + self.id = id + self.type = type + + +class Operation(_serialization.Model): + """Microsoft.Features operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.features.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.features.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Features. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Features. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Features operations. It contains a list of operations + and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Features operations. + :vartype value: list[~azure.mgmt.resource.features.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Features operations. + :paramtype value: list[~azure.mgmt.resource.features.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ProxyResource(_serialization.Model): + """An Azure proxy resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + + +class SubscriptionFeatureRegistration(ProxyResource): + """Subscription feature registration details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar properties: + :vartype properties: + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "SubscriptionFeatureRegistrationProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.SubscriptionFeatureRegistrationProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: + :paramtype properties: + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class SubscriptionFeatureRegistrationList(_serialization.Model): + """The list of subscription feature registrations. + + :ivar next_link: The link used to get the next page of subscription feature registrations list. + :vartype next_link: str + :ivar value: The list of subscription feature registrations. + :vartype value: list[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[SubscriptionFeatureRegistration]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[list["_models.SubscriptionFeatureRegistration"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of subscription feature registrations + list. + :paramtype next_link: str + :keyword value: The list of subscription feature registrations. + :paramtype value: list[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class SubscriptionFeatureRegistrationProperties(_serialization.Model): # pylint: disable=name-too-long + """SubscriptionFeatureRegistrationProperties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar tenant_id: The tenantId. + :vartype tenant_id: str + :ivar subscription_id: The subscriptionId. + :vartype subscription_id: str + :ivar feature_name: The featureName. + :vartype feature_name: str + :ivar display_name: The featureDisplayName. + :vartype display_name: str + :ivar provider_namespace: The providerNamespace. + :vartype provider_namespace: str + :ivar state: The state. Known values are: "NotSpecified", "NotRegistered", "Pending", + "Registering", "Registered", "Unregistering", and "Unregistered". + :vartype state: str or + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationState + :ivar authorization_profile: Authorization Profile. + :vartype authorization_profile: ~azure.mgmt.resource.features.models.AuthorizationProfile + :ivar metadata: Key-value pairs for meta data. + :vartype metadata: dict[str, str] + :ivar release_date: The feature release date. + :vartype release_date: ~datetime.datetime + :ivar registration_date: The feature registration date. + :vartype registration_date: ~datetime.datetime + :ivar documentation_link: The feature documentation link. + :vartype documentation_link: str + :ivar approval_type: The feature approval type. Known values are: "NotSpecified", + "ApprovalRequired", and "AutoApproval". + :vartype approval_type: str or + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationApprovalType + :ivar should_feature_display_in_portal: Indicates whether feature should be displayed in + Portal. + :vartype should_feature_display_in_portal: bool + :ivar description: The feature description. + :vartype description: str + """ + + _validation = { + "tenant_id": {"readonly": True}, + "subscription_id": {"readonly": True}, + "feature_name": {"readonly": True}, + "display_name": {"readonly": True}, + "provider_namespace": {"readonly": True}, + "release_date": {"readonly": True}, + "registration_date": {"readonly": True}, + "documentation_link": {"readonly": True, "max_length": 1000}, + "approval_type": {"readonly": True}, + "description": {"max_length": 1000}, + } + + _attribute_map = { + "tenant_id": {"key": "tenantId", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "feature_name": {"key": "featureName", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "provider_namespace": {"key": "providerNamespace", "type": "str"}, + "state": {"key": "state", "type": "str"}, + "authorization_profile": {"key": "authorizationProfile", "type": "AuthorizationProfile"}, + "metadata": {"key": "metadata", "type": "{str}"}, + "release_date": {"key": "releaseDate", "type": "iso-8601"}, + "registration_date": {"key": "registrationDate", "type": "iso-8601"}, + "documentation_link": {"key": "documentationLink", "type": "str"}, + "approval_type": {"key": "approvalType", "type": "str"}, + "should_feature_display_in_portal": {"key": "shouldFeatureDisplayInPortal", "type": "bool"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + state: Optional[Union[str, "_models.SubscriptionFeatureRegistrationState"]] = None, + authorization_profile: Optional["_models.AuthorizationProfile"] = None, + metadata: Optional[dict[str, str]] = None, + should_feature_display_in_portal: bool = False, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword state: The state. Known values are: "NotSpecified", "NotRegistered", "Pending", + "Registering", "Registered", "Unregistering", and "Unregistered". + :paramtype state: str or + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationState + :keyword authorization_profile: Authorization Profile. + :paramtype authorization_profile: ~azure.mgmt.resource.features.models.AuthorizationProfile + :keyword metadata: Key-value pairs for meta data. + :paramtype metadata: dict[str, str] + :keyword should_feature_display_in_portal: Indicates whether feature should be displayed in + Portal. + :paramtype should_feature_display_in_portal: bool + :keyword description: The feature description. + :paramtype description: str + """ + super().__init__(**kwargs) + self.tenant_id: Optional[str] = None + self.subscription_id: Optional[str] = None + self.feature_name: Optional[str] = None + self.display_name: Optional[str] = None + self.provider_namespace: Optional[str] = None + self.state = state + self.authorization_profile = authorization_profile + self.metadata = metadata + self.release_date: Optional[datetime.datetime] = None + self.registration_date: Optional[datetime.datetime] = None + self.documentation_link: Optional[str] = None + self.approval_type: Optional[Union[str, "_models.SubscriptionFeatureRegistrationApprovalType"]] = None + self.should_feature_display_in_portal = should_feature_display_in_portal + self.description = description diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_patch.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/__init__.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/__init__.py new file mode 100644 index 000000000000..89e139cf2f4f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/__init__.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _FeatureClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import FeaturesOperations # type: ignore +from ._operations import SubscriptionFeatureRegistrationsOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeaturesOperations", + "SubscriptionFeatureRegistrationsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_operations.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_operations.py new file mode 100644 index 000000000000..172637c64cad --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_operations.py @@ -0,0 +1,1235 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import FeatureClientConfiguration +from .._utils.serialization import Deserializer, Serializer +from .._utils.utils import ClientMixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_feature_list_operations_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Features/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_all_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_request(resource_provider_namespace: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features", + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_get_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}", + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_register_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register", + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_unregister_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister", + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_get_request( # pylint: disable=name-too-long + provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_create_or_update_request( # pylint: disable=name-too-long + provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_delete_request( # pylint: disable=name-too-long + provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_list_by_subscription_request( # pylint: disable=name-too-long + provider_namespace: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_list_all_by_subscription_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/subscriptionFeatureRegistrations" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class _FeatureClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], FeatureClientConfiguration] +): + + @distributed_trace + def list_operations(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_feature_list_operations_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.FeatureClient`'s + :attr:`features` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all(self, **kwargs: Any) -> ItemPaged["_models.FeatureResult"]: + """Gets all the preview features that are available through AFEC for the subscription. + + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_features_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list(self, resource_provider_namespace: str, **kwargs: Any) -> ItemPaged["_models.FeatureResult"]: + """Gets all the preview features in a provider namespace that are available through AFEC for the + subscription. + + :param resource_provider_namespace: The namespace of the resource provider for getting + features. Required. + :type resource_provider_namespace: str + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_features_list_request( + resource_provider_namespace=resource_provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Gets the preview feature with the specified name. + + :param resource_provider_namespace: The resource provider namespace for the feature. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to get. Required. + :type feature_name: str + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + _request = build_features_get_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def register(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Registers the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to register. Required. + :type feature_name: str + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + _request = build_features_register_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def unregister(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Unregisters the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to unregister. Required. + :type feature_name: str + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + _request = build_features_unregister_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SubscriptionFeatureRegistrationsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.FeatureClient`'s + :attr:`subscription_feature_registrations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.SubscriptionFeatureRegistration: + """Returns a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + _request = build_subscription_feature_registrations_get_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[_models.SubscriptionFeatureRegistration] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[ + Union[_models.SubscriptionFeatureRegistration, IO[bytes]] + ] = None, + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Is either a SubscriptionFeatureRegistration type or a IO[bytes] type. Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration or IO[bytes] + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if subscription_feature_registration_type else None + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if subscription_feature_registration_type else None + _json = None + _content = None + if isinstance(subscription_feature_registration_type, (IOBase, bytes)): + _content = subscription_feature_registration_type + else: + if subscription_feature_registration_type is not None: + _json = self._serialize.body(subscription_feature_registration_type, "SubscriptionFeatureRegistration") + else: + _json = None + + _request = build_subscription_feature_registrations_create_or_update_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, provider_namespace: str, feature_name: str, **kwargs: Any + ) -> None: + """Deletes a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subscription_feature_registrations_delete_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_subscription( + self, provider_namespace: str, **kwargs: Any + ) -> ItemPaged["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription and provider namespace. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscription_feature_registrations_list_by_subscription_request( + provider_namespace=provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_all_by_subscription(self, **kwargs: Any) -> ItemPaged["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription. + + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscription_feature_registrations_list_all_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_patch.py b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/py.typed b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/azure/mgmt/resource/features/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-features/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-features/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_delete.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_delete.py new file mode 100644 index 000000000000..aa64fda64274 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_delete.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python subscription_feature_registration_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + client.subscription_feature_registrations.delete( + provider_namespace="subscriptionFeatureRegistrationGroupTestRG", + feature_name="testFeature", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationDELETE.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_get.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_get.py new file mode 100644 index 000000000000..8d2104797498 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_get.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python subscription_feature_registration_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.subscription_feature_registrations.get( + provider_namespace="subscriptionFeatureRegistrationGroupTestRG", + feature_name="testFeature", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationGET.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_list.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_list.py new file mode 100644 index 000000000000..62be221b30b2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_list.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python subscription_feature_registration_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.subscription_feature_registrations.list_by_subscription( + provider_namespace="subscriptionFeatureRegistrationGroupTestRG", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationLIST.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_listall.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_listall.py new file mode 100644 index 000000000000..d37b068693b0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_listall.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python subscription_feature_registration_listall.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.subscription_feature_registrations.list_all_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationLISTALL.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_put.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_put.py new file mode 100644 index 000000000000..83752d980c62 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/feature_registration/subscription_feature_registration_put.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python subscription_feature_registration_put.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.subscription_feature_registrations.create_or_update( + provider_namespace="subscriptionFeatureRegistrationGroupTestRG", + feature_name="testFeature", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationPUT.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/get_feature.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/get_feature.py new file mode 100644 index 000000000000..f404f56f1190 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/get_feature.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python get_feature.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.features.get( + resource_provider_namespace="Resource Provider Namespace", + feature_name="feature", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/getFeature.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/list_features_operations.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/list_features_operations.py new file mode 100644 index 000000000000..59c9d94bb3bb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/list_features_operations.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python list_features_operations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.list_operations() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/listFeaturesOperations.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/list_provider_features.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/list_provider_features.py new file mode 100644 index 000000000000..694d923037b1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/list_provider_features.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python list_provider_features.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.features.list( + resource_provider_namespace="Resource Provider Namespace", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/listProviderFeatures.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/list_subscription_features.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/list_subscription_features.py new file mode 100644 index 000000000000..766b33dadfdc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/list_subscription_features.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python list_subscription_features.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.features.list_all() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/listSubscriptionFeatures.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/register_feature.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/register_feature.py new file mode 100644 index 000000000000..0d67bd641c74 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/register_feature.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python register_feature.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.features.register( + resource_provider_namespace="Resource Provider Namespace", + feature_name="feature", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/registerFeature.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_samples/unregister_feature.py b/sdk/resources/azure-mgmt-resource-features/generated_samples/unregister_feature.py new file mode 100644 index 000000000000..76d5cf0c4bf9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_samples/unregister_feature.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.features import FeatureClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-features +# USAGE + python unregister_feature.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = FeatureClient( + credential=DefaultAzureCredential(), + subscription_id="ff23096b-f5a2-46ea-bd62-59c3e93fef9a", + ) + + response = client.features.unregister( + resource_provider_namespace="Resource Provider Namespace", + feature_name="feature", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/features/stable/2021-07-01/examples/unregisterFeature.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/conftest.py new file mode 100644 index 000000000000..4a82c7f2c845 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + feature_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + feature_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + feature_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + feature_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature.py new file mode 100644 index 000000000000..3e8c2f19b93b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestFeature(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_operations(self, resource_group): + response = self.client.list_operations( + api_version="2021-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_async.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_async.py new file mode 100644 index 000000000000..b74a3e8e12ad --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features.aio import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestFeatureAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_operations(self, resource_group): + response = self.client.list_operations( + api_version="2021-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations.py new file mode 100644 index 000000000000..378bbf66d7aa --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestFeatureFeaturesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_features_list_all(self, resource_group): + response = self.client.features.list_all( + api_version="2021-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_features_list(self, resource_group): + response = self.client.features.list( + resource_provider_namespace="str", + api_version="2021-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_features_get(self, resource_group): + response = self.client.features.get( + resource_provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_features_register(self, resource_group): + response = self.client.features.register( + resource_provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_features_unregister(self, resource_group): + response = self.client.features.unregister( + resource_provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations_async.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations_async.py new file mode 100644 index 000000000000..df7789e0065b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_features_operations_async.py @@ -0,0 +1,77 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features.aio import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestFeatureFeaturesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_features_list_all(self, resource_group): + response = self.client.features.list_all( + api_version="2021-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_features_list(self, resource_group): + response = self.client.features.list( + resource_provider_namespace="str", + api_version="2021-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_features_get(self, resource_group): + response = await self.client.features.get( + resource_provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_features_register(self, resource_group): + response = await self.client.features.register( + resource_provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_features_unregister(self, resource_group): + response = await self.client.features.unregister( + resource_provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations.py new file mode 100644 index 000000000000..767f142ac401 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestFeatureSubscriptionFeatureRegistrationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscription_feature_registrations_get(self, resource_group): + response = self.client.subscription_feature_registrations.get( + provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscription_feature_registrations_create_or_update(self, resource_group): + response = self.client.subscription_feature_registrations.create_or_update( + provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscription_feature_registrations_delete(self, resource_group): + response = self.client.subscription_feature_registrations.delete( + provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscription_feature_registrations_list_by_subscription(self, resource_group): + response = self.client.subscription_feature_registrations.list_by_subscription( + provider_namespace="str", + api_version="2021-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscription_feature_registrations_list_all_by_subscription(self, resource_group): + response = self.client.subscription_feature_registrations.list_all_by_subscription( + api_version="2021-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations_async.py b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations_async.py new file mode 100644 index 000000000000..2f75a84cec6c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/generated_tests/test_feature_subscription_feature_registrations_operations_async.py @@ -0,0 +1,77 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features.aio import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestFeatureSubscriptionFeatureRegistrationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscription_feature_registrations_get(self, resource_group): + response = await self.client.subscription_feature_registrations.get( + provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscription_feature_registrations_create_or_update(self, resource_group): + response = await self.client.subscription_feature_registrations.create_or_update( + provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscription_feature_registrations_delete(self, resource_group): + response = await self.client.subscription_feature_registrations.delete( + provider_namespace="str", + feature_name="str", + api_version="2021-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscription_feature_registrations_list_by_subscription(self, resource_group): + response = self.client.subscription_feature_registrations.list_by_subscription( + provider_namespace="str", + api_version="2021-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscription_feature_registrations_list_all_by_subscription(self, resource_group): + response = self.client.subscription_feature_registrations.list_all_by_subscription( + api_version="2021-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-features/pyproject.toml b/sdk/resources/azure-mgmt-resource-features/pyproject.toml new file mode 100644 index 000000000000..bf589997336f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-features" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Features Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.features._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-features" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Features Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "FeatureClient" diff --git a/sdk/resources/azure-mgmt-resource-features/tests/conftest.py b/sdk/resources/azure-mgmt-resource-features/tests/conftest.py new file mode 100644 index 000000000000..4a82c7f2c845 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + feature_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + feature_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + feature_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + feature_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=feature_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-features/tests/test_feature_async_test.py b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_async_test.py new file mode 100644 index 000000000000..b63ae2c108ab --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features.aio import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestFeatureAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_operations(self, resource_group): + response = self.client.list_operations() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_async_test.py b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_async_test.py new file mode 100644 index 000000000000..b30e68833f4c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features.aio import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestFeatureFeaturesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_features_list_all(self, resource_group): + response = self.client.features.list_all() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_test.py b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_test.py new file mode 100644 index 000000000000..0a41756ef972 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_features_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestFeatureFeaturesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_features_list_all(self, resource_group): + response = self.client.features.list_all() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_async_test.py b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_async_test.py new file mode 100644 index 000000000000..310c4809aab0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features.aio import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestFeatureSubscriptionFeatureRegistrationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscription_feature_registrations_list_all_by_subscription(self, resource_group): + response = self.client.subscription_feature_registrations.list_all_by_subscription() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_test.py b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_test.py new file mode 100644 index 000000000000..ac3b36904a79 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_subscription_feature_registrations_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestFeatureSubscriptionFeatureRegistrationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscription_feature_registrations_list_all_by_subscription(self, resource_group): + response = self.client.subscription_feature_registrations.list_all_by_subscription() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-features/tests/test_feature_test.py b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_test.py new file mode 100644 index 000000000000..f65833b40ade --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-features/tests/test_feature_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.features import FeatureClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestFeature(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(FeatureClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_operations(self, resource_group): + response = self.client.list_operations() + result = [r for r in response] + assert result From 9dc2f5bb714ea0b516a9916c186a53cdda868512 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:26:25 -0800 Subject: [PATCH 53/84] [AutoRelease] t2-resource-links-2026-02-05-01849(can only be merged by SDK owner) (#45022) * code and test * update --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 --- .../azure-mgmt-resource-links/CHANGELOG.md | 7 + .../azure-mgmt-resource-links/LICENSE | 21 + .../azure-mgmt-resource-links/MANIFEST.in | 8 + .../azure-mgmt-resource-links/README.md | 61 + .../azure-mgmt-resource-links/_metadata.json | 11 + .../apiview-properties.json | 24 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../azure/mgmt/resource/links/__init__.py | 32 + .../mgmt/resource/links/_configuration.py | 75 + .../resource/links/_management_link_client.py | 130 ++ .../azure/mgmt/resource/links/_patch.py | 21 + .../mgmt/resource/links/_utils/__init__.py | 6 + .../resource/links/_utils/serialization.py | 2041 +++++++++++++++++ .../azure/mgmt/resource/links/_version.py | 9 + .../azure/mgmt/resource/links/aio/__init__.py | 29 + .../mgmt/resource/links/aio/_configuration.py | 75 + .../links/aio/_management_link_client.py | 134 ++ .../azure/mgmt/resource/links/aio/_patch.py | 21 + .../resource/links/aio/operations/__init__.py | 27 + .../links/aio/operations/_operations.py | 541 +++++ .../resource/links/aio/operations/_patch.py | 21 + .../mgmt/resource/links/models/__init__.py | 39 + .../mgmt/resource/links/models/_models_py3.py | 257 +++ .../mgmt/resource/links/models/_patch.py | 21 + .../resource/links/operations/__init__.py | 27 + .../resource/links/operations/_operations.py | 679 ++++++ .../mgmt/resource/links/operations/_patch.py | 21 + .../azure/mgmt/resource/links/py.typed | 1 + .../dev_requirements.txt | 5 + .../generated_tests/conftest.py | 35 + .../test_management_link_operations.py | 29 + .../test_management_link_operations_async.py | 30 + ...nagement_link_resource_links_operations.py | 79 + ...nt_link_resource_links_operations_async.py | 80 + .../azure-mgmt-resource-links/pyproject.toml | 87 + .../tests/conftest.py | 35 + ...t_management_link_operations_async_test.py | 27 + .../test_management_link_operations_test.py | 26 + ...nk_resource_links_operations_async_test.py | 27 + ...ent_link_resource_links_operations_test.py | 26 + 42 files changed, 4828 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-links/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-links/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-links/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-links/README.md create mode 100644 sdk/resources/azure-mgmt-resource-links/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-links/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_management_link_client.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_management_link_client.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-links/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-links/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-links/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-links/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-links/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-links/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-links/LICENSE b/sdk/resources/azure-mgmt-resource-links/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-links/MANIFEST.in b/sdk/resources/azure-mgmt-resource-links/MANIFEST.in new file mode 100644 index 000000000000..fc33afa79bd0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/links/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-links/README.md b/sdk/resources/azure-mgmt-resource-links/README.md new file mode 100644 index 000000000000..1054ec15b499 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Links Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-links +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.links import ManagementLinkClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ManagementLinkClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Links Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-links/_metadata.json b/sdk/resources/azure-mgmt-resource-links/_metadata.json new file mode 100644 index 000000000000..53f3ae224791 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Resources/links/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-links-2016-09 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Resources/links/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-links/apiview-properties.json b/sdk/resources/azure-mgmt-resource-links/apiview-properties.json new file mode 100644 index 000000000000..15f2deadf0b1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/apiview-properties.json @@ -0,0 +1,24 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.links.models.Operation": null, + "azure.mgmt.resource.links.models.OperationDisplay": null, + "azure.mgmt.resource.links.models.OperationListResult": null, + "azure.mgmt.resource.links.models.ResourceLink": null, + "azure.mgmt.resource.links.models.ResourceLinkFilter": null, + "azure.mgmt.resource.links.models.ResourceLinkProperties": null, + "azure.mgmt.resource.links.models.ResourceLinkResult": null, + "azure.mgmt.resource.links.operations.Operations.list": null, + "azure.mgmt.resource.links.aio.operations.Operations.list": null, + "azure.mgmt.resource.links.operations.ResourceLinksOperations.delete": null, + "azure.mgmt.resource.links.aio.operations.ResourceLinksOperations.delete": null, + "azure.mgmt.resource.links.operations.ResourceLinksOperations.create_or_update": null, + "azure.mgmt.resource.links.aio.operations.ResourceLinksOperations.create_or_update": null, + "azure.mgmt.resource.links.operations.ResourceLinksOperations.get": null, + "azure.mgmt.resource.links.aio.operations.ResourceLinksOperations.get": null, + "azure.mgmt.resource.links.operations.ResourceLinksOperations.list_at_subscription": null, + "azure.mgmt.resource.links.aio.operations.ResourceLinksOperations.list_at_subscription": null, + "azure.mgmt.resource.links.operations.ResourceLinksOperations.list_at_source_scope": null, + "azure.mgmt.resource.links.aio.operations.ResourceLinksOperations.list_at_source_scope": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-links/azure/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/__init__.py new file mode 100644 index 000000000000..8405b984d233 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._management_link_client import ManagementLinkClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLinkClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_configuration.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_configuration.py new file mode 100644 index 000000000000..b9c4caf3eb26 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ManagementLinkClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-links/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_management_link_client.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_management_link_client.py new file mode 100644 index 000000000000..56904c29fed6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_management_link_client.py @@ -0,0 +1,130 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import ManagementLinkClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import Operations, ResourceLinksOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ManagementLinkClient: + """ManagementLink Client. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.resource.links.operations.Operations + :ivar resource_links: ResourceLinksOperations operations + :vartype resource_links: azure.mgmt.resource.links.operations.ResourceLinksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ManagementLinkClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.resource_links = ResourceLinksOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_patch.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_version.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/__init__.py new file mode 100644 index 000000000000..2d5efa026a0d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._management_link_client import ManagementLinkClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLinkClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_configuration.py new file mode 100644 index 000000000000..2611d4919174 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLinkClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-links/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_management_link_client.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_management_link_client.py new file mode 100644 index 000000000000..b59209cdd4cc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_management_link_client.py @@ -0,0 +1,134 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ManagementLinkClientConfiguration +from .operations import Operations, ResourceLinksOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLinkClient: + """ManagementLink Client. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.resource.links.aio.operations.Operations + :ivar resource_links: ResourceLinksOperations operations + :vartype resource_links: azure.mgmt.resource.links.aio.operations.ResourceLinksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ManagementLinkClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.resource_links = ResourceLinksOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_patch.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/__init__.py new file mode 100644 index 000000000000..f1aa3c6ca1ff --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import ResourceLinksOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "ResourceLinksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_operations.py new file mode 100644 index 000000000000..a36db6347964 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_operations.py @@ -0,0 +1,541 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_operations_list_request, + build_resource_links_create_or_update_request, + build_resource_links_delete_request, + build_resource_links_get_request, + build_resource_links_list_at_source_scope_request, + build_resource_links_list_at_subscription_request, +) +from .._configuration import ManagementLinkClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.aio.ManagementLinkClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Resources REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ResourceLinksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.aio.ManagementLinkClient`'s + :attr:`resource_links` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, link_id: str, **kwargs: Any) -> None: + """Deletes a resource link with the specified ID. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_resource_links_delete_request( + link_id=link_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, link_id: str, parameters: _models.ResourceLink, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: ~azure.mgmt.resource.links.models.ResourceLink + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, link_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, link_id: str, parameters: Union[_models.ResourceLink, IO[bytes]], **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Is either a + ResourceLink type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.links.models.ResourceLink or IO[bytes] + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ResourceLink") + + _request = build_resource_links_create_or_update_request( + link_id=link_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, link_id: str, **kwargs: Any) -> _models.ResourceLink: + """Gets a resource link with the specified ID. + + :param link_id: The fully qualified Id of the resource link. For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + _request = build_resource_links_get_request( + link_id=link_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_at_subscription( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.ResourceLink"]: + """Gets all the linked resources for the subscription. + + :param filter: The filter to apply on the list resource links operation. The supported filter + for list resource links is targetId. For example, $filter=targetId eq {value}. Default value is + None. + :type filter: str + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_resource_links_list_at_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_at_source_scope( + self, scope: str, filter: Literal["atScope()"] = "atScope()", **kwargs: Any + ) -> AsyncItemPaged["_models.ResourceLink"]: + """Gets a list of resource links at and below the specified source scope. + + :param scope: The fully qualified ID of the scope for getting the resource links. For example, + to list resource links at and under a resource group, set the scope to + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup. Required. + :type scope: str + :param filter: The filter to apply when getting resource links. To get links only at the + specified scope (not below the scope), use Filter.atScope(). Known values are "atScope()" and + None. Default value is "atScope()". + :type filter: str + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_resource_links_list_at_source_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/__init__.py new file mode 100644 index 000000000000..16e885e96822 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/__init__.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Operation, + OperationDisplay, + OperationListResult, + ResourceLink, + ResourceLinkFilter, + ResourceLinkProperties, + ResourceLinkResult, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operation", + "OperationDisplay", + "OperationListResult", + "ResourceLink", + "ResourceLinkFilter", + "ResourceLinkProperties", + "ResourceLinkResult", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_models_py3.py new file mode 100644 index 000000000000..82d2a16c2035 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_models_py3.py @@ -0,0 +1,257 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +from typing import Any, Optional, TYPE_CHECKING + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class Operation(_serialization.Model): + """Microsoft.Resources operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.links.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.links.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Resources. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + :ivar description: Description of the operation. + :vartype description: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Resources. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + :keyword description: Description of the operation. + :paramtype description: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Resources operations. It contains a list of operations + and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Resources operations. + :vartype value: list[~azure.mgmt.resource.links.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Resources operations. + :paramtype value: list[~azure.mgmt.resource.links.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ResourceLink(_serialization.Model): + """The resource link. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The fully qualified ID of the resource link. + :vartype id: str + :ivar name: The name of the resource link. + :vartype name: str + :ivar type: The resource link object. + :vartype type: JSON + :ivar properties: Properties for resource link. + :vartype properties: ~azure.mgmt.resource.links.models.ResourceLinkProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "object"}, + "properties": {"key": "properties", "type": "ResourceLinkProperties"}, + } + + def __init__(self, *, properties: Optional["_models.ResourceLinkProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Properties for resource link. + :paramtype properties: ~azure.mgmt.resource.links.models.ResourceLinkProperties + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[JSON] = None + self.properties = properties + + +class ResourceLinkFilter(_serialization.Model): + """Resource link filter. + + All required parameters must be populated in order to send to server. + + :ivar target_id: The ID of the target resource. Required. + :vartype target_id: str + """ + + _validation = { + "target_id": {"required": True}, + } + + _attribute_map = { + "target_id": {"key": "targetId", "type": "str"}, + } + + def __init__(self, *, target_id: str, **kwargs: Any) -> None: + """ + :keyword target_id: The ID of the target resource. Required. + :paramtype target_id: str + """ + super().__init__(**kwargs) + self.target_id = target_id + + +class ResourceLinkProperties(_serialization.Model): + """The resource link properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar source_id: The fully qualified ID of the source resource in the link. + :vartype source_id: str + :ivar target_id: The fully qualified ID of the target resource in the link. Required. + :vartype target_id: str + :ivar notes: Notes about the resource link. + :vartype notes: str + """ + + _validation = { + "source_id": {"readonly": True}, + "target_id": {"required": True}, + } + + _attribute_map = { + "source_id": {"key": "sourceId", "type": "str"}, + "target_id": {"key": "targetId", "type": "str"}, + "notes": {"key": "notes", "type": "str"}, + } + + def __init__(self, *, target_id: str, notes: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword target_id: The fully qualified ID of the target resource in the link. Required. + :paramtype target_id: str + :keyword notes: Notes about the resource link. + :paramtype notes: str + """ + super().__init__(**kwargs) + self.source_id: Optional[str] = None + self.target_id = target_id + self.notes = notes + + +class ResourceLinkResult(_serialization.Model): + """List of resource links. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar value: An array of resource links. Required. + :vartype value: list[~azure.mgmt.resource.links.models.ResourceLink] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ResourceLink]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: list["_models.ResourceLink"], **kwargs: Any) -> None: + """ + :keyword value: An array of resource links. Required. + :paramtype value: list[~azure.mgmt.resource.links.models.ResourceLink] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_patch.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/__init__.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/__init__.py new file mode 100644 index 000000000000..f1aa3c6ca1ff --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import ResourceLinksOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "ResourceLinksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_operations.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_operations.py new file mode 100644 index 000000000000..ed9fb7ab43bb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_operations.py @@ -0,0 +1,679 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import ManagementLinkClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_operations_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_delete_request(link_id: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop("template_url", "/{linkId}") + path_format_arguments = { + "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_resource_links_create_or_update_request( # pylint: disable=name-too-long + link_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{linkId}") + path_format_arguments = { + "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_get_request(link_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{linkId}") + path_format_arguments = { + "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_list_at_subscription_request( # pylint: disable=name-too-long + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/links") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_list_at_source_scope_request( # pylint: disable=name-too-long + scope: str, *, filter: Literal["atScope()"] = "atScope()", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Resources/links") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.ManagementLinkClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Resources REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ResourceLinksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.ManagementLinkClient`'s + :attr:`resource_links` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, link_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a resource link with the specified ID. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_resource_links_delete_request( + link_id=link_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, link_id: str, parameters: _models.ResourceLink, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: ~azure.mgmt.resource.links.models.ResourceLink + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, link_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, link_id: str, parameters: Union[_models.ResourceLink, IO[bytes]], **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Is either a + ResourceLink type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.links.models.ResourceLink or IO[bytes] + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ResourceLink") + + _request = build_resource_links_create_or_update_request( + link_id=link_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, link_id: str, **kwargs: Any) -> _models.ResourceLink: + """Gets a resource link with the specified ID. + + :param link_id: The fully qualified Id of the resource link. For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + _request = build_resource_links_get_request( + link_id=link_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_at_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.ResourceLink"]: + """Gets all the linked resources for the subscription. + + :param filter: The filter to apply on the list resource links operation. The supported filter + for list resource links is targetId. For example, $filter=targetId eq {value}. Default value is + None. + :type filter: str + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_resource_links_list_at_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_at_source_scope( + self, scope: str, filter: Literal["atScope()"] = "atScope()", **kwargs: Any + ) -> ItemPaged["_models.ResourceLink"]: + """Gets a list of resource links at and below the specified source scope. + + :param scope: The fully qualified ID of the scope for getting the resource links. For example, + to list resource links at and under a resource group, set the scope to + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup. Required. + :type scope: str + :param filter: The filter to apply when getting resource links. To get links only at the + specified scope (not below the scope), use Filter.atScope(). Known values are "atScope()" and + None. Default value is "atScope()". + :type filter: str + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_resource_links_list_at_source_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_patch.py b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/py.typed b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/azure/mgmt/resource/links/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-links/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-links/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-links/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-links/generated_tests/conftest.py new file mode 100644 index 000000000000..b2c242d509e3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementlink_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + managementlink_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementlink_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementlink_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations.py b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations.py new file mode 100644 index 000000000000..e267f119cb12 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLinkOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations_async.py b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations_async.py new file mode 100644 index 000000000000..1a27683f3d5c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links.aio import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLinkOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations.py b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations.py new file mode 100644 index 000000000000..73e3130d31c8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations.py @@ -0,0 +1,79 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLinkResourceLinksOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_links_delete(self, resource_group): + response = self.client.resource_links.delete( + link_id="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_links_create_or_update(self, resource_group): + response = self.client.resource_links.create_or_update( + link_id="str", + parameters={ + "id": "str", + "name": "str", + "properties": {"targetId": "str", "notes": "str", "sourceId": "str"}, + "type": {}, + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_links_get(self, resource_group): + response = self.client.resource_links.get( + link_id="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_links_list_at_subscription(self, resource_group): + response = self.client.resource_links.list_at_subscription( + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_links_list_at_source_scope(self, resource_group): + response = self.client.resource_links.list_at_source_scope( + scope="str", + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations_async.py b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations_async.py new file mode 100644 index 000000000000..291bf615cf33 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/generated_tests/test_management_link_resource_links_operations_async.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links.aio import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLinkResourceLinksOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_links_delete(self, resource_group): + response = await self.client.resource_links.delete( + link_id="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_links_create_or_update(self, resource_group): + response = await self.client.resource_links.create_or_update( + link_id="str", + parameters={ + "id": "str", + "name": "str", + "properties": {"targetId": "str", "notes": "str", "sourceId": "str"}, + "type": {}, + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_links_get(self, resource_group): + response = await self.client.resource_links.get( + link_id="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_links_list_at_subscription(self, resource_group): + response = self.client.resource_links.list_at_subscription( + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_links_list_at_source_scope(self, resource_group): + response = self.client.resource_links.list_at_source_scope( + scope="str", + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-links/pyproject.toml b/sdk/resources/azure-mgmt-resource-links/pyproject.toml new file mode 100644 index 000000000000..c1f7a220d144 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-links" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Links Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.links._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-links" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Links Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "ManagementLinkClient" diff --git a/sdk/resources/azure-mgmt-resource-links/tests/conftest.py b/sdk/resources/azure-mgmt-resource-links/tests/conftest.py new file mode 100644 index 000000000000..b2c242d509e3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementlink_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + managementlink_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementlink_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementlink_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlink_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_async_test.py b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_async_test.py new file mode 100644 index 000000000000..4ce19af79117 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links.aio import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLinkOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_test.py b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_test.py new file mode 100644 index 000000000000..11b3a09bc4e5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLinkOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_async_test.py b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_async_test.py new file mode 100644 index 000000000000..fe5b1c271378 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links.aio import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLinkResourceLinksOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_resource_links_list_at_subscription(self, resource_group): + response = self.client.resource_links.list_at_subscription() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_test.py b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_test.py new file mode 100644 index 000000000000..77a0c71f861c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-links/tests/test_management_link_resource_links_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.links import ManagementLinkClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLinkResourceLinksOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLinkClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_resource_links_list_at_subscription(self, resource_group): + response = self.client.resource_links.list_at_subscription() + result = [r for r in response] + assert response From fb8beeb465d0131f19d0c3382e94c185346b800d Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:27:05 -0800 Subject: [PATCH 54/84] [AutoRelease] t2-resource-databoundaries-2026-02-05-66014(can only be merged by SDK owner) (#45014) * code and test * update doc * update changelog --------- Co-authored-by: azure-sdk Co-authored-by: Yuchao Yan Co-authored-by: ChenxiJiang333 --- .../CHANGELOG.md | 7 + .../LICENSE | 21 + .../MANIFEST.in | 8 + .../README.md | 57 + .../_metadata.json | 11 + .../apiview-properties.json | 23 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../mgmt/resource/databoundaries/__init__.py | 32 + .../resource/databoundaries/_configuration.py | 66 + .../_data_boundary_mgmt_client.py | 121 + .../mgmt/resource/databoundaries/_patch.py | 21 + .../databoundaries/_utils/__init__.py | 6 + .../databoundaries/_utils/serialization.py | 2041 +++++++++++++++++ .../mgmt/resource/databoundaries/_version.py | 9 + .../resource/databoundaries/aio/__init__.py | 29 + .../databoundaries/aio/_configuration.py | 66 + .../aio/_data_boundary_mgmt_client.py | 125 + .../resource/databoundaries/aio/_patch.py | 21 + .../databoundaries/aio/operations/__init__.py | 25 + .../aio/operations/_operations.py | 299 +++ .../databoundaries/aio/operations/_patch.py | 21 + .../databoundaries/models/__init__.py | 52 + .../_data_boundary_mgmt_client_enums.py | 46 + .../databoundaries/models/_models_py3.py | 314 +++ .../resource/databoundaries/models/_patch.py | 21 + .../databoundaries/operations/__init__.py | 25 + .../databoundaries/operations/_operations.py | 373 +++ .../databoundaries/operations/_patch.py | 21 + .../mgmt/resource/databoundaries/py.typed | 1 + .../dev_requirements.txt | 5 + .../get_scoped_data_boundary.py | 42 + .../get_tenant_data_boundary.py | 41 + .../generated_samples/put_data_boundary.py | 42 + .../generated_tests/conftest.py | 35 + ...oundary_mgmt_data_boundaries_operations.py | 67 + ...y_mgmt_data_boundaries_operations_async.py | 68 + .../pyproject.toml | 88 + .../tests/conftest.py | 35 + ...t_data_boundaries_operations_async_test.py | 40 + ...ry_mgmt_data_boundaries_operations_test.py | 39 + 42 files changed, 4367 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/README.md create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_scoped_data_boundary.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_tenant_data_boundary.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/put_data_boundary.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-databoundaries/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/LICENSE b/sdk/resources/azure-mgmt-resource-databoundaries/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/MANIFEST.in b/sdk/resources/azure-mgmt-resource-databoundaries/MANIFEST.in new file mode 100644 index 000000000000..4849f443ddbc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/databoundaries/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/README.md b/sdk/resources/azure-mgmt-resource-databoundaries/README.md new file mode 100644 index 000000000000..956bbbd53fb0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/README.md @@ -0,0 +1,57 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Databoundaries Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-databoundaries +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient + +client = DataBoundaryMgmtClient(credential=DefaultAzureCredential()) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Databoundaries Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/_metadata.json b/sdk/resources/azure-mgmt-resource-databoundaries/_metadata.json new file mode 100644 index 000000000000..dda9d1db48b6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "93edc09ba3d879875fe0fcca6db36a61ff27b2d6", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Resources/databoundaries/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-databoundaries-2024-08 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Resources/databoundaries/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/apiview-properties.json b/sdk/resources/azure-mgmt-resource-databoundaries/apiview-properties.json new file mode 100644 index 000000000000..18a218e36297 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/apiview-properties.json @@ -0,0 +1,23 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.databoundaries.models.Resource": null, + "azure.mgmt.resource.databoundaries.models.ProxyResource": null, + "azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition": null, + "azure.mgmt.resource.databoundaries.models.DataBoundaryProperties": null, + "azure.mgmt.resource.databoundaries.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.databoundaries.models.ErrorDetail": null, + "azure.mgmt.resource.databoundaries.models.ErrorResponse": null, + "azure.mgmt.resource.databoundaries.models.SystemData": null, + "azure.mgmt.resource.databoundaries.models.DefaultName": null, + "azure.mgmt.resource.databoundaries.models.DataBoundary": null, + "azure.mgmt.resource.databoundaries.models.ProvisioningState": null, + "azure.mgmt.resource.databoundaries.models.CreatedByType": null, + "azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations.put": null, + "azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations.put": null, + "azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations.get_tenant": null, + "azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations.get_tenant": null, + "azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations.get_scope": null, + "azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations.get_scope": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/__init__.py new file mode 100644 index 000000000000..bdb7fb5d678b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_boundary_mgmt_client import DataBoundaryMgmtClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataBoundaryMgmtClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_configuration.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_configuration.py new file mode 100644 index 000000000000..4a4f78447f92 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class DataBoundaryMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for DataBoundaryMgmtClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, credential: "TokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-databoundaries/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py new file mode 100644 index 000000000000..3f47495b4635 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import DataBoundaryMgmtClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import DataBoundariesOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class DataBoundaryMgmtClient: + """DataBoundaryMgmt Client. + + :ivar data_boundaries: DataBoundariesOperations operations + :vartype data_boundaries: + azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = DataBoundaryMgmtClientConfiguration( + credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.data_boundaries = DataBoundariesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_patch.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_version.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/__init__.py new file mode 100644 index 000000000000..232f214e1b14 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_boundary_mgmt_client import DataBoundaryMgmtClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataBoundaryMgmtClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_configuration.py new file mode 100644 index 000000000000..b236e51c181d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class DataBoundaryMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for DataBoundaryMgmtClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, credential: "AsyncTokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-databoundaries/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py new file mode 100644 index 000000000000..c25cf2787f8e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py @@ -0,0 +1,125 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import DataBoundaryMgmtClientConfiguration +from .operations import DataBoundariesOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class DataBoundaryMgmtClient: + """DataBoundaryMgmt Client. + + :ivar data_boundaries: DataBoundariesOperations operations + :vartype data_boundaries: + azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = DataBoundaryMgmtClientConfiguration( + credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.data_boundaries = DataBoundariesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_patch.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/__init__.py new file mode 100644 index 000000000000..3cd0a7f40599 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataBoundariesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataBoundariesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_operations.py new file mode 100644 index 000000000000..1fd666cbbdbe --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_operations.py @@ -0,0 +1,299 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_data_boundaries_get_scope_request, + build_data_boundaries_get_tenant_request, + build_data_boundaries_put_request, +) +from .._configuration import DataBoundaryMgmtClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class DataBoundariesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.databoundaries.aio.DataBoundaryMgmtClient`'s + :attr:`data_boundaries` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: DataBoundaryMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def put( + self, + default: Union[str, _models.DefaultName], + data_boundary_definition: _models.DataBoundaryDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Opt-in tenant to data boundary. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :param data_boundary_definition: The data boundary to opt the tenant to. Required. + :type data_boundary_definition: + ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, + default: Union[str, _models.DefaultName], + data_boundary_definition: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Opt-in tenant to data boundary. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :param data_boundary_definition: The data boundary to opt the tenant to. Required. + :type data_boundary_definition: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, + default: Union[str, _models.DefaultName], + data_boundary_definition: Union[_models.DataBoundaryDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Opt-in tenant to data boundary. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :param data_boundary_definition: The data boundary to opt the tenant to. Is either a + DataBoundaryDefinition type or a IO[bytes] type. Required. + :type data_boundary_definition: + ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition or IO[bytes] + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(data_boundary_definition, (IOBase, bytes)): + _content = data_boundary_definition + else: + _json = self._serialize.body(data_boundary_definition, "DataBoundaryDefinition") + + _request = build_data_boundaries_put_request( + default=default, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_tenant( + self, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Get data boundary of tenant. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) + + _request = build_data_boundaries_get_tenant_request( + default=default, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_scope( + self, scope: str, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Get data boundary at specified scope. + + :param scope: The scope at which the operation is performed. Required. + :type scope: str + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) + + _request = build_data_boundaries_get_scope_request( + scope=scope, + default=default, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/__init__.py new file mode 100644 index 000000000000..5a86d6a8b2c5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/__init__.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + DataBoundaryDefinition, + DataBoundaryProperties, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + ProxyResource, + Resource, + SystemData, +) + +from ._data_boundary_mgmt_client_enums import ( # type: ignore + CreatedByType, + DataBoundary, + DefaultName, + ProvisioningState, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataBoundaryDefinition", + "DataBoundaryProperties", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "ProxyResource", + "Resource", + "SystemData", + "CreatedByType", + "DataBoundary", + "DefaultName", + "ProvisioningState", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py new file mode 100644 index 000000000000..0c06bfddfbf2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py @@ -0,0 +1,46 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class DataBoundary(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The data boundary definition.""" + + NOT_DEFINED = "NotDefined" + GLOBAL = "Global" + EU = "EU" + GLOBAL_ENUM = "Global" + + +class DefaultName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """DefaultName.""" + + DEFAULT = "default" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Denotes the state of provisioning.""" + + ACCEPTED = "Accepted" + RUNNING = "Running" + CREATING = "Creating" + CANCELED = "Canceled" + FAILED = "Failed" + SUCCEEDED = "Succeeded" + UPDATING = "Updating" diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_models_py3.py new file mode 100644 index 000000000000..99b131976286 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_models_py3.py @@ -0,0 +1,314 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +import datetime +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.databoundaries.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have + tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.databoundaries.models.SystemData + """ + + +class DataBoundaryDefinition(ProxyResource): + """A data boundary definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.databoundaries.models.SystemData + :ivar properties: Data boundary properties. + :vartype properties: ~azure.mgmt.resource.databoundaries.models.DataBoundaryProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "DataBoundaryProperties"}, + } + + def __init__(self, *, properties: Optional["_models.DataBoundaryProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Data boundary properties. + :paramtype properties: ~azure.mgmt.resource.databoundaries.models.DataBoundaryProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class DataBoundaryProperties(_serialization.Model): + """Data boundary properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar data_boundary: The data boundary definition. Known values are: "NotDefined", "Global", + "EU", and "Global". + :vartype data_boundary: str or ~azure.mgmt.resource.databoundaries.models.DataBoundary + :ivar provisioning_state: Denotes the state of provisioning. Known values are: "Accepted", + "Running", "Creating", "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.databoundaries.models.ProvisioningState + """ + + _validation = { + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "data_boundary": {"key": "dataBoundary", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + } + + def __init__(self, *, data_boundary: Optional[Union[str, "_models.DataBoundary"]] = None, **kwargs: Any) -> None: + """ + :keyword data_boundary: The data boundary definition. Known values are: "NotDefined", "Global", + "EU", and "Global". + :paramtype data_boundary: str or ~azure.mgmt.resource.databoundaries.models.DataBoundary + """ + super().__init__(**kwargs) + self.data_boundary = data_boundary + self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.databoundaries.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.databoundaries.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorDetail"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.resource.databoundaries.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.resource.databoundaries.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.resource.databoundaries.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.resource.databoundaries.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.resource.databoundaries.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or + ~azure.mgmt.resource.databoundaries.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_patch.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/__init__.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/__init__.py new file mode 100644 index 000000000000..3cd0a7f40599 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataBoundariesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataBoundariesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_operations.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_operations.py new file mode 100644 index 000000000000..02f1208a4b58 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_operations.py @@ -0,0 +1,373 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import DataBoundaryMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_data_boundaries_put_request(default: Union[str, _models.DefaultName], **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/dataBoundaries/{default}") + path_format_arguments = { + "default": _SERIALIZER.url("default", default, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_boundaries_get_tenant_request(default: Union[str, _models.DefaultName], **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/dataBoundaries/{default}") + path_format_arguments = { + "default": _SERIALIZER.url("default", default, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_boundaries_get_scope_request( + scope: str, default: Union[str, _models.DefaultName], **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True, min_length=1), + "default": _SERIALIZER.url("default", default, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DataBoundariesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.databoundaries.DataBoundaryMgmtClient`'s + :attr:`data_boundaries` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: DataBoundaryMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def put( + self, + default: Union[str, _models.DefaultName], + data_boundary_definition: _models.DataBoundaryDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Opt-in tenant to data boundary. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :param data_boundary_definition: The data boundary to opt the tenant to. Required. + :type data_boundary_definition: + ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, + default: Union[str, _models.DefaultName], + data_boundary_definition: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Opt-in tenant to data boundary. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :param data_boundary_definition: The data boundary to opt the tenant to. Required. + :type data_boundary_definition: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, + default: Union[str, _models.DefaultName], + data_boundary_definition: Union[_models.DataBoundaryDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Opt-in tenant to data boundary. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :param data_boundary_definition: The data boundary to opt the tenant to. Is either a + DataBoundaryDefinition type or a IO[bytes] type. Required. + :type data_boundary_definition: + ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition or IO[bytes] + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(data_boundary_definition, (IOBase, bytes)): + _content = data_boundary_definition + else: + _json = self._serialize.body(data_boundary_definition, "DataBoundaryDefinition") + + _request = build_data_boundaries_put_request( + default=default, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_tenant(self, default: Union[str, _models.DefaultName], **kwargs: Any) -> _models.DataBoundaryDefinition: + """Get data boundary of tenant. + + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) + + _request = build_data_boundaries_get_tenant_request( + default=default, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_scope( + self, scope: str, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> _models.DataBoundaryDefinition: + """Get data boundary at specified scope. + + :param scope: The scope at which the operation is performed. Required. + :type scope: str + :param default: Default string modeled as parameter for auto generation to work correctly. + "default" Required. + :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName + :return: DataBoundaryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) + + _request = build_data_boundaries_get_scope_request( + scope=scope, + default=default, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_patch.py b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/py.typed b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/azure/mgmt/resource/databoundaries/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-databoundaries/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_scoped_data_boundary.py b/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_scoped_data_boundary.py new file mode 100644 index 000000000000..f2dd06ebb7b2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_scoped_data_boundary.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-databoundaries +# USAGE + python get_scoped_data_boundary.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DataBoundaryMgmtClient( + credential=DefaultAzureCredential(), + ) + + response = client.data_boundaries.get_scope( + scope="subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group", + default="default", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/databoundaries/stable/2024-08-01/examples/GetScopedDataBoundary.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_tenant_data_boundary.py b/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_tenant_data_boundary.py new file mode 100644 index 000000000000..150691508555 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/get_tenant_data_boundary.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-databoundaries +# USAGE + python get_tenant_data_boundary.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DataBoundaryMgmtClient( + credential=DefaultAzureCredential(), + ) + + response = client.data_boundaries.get_tenant( + default="default", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/databoundaries/stable/2024-08-01/examples/GetTenantDataBoundary.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/put_data_boundary.py b/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/put_data_boundary.py new file mode 100644 index 000000000000..2b7071272416 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/generated_samples/put_data_boundary.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-databoundaries +# USAGE + python put_data_boundary.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DataBoundaryMgmtClient( + credential=DefaultAzureCredential(), + ) + + response = client.data_boundaries.put( + default="default", + data_boundary_definition={"properties": {"dataBoundary": "EU"}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/databoundaries/stable/2024-08-01/examples/PutDataBoundary.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/conftest.py new file mode 100644 index 000000000000..d0a3b52e198a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + databoundarymgmt_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + databoundarymgmt_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + databoundarymgmt_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + databoundarymgmt_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py b/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py new file mode 100644 index 000000000000..34eac057d847 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDataBoundaryMgmtDataBoundariesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(DataBoundaryMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_boundaries_put(self, resource_group): + response = self.client.data_boundaries.put( + default="str", + data_boundary_definition={ + "id": "str", + "name": "str", + "properties": {"dataBoundary": "str", "provisioningState": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-08-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_boundaries_get_tenant(self, resource_group): + response = self.client.data_boundaries.get_tenant( + default="str", + api_version="2024-08-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_boundaries_get_scope(self, resource_group): + response = self.client.data_boundaries.get_scope( + scope="str", + default="str", + api_version="2024-08-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py b/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py new file mode 100644 index 000000000000..ca7627519d79 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py @@ -0,0 +1,68 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.databoundaries.aio import DataBoundaryMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDataBoundaryMgmtDataBoundariesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(DataBoundaryMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_boundaries_put(self, resource_group): + response = await self.client.data_boundaries.put( + default="str", + data_boundary_definition={ + "id": "str", + "name": "str", + "properties": {"dataBoundary": "str", "provisioningState": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-08-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_boundaries_get_tenant(self, resource_group): + response = await self.client.data_boundaries.get_tenant( + default="str", + api_version="2024-08-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_boundaries_get_scope(self, resource_group): + response = await self.client.data_boundaries.get_scope( + scope="str", + default="str", + api_version="2024-08-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/pyproject.toml b/sdk/resources/azure-mgmt-resource-databoundaries/pyproject.toml new file mode 100644 index 000000000000..54250a753dae --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/pyproject.toml @@ -0,0 +1,88 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-databoundaries" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Databoundaries Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.databoundaries._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-databoundaries" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Databoundaries Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +no_sub = true +title = "DataBoundaryMgmtClient" diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/tests/conftest.py b/sdk/resources/azure-mgmt-resource-databoundaries/tests/conftest.py new file mode 100644 index 000000000000..d0a3b52e198a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + databoundarymgmt_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + databoundarymgmt_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + databoundarymgmt_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + databoundarymgmt_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=databoundarymgmt_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py b/sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py new file mode 100644 index 000000000000..254306c7de52 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.databoundaries.aio import DataBoundaryMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestDataBoundaryMgmtDataBoundariesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(DataBoundaryMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_boundaries_get_tenant(self, resource_group): + response = await self.client.data_boundaries.get_tenant( + default="default", + ) + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_boundaries_get_scope(self, resource_group): + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + response = await self.client.data_boundaries.get_scope( + scope=f"subscriptions/{SUBSCRIPTION_ID}", + default="default", + ) + + assert response diff --git a/sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py b/sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py new file mode 100644 index 000000000000..21d18ac9107b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-databoundaries/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestDataBoundaryMgmtDataBoundariesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(DataBoundaryMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_boundaries_get_tenant(self, resource_group): + response = self.client.data_boundaries.get_tenant( + default="default", + ) + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_boundaries_get_scope(self, resource_group): + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + response = self.client.data_boundaries.get_scope( + scope=f"subscriptions/{SUBSCRIPTION_ID}", + default="default", + ) + + assert response From 7718690aa4e17c820155030cc3f98de11447f8f3 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:27:34 -0800 Subject: [PATCH 55/84] [AutoRelease] t2-resource-subscriptions-2026-02-05-30452(can only be merged by SDK owner) (#45019) * code and test * Fix README to remove subscription_id parameter and add no_sub flag * update --------- Co-authored-by: azure-sdk Co-authored-by: Yuchao Yan Co-authored-by: ChenxiJiang333 --- .../CHANGELOG.md | 7 + .../azure-mgmt-resource-subscriptions/LICENSE | 21 + .../MANIFEST.in | 8 + .../README.md | 57 + .../_metadata.json | 11 + .../apiview-properties.json | 55 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../mgmt/resource/subscriptions/__init__.py | 32 + .../resource/subscriptions/_configuration.py | 66 + .../mgmt/resource/subscriptions/_patch.py | 21 + .../subscriptions/_subscription_client.py | 126 + .../resource/subscriptions/_utils/__init__.py | 6 + .../subscriptions/_utils/serialization.py | 2041 +++++++++++++++++ .../resource/subscriptions/_utils/utils.py | 25 + .../mgmt/resource/subscriptions/_version.py | 9 + .../resource/subscriptions/aio/__init__.py | 29 + .../subscriptions/aio/_configuration.py | 66 + .../mgmt/resource/subscriptions/aio/_patch.py | 21 + .../subscriptions/aio/_subscription_client.py | 131 ++ .../subscriptions/aio/operations/__init__.py | 30 + .../aio/operations/_operations.py | 702 ++++++ .../subscriptions/aio/operations/_patch.py | 21 + .../resource/subscriptions/models/__init__.py | 100 + .../subscriptions/models/_models_py3.py | 1112 +++++++++ .../resource/subscriptions/models/_patch.py | 21 + .../models/_subscription_client_enums.py | 81 + .../subscriptions/operations/__init__.py | 30 + .../subscriptions/operations/_operations.py | 853 +++++++ .../subscriptions/operations/_patch.py | 21 + .../mgmt/resource/subscriptions/py.typed | 1 + .../dev_requirements.txt | 5 + .../generated_samples/check_resource_name.py | 39 + .../generated_samples/get_locations.py | 42 + .../get_locations_with_extended_locations.py | 42 + .../generated_samples/get_subscription.py | 41 + .../generated_samples/get_subscriptions.py | 40 + .../generated_samples/get_tenants.py | 40 + .../post_check_zone_peers.py | 42 + .../generated_tests/conftest.py | 35 + .../generated_tests/test_subscription.py | 29 + .../test_subscription_async.py | 30 + .../test_subscription_operations.py | 29 + .../test_subscription_operations_async.py | 30 + ...t_subscription_subscriptions_operations.py | 63 + ...cription_subscriptions_operations_async.py | 64 + .../test_subscription_tenants_operations.py | 29 + ...t_subscription_tenants_operations_async.py | 30 + .../pyproject.toml | 88 + .../tests/conftest.py | 35 + ...test_subscription_operations_async_test.py | 27 + .../test_subscription_operations_test.py | 26 + ...ion_subscriptions_operations_async_test.py | 47 + ...scription_subscriptions_operations_test.py | 46 + ...scription_tenants_operations_async_test.py | 27 + ...st_subscription_tenants_operations_test.py | 26 + 57 files changed, 6659 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/README.md create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_subscription_client.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/utils.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_subscription_client.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/check_resource_name.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations_with_extended_locations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscription.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscriptions.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_tenants.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/post_check_zone_peers.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_async.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-subscriptions/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/LICENSE b/sdk/resources/azure-mgmt-resource-subscriptions/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/MANIFEST.in b/sdk/resources/azure-mgmt-resource-subscriptions/MANIFEST.in new file mode 100644 index 000000000000..530161304fe2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/subscriptions/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/README.md b/sdk/resources/azure-mgmt-resource-subscriptions/README.md new file mode 100644 index 000000000000..d148cc319808 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/README.md @@ -0,0 +1,57 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Subscriptions Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-subscriptions +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.subscriptions import SubscriptionClient + +client = SubscriptionClient(credential=DefaultAzureCredential()) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Subscriptions Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/_metadata.json b/sdk/resources/azure-mgmt-resource-subscriptions/_metadata.json new file mode 100644 index 000000000000..22e129b3b740 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Resources/subscriptions/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-subscriptions-2022-12 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Resources/subscriptions/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/apiview-properties.json b/sdk/resources/azure-mgmt-resource-subscriptions/apiview-properties.json new file mode 100644 index 000000000000..68e22d8c461d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/apiview-properties.json @@ -0,0 +1,55 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.subscriptions.models.AvailabilityZoneMappings": null, + "azure.mgmt.resource.subscriptions.models.AvailabilityZonePeers": null, + "azure.mgmt.resource.subscriptions.models.CheckResourceNameResult": null, + "azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest": null, + "azure.mgmt.resource.subscriptions.models.CheckZonePeersResult": null, + "azure.mgmt.resource.subscriptions.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.subscriptions.models.ErrorDetail": null, + "azure.mgmt.resource.subscriptions.models.ErrorResponse": null, + "azure.mgmt.resource.subscriptions.models.ErrorResponseAutoGenerated": null, + "azure.mgmt.resource.subscriptions.models.Location": null, + "azure.mgmt.resource.subscriptions.models.LocationListResult": null, + "azure.mgmt.resource.subscriptions.models.LocationMetadata": null, + "azure.mgmt.resource.subscriptions.models.ManagedByTenant": null, + "azure.mgmt.resource.subscriptions.models.Operation": null, + "azure.mgmt.resource.subscriptions.models.OperationAutoGenerated": null, + "azure.mgmt.resource.subscriptions.models.OperationDisplay": null, + "azure.mgmt.resource.subscriptions.models.OperationDisplayAutoGenerated": null, + "azure.mgmt.resource.subscriptions.models.OperationListResult": null, + "azure.mgmt.resource.subscriptions.models.OperationListResultAutoGenerated": null, + "azure.mgmt.resource.subscriptions.models.PairedRegion": null, + "azure.mgmt.resource.subscriptions.models.Peers": null, + "azure.mgmt.resource.subscriptions.models.ResourceName": null, + "azure.mgmt.resource.subscriptions.models.Subscription": null, + "azure.mgmt.resource.subscriptions.models.SubscriptionListResult": null, + "azure.mgmt.resource.subscriptions.models.SubscriptionPolicies": null, + "azure.mgmt.resource.subscriptions.models.TenantIdDescription": null, + "azure.mgmt.resource.subscriptions.models.TenantListResult": null, + "azure.mgmt.resource.subscriptions.models.Origin": null, + "azure.mgmt.resource.subscriptions.models.ActionType": null, + "azure.mgmt.resource.subscriptions.models.LocationType": null, + "azure.mgmt.resource.subscriptions.models.RegionType": null, + "azure.mgmt.resource.subscriptions.models.RegionCategory": null, + "azure.mgmt.resource.subscriptions.models.SubscriptionState": null, + "azure.mgmt.resource.subscriptions.models.SpendingLimit": null, + "azure.mgmt.resource.subscriptions.models.TenantCategory": null, + "azure.mgmt.resource.subscriptions.models.ResourceNameStatus": null, + "azure.mgmt.resource.subscriptions.operations.Operations.list": null, + "azure.mgmt.resource.subscriptions.aio.operations.Operations.list": null, + "azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations.list_locations": null, + "azure.mgmt.resource.subscriptions.aio.operations.SubscriptionsOperations.list_locations": null, + "azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations.get": null, + "azure.mgmt.resource.subscriptions.aio.operations.SubscriptionsOperations.get": null, + "azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations.list": null, + "azure.mgmt.resource.subscriptions.aio.operations.SubscriptionsOperations.list": null, + "azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations.check_zone_peers": null, + "azure.mgmt.resource.subscriptions.aio.operations.SubscriptionsOperations.check_zone_peers": null, + "azure.mgmt.resource.subscriptions.operations.TenantsOperations.list": null, + "azure.mgmt.resource.subscriptions.aio.operations.TenantsOperations.list": null, + "azure.mgmt.resource.subscriptions.SubscriptionClient.check_resource_name": null, + "azure.mgmt.resource.subscriptions.aio.SubscriptionClient.check_resource_name": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/__init__.py new file mode 100644 index 000000000000..2ce2c3a5dd64 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._subscription_client import SubscriptionClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "SubscriptionClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_configuration.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_configuration.py new file mode 100644 index 000000000000..44557513806e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class SubscriptionClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SubscriptionClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, credential: "TokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2022-12-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-subscriptions/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_patch.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_subscription_client.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_subscription_client.py new file mode 100644 index 000000000000..d355129648ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_subscription_client.py @@ -0,0 +1,126 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import SubscriptionClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import Operations, SubscriptionsOperations, TenantsOperations, _SubscriptionClientOperationsMixin + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class SubscriptionClient(_SubscriptionClientOperationsMixin): + """Subscription Client. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.resource.subscriptions.operations.Operations + :ivar subscriptions: SubscriptionsOperations operations + :vartype subscriptions: azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations + :ivar tenants: TenantsOperations operations + :vartype tenants: azure.mgmt.resource.subscriptions.operations.TenantsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = SubscriptionClientConfiguration( + credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.subscriptions = SubscriptionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.tenants = TenantsOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/utils.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/utils.py new file mode 100644 index 000000000000..39b612f39a9b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_utils/utils.py @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, TYPE_CHECKING, TypeVar + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_version.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/__init__.py new file mode 100644 index 000000000000..bb5ad1b4e042 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._subscription_client import SubscriptionClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "SubscriptionClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_configuration.py new file mode 100644 index 000000000000..edf1cb950246 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class SubscriptionClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SubscriptionClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, credential: "AsyncTokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2022-12-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-subscriptions/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_patch.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_subscription_client.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_subscription_client.py new file mode 100644 index 000000000000..9c3611095373 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/_subscription_client.py @@ -0,0 +1,131 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import SubscriptionClientConfiguration +from .operations import Operations, SubscriptionsOperations, TenantsOperations, _SubscriptionClientOperationsMixin + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class SubscriptionClient(_SubscriptionClientOperationsMixin): + """Subscription Client. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.resource.subscriptions.aio.operations.Operations + :ivar subscriptions: SubscriptionsOperations operations + :vartype subscriptions: + azure.mgmt.resource.subscriptions.aio.operations.SubscriptionsOperations + :ivar tenants: TenantsOperations operations + :vartype tenants: azure.mgmt.resource.subscriptions.aio.operations.TenantsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = SubscriptionClientConfiguration( + credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.subscriptions = SubscriptionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.tenants = TenantsOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/__init__.py new file mode 100644 index 000000000000..d43f10f233ab --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/__init__.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import SubscriptionsOperations # type: ignore +from ._operations import TenantsOperations # type: ignore +from ._operations import _SubscriptionClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "SubscriptionsOperations", + "TenantsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_operations.py new file mode 100644 index 000000000000..e89f7bbedb58 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_operations.py @@ -0,0 +1,702 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import ClientMixinABC +from ...operations._operations import ( + build_operations_list_request, + build_subscription_check_resource_name_request, + build_subscriptions_check_zone_peers_request, + build_subscriptions_get_request, + build_subscriptions_list_locations_request, + build_subscriptions_list_request, + build_tenants_list_request, +) +from .._configuration import SubscriptionClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.subscriptions.aio.SubscriptionClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Resources REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class SubscriptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.subscriptions.aio.SubscriptionClient`'s + :attr:`subscriptions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_locations( + self, subscription_id: str, include_extended_locations: Optional[bool] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.Location"]: + """Gets all available geo-locations. + + This operation provides all the locations that are available for resource providers; however, + each resource provider may support a subset of this list. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param include_extended_locations: Whether to include extended locations. Default value is + None. + :type include_extended_locations: bool + :return: An iterator like instance of either Location or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.Location] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscriptions_list_locations_request( + subscription_id=subscription_id, + include_extended_locations=include_extended_locations, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("LocationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: + """Gets details about a specified subscription. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :return: Subscription or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.Subscription + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + _request = build_subscriptions_get_request( + subscription_id=subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Subscription", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Subscription"]: + """Gets all subscriptions for a tenant. + + :return: An iterator like instance of either Subscription or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.Subscription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscriptions_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def check_zone_peers( + self, + subscription_id: str, + parameters: _models.CheckZonePeersRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckZonePeersResult: + """Compares a subscriptions logical zone mapping. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param parameters: Parameters for checking zone peers. Required. + :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckZonePeersResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_zone_peers( + self, subscription_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckZonePeersResult: + """Compares a subscriptions logical zone mapping. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param parameters: Parameters for checking zone peers. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckZonePeersResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_zone_peers( + self, subscription_id: str, parameters: Union[_models.CheckZonePeersRequest, IO[bytes]], **kwargs: Any + ) -> _models.CheckZonePeersResult: + """Compares a subscriptions logical zone mapping. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param parameters: Parameters for checking zone peers. Is either a CheckZonePeersRequest type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest or IO[bytes] + :return: CheckZonePeersResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckZonePeersResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckZonePeersRequest") + + _request = build_subscriptions_check_zone_peers_request( + subscription_id=subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponseAutoGenerated, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckZonePeersResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class TenantsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.subscriptions.aio.SubscriptionClient`'s + :attr:`tenants` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.TenantIdDescription"]: + """Gets the tenants for your account. + + :return: An iterator like instance of either TenantIdDescription or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TenantListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_tenants_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("TenantListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class _SubscriptionClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SubscriptionClientConfiguration] +): + + @overload + async def check_resource_name( + self, + resource_name_definition: Optional[_models.ResourceName] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckResourceNameResult: + """Checks resource name validity. + + A resource name is valid if it is not a reserved word, does not contains a reserved word and + does not start with a reserved word. + + :param resource_name_definition: Resource object with values for resource name and resource + type. Default value is None. + :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckResourceNameResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_resource_name( + self, + resource_name_definition: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckResourceNameResult: + """Checks resource name validity. + + A resource name is valid if it is not a reserved word, does not contains a reserved word and + does not start with a reserved word. + + :param resource_name_definition: Resource object with values for resource name and resource + type. Default value is None. + :type resource_name_definition: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckResourceNameResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_resource_name( + self, resource_name_definition: Optional[Union[_models.ResourceName, IO[bytes]]] = None, **kwargs: Any + ) -> _models.CheckResourceNameResult: + """Checks resource name validity. + + A resource name is valid if it is not a reserved word, does not contains a reserved word and + does not start with a reserved word. + + :param resource_name_definition: Resource object with values for resource name and resource + type. Is either a ResourceName type or a IO[bytes] type. Default value is None. + :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName or + IO[bytes] + :return: CheckResourceNameResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if resource_name_definition else None + cls: ClsType[_models.CheckResourceNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if resource_name_definition else None + _json = None + _content = None + if isinstance(resource_name_definition, (IOBase, bytes)): + _content = resource_name_definition + else: + if resource_name_definition is not None: + _json = self._serialize.body(resource_name_definition, "ResourceName") + else: + _json = None + + _request = build_subscription_check_resource_name_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckResourceNameResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/__init__.py new file mode 100644 index 000000000000..58d161b82e76 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/__init__.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AvailabilityZoneMappings, + AvailabilityZonePeers, + CheckResourceNameResult, + CheckZonePeersRequest, + CheckZonePeersResult, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + ErrorResponseAutoGenerated, + Location, + LocationListResult, + LocationMetadata, + ManagedByTenant, + Operation, + OperationAutoGenerated, + OperationDisplay, + OperationDisplayAutoGenerated, + OperationListResult, + OperationListResultAutoGenerated, + PairedRegion, + Peers, + ResourceName, + Subscription, + SubscriptionListResult, + SubscriptionPolicies, + TenantIdDescription, + TenantListResult, +) + +from ._subscription_client_enums import ( # type: ignore + ActionType, + LocationType, + Origin, + RegionCategory, + RegionType, + ResourceNameStatus, + SpendingLimit, + SubscriptionState, + TenantCategory, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AvailabilityZoneMappings", + "AvailabilityZonePeers", + "CheckResourceNameResult", + "CheckZonePeersRequest", + "CheckZonePeersResult", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "ErrorResponseAutoGenerated", + "Location", + "LocationListResult", + "LocationMetadata", + "ManagedByTenant", + "Operation", + "OperationAutoGenerated", + "OperationDisplay", + "OperationDisplayAutoGenerated", + "OperationListResult", + "OperationListResultAutoGenerated", + "PairedRegion", + "Peers", + "ResourceName", + "Subscription", + "SubscriptionListResult", + "SubscriptionPolicies", + "TenantIdDescription", + "TenantListResult", + "ActionType", + "LocationType", + "Origin", + "RegionCategory", + "RegionType", + "ResourceNameStatus", + "SpendingLimit", + "SubscriptionState", + "TenantCategory", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_models_py3.py new file mode 100644 index 000000000000..15679dba0bee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_models_py3.py @@ -0,0 +1,1112 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class AvailabilityZoneMappings(_serialization.Model): + """Availability zone mappings for the region. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar logical_zone: The logical zone id for the availability zone. + :vartype logical_zone: str + :ivar physical_zone: The fully qualified physical zone id of availability zone to which logical + zone id is mapped to. + :vartype physical_zone: str + """ + + _validation = { + "logical_zone": {"readonly": True}, + "physical_zone": {"readonly": True}, + } + + _attribute_map = { + "logical_zone": {"key": "logicalZone", "type": "str"}, + "physical_zone": {"key": "physicalZone", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.logical_zone: Optional[str] = None + self.physical_zone: Optional[str] = None + + +class AvailabilityZonePeers(_serialization.Model): + """List of availability zones shared by the subscriptions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar availability_zone: The availabilityZone. + :vartype availability_zone: str + :ivar peers: Details of shared availability zone. + :vartype peers: list[~azure.mgmt.resource.subscriptions.models.Peers] + """ + + _validation = { + "availability_zone": {"readonly": True}, + } + + _attribute_map = { + "availability_zone": {"key": "availabilityZone", "type": "str"}, + "peers": {"key": "peers", "type": "[Peers]"}, + } + + def __init__(self, *, peers: Optional[list["_models.Peers"]] = None, **kwargs: Any) -> None: + """ + :keyword peers: Details of shared availability zone. + :paramtype peers: list[~azure.mgmt.resource.subscriptions.models.Peers] + """ + super().__init__(**kwargs) + self.availability_zone: Optional[str] = None + self.peers = peers + + +class CheckResourceNameResult(_serialization.Model): + """Resource Name valid if not a reserved word, does not contain a reserved word and does not start + with a reserved word. + + :ivar name: Name of Resource. + :vartype name: str + :ivar type: Type of Resource. + :vartype type: str + :ivar status: Is the resource name Allowed or Reserved. Known values are: "Allowed" and + "Reserved". + :vartype status: str or ~azure.mgmt.resource.subscriptions.models.ResourceNameStatus + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + type: Optional[str] = None, + status: Optional[Union[str, "_models.ResourceNameStatus"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of Resource. + :paramtype name: str + :keyword type: Type of Resource. + :paramtype type: str + :keyword status: Is the resource name Allowed or Reserved. Known values are: "Allowed" and + "Reserved". + :paramtype status: str or ~azure.mgmt.resource.subscriptions.models.ResourceNameStatus + """ + super().__init__(**kwargs) + self.name = name + self.type = type + self.status = status + + +class CheckZonePeersRequest(_serialization.Model): + """Check zone peers request parameters. + + :ivar location: The Microsoft location. + :vartype location: str + :ivar subscription_ids: The peer Microsoft Azure subscription ID. + :vartype subscription_ids: list[str] + """ + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "subscription_ids": {"key": "subscriptionIds", "type": "[str]"}, + } + + def __init__( + self, *, location: Optional[str] = None, subscription_ids: Optional[list[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword location: The Microsoft location. + :paramtype location: str + :keyword subscription_ids: The peer Microsoft Azure subscription ID. + :paramtype subscription_ids: list[str] + """ + super().__init__(**kwargs) + self.location = location + self.subscription_ids = subscription_ids + + +class CheckZonePeersResult(_serialization.Model): + """Result of the Check zone peers operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar subscription_id: The subscription ID. + :vartype subscription_id: str + :ivar location: the location of the subscription. + :vartype location: str + :ivar availability_zone_peers: The Availability Zones shared by the subscriptions. + :vartype availability_zone_peers: + list[~azure.mgmt.resource.subscriptions.models.AvailabilityZonePeers] + """ + + _validation = { + "subscription_id": {"readonly": True}, + } + + _attribute_map = { + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "availability_zone_peers": {"key": "availabilityZonePeers", "type": "[AvailabilityZonePeers]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + availability_zone_peers: Optional[list["_models.AvailabilityZonePeers"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: the location of the subscription. + :paramtype location: str + :keyword availability_zone_peers: The Availability Zones shared by the subscriptions. + :paramtype availability_zone_peers: + list[~azure.mgmt.resource.subscriptions.models.AvailabilityZonePeers] + """ + super().__init__(**kwargs) + self.subscription_id: Optional[str] = None + self.location = location + self.availability_zone_peers = availability_zone_peers + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.subscriptions.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.subscriptions.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorDetail"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.subscriptions.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.subscriptions.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorResponse"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class ErrorResponseAutoGenerated(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.resource.subscriptions.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.resource.subscriptions.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class Location(_serialization.Model): + """Location information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The fully qualified ID of the location. For example, + /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. + :vartype id: str + :ivar subscription_id: The subscription ID. + :vartype subscription_id: str + :ivar name: The location name. + :vartype name: str + :ivar type: The location type. Known values are: "Region" and "EdgeZone". + :vartype type: str or ~azure.mgmt.resource.subscriptions.models.LocationType + :ivar display_name: The display name of the location. + :vartype display_name: str + :ivar regional_display_name: The display name of the location and its region. + :vartype regional_display_name: str + :ivar metadata: Metadata of the location, such as lat/long, paired region, and others. + :vartype metadata: ~azure.mgmt.resource.subscriptions.models.LocationMetadata + :ivar availability_zone_mappings: The availability zone mappings for this region. + :vartype availability_zone_mappings: + list[~azure.mgmt.resource.subscriptions.models.AvailabilityZoneMappings] + """ + + _validation = { + "id": {"readonly": True}, + "subscription_id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "display_name": {"readonly": True}, + "regional_display_name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "regional_display_name": {"key": "regionalDisplayName", "type": "str"}, + "metadata": {"key": "metadata", "type": "LocationMetadata"}, + "availability_zone_mappings": {"key": "availabilityZoneMappings", "type": "[AvailabilityZoneMappings]"}, + } + + def __init__( + self, + *, + metadata: Optional["_models.LocationMetadata"] = None, + availability_zone_mappings: Optional[list["_models.AvailabilityZoneMappings"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword metadata: Metadata of the location, such as lat/long, paired region, and others. + :paramtype metadata: ~azure.mgmt.resource.subscriptions.models.LocationMetadata + :keyword availability_zone_mappings: The availability zone mappings for this region. + :paramtype availability_zone_mappings: + list[~azure.mgmt.resource.subscriptions.models.AvailabilityZoneMappings] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.subscription_id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[Union[str, "_models.LocationType"]] = None + self.display_name: Optional[str] = None + self.regional_display_name: Optional[str] = None + self.metadata = metadata + self.availability_zone_mappings = availability_zone_mappings + + +class LocationListResult(_serialization.Model): + """Location list operation response. + + :ivar value: An array of locations. + :vartype value: list[~azure.mgmt.resource.subscriptions.models.Location] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Location]"}, + } + + def __init__(self, *, value: Optional[list["_models.Location"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of locations. + :paramtype value: list[~azure.mgmt.resource.subscriptions.models.Location] + """ + super().__init__(**kwargs) + self.value = value + + +class LocationMetadata(_serialization.Model): + """Location metadata information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar region_type: The type of the region. Known values are: "Physical" and "Logical". + :vartype region_type: str or ~azure.mgmt.resource.subscriptions.models.RegionType + :ivar region_category: The category of the region. Known values are: "Recommended", "Extended", + and "Other". + :vartype region_category: str or ~azure.mgmt.resource.subscriptions.models.RegionCategory + :ivar geography: The geography of the location. + :vartype geography: str + :ivar geography_group: The geography group of the location. + :vartype geography_group: str + :ivar longitude: The longitude of the location. + :vartype longitude: str + :ivar latitude: The latitude of the location. + :vartype latitude: str + :ivar physical_location: The physical location of the Azure location. + :vartype physical_location: str + :ivar paired_region: The regions paired to this region. + :vartype paired_region: list[~azure.mgmt.resource.subscriptions.models.PairedRegion] + :ivar home_location: The home location of an edge zone. + :vartype home_location: str + """ + + _validation = { + "region_type": {"readonly": True}, + "region_category": {"readonly": True}, + "geography": {"readonly": True}, + "geography_group": {"readonly": True}, + "longitude": {"readonly": True}, + "latitude": {"readonly": True}, + "physical_location": {"readonly": True}, + "home_location": {"readonly": True}, + } + + _attribute_map = { + "region_type": {"key": "regionType", "type": "str"}, + "region_category": {"key": "regionCategory", "type": "str"}, + "geography": {"key": "geography", "type": "str"}, + "geography_group": {"key": "geographyGroup", "type": "str"}, + "longitude": {"key": "longitude", "type": "str"}, + "latitude": {"key": "latitude", "type": "str"}, + "physical_location": {"key": "physicalLocation", "type": "str"}, + "paired_region": {"key": "pairedRegion", "type": "[PairedRegion]"}, + "home_location": {"key": "homeLocation", "type": "str"}, + } + + def __init__(self, *, paired_region: Optional[list["_models.PairedRegion"]] = None, **kwargs: Any) -> None: + """ + :keyword paired_region: The regions paired to this region. + :paramtype paired_region: list[~azure.mgmt.resource.subscriptions.models.PairedRegion] + """ + super().__init__(**kwargs) + self.region_type: Optional[Union[str, "_models.RegionType"]] = None + self.region_category: Optional[Union[str, "_models.RegionCategory"]] = None + self.geography: Optional[str] = None + self.geography_group: Optional[str] = None + self.longitude: Optional[str] = None + self.latitude: Optional[str] = None + self.physical_location: Optional[str] = None + self.paired_region = paired_region + self.home_location: Optional[str] = None + + +class ManagedByTenant(_serialization.Model): + """Information about a tenant managing the subscription. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar tenant_id: The tenant ID of the managing tenant. This is a GUID. + :vartype tenant_id: str + """ + + _validation = { + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "tenant_id": {"key": "tenantId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.tenant_id: Optional[str] = None + + +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.resource.subscriptions.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.resource.subscriptions.models.ActionType + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name: Optional[str] = None + self.is_data_action: Optional[bool] = None + self.display = display + self.origin: Optional[Union[str, "_models.Origin"]] = None + self.action_type: Optional[Union[str, "_models.ActionType"]] = None + + +class OperationAutoGenerated(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplayAutoGenerated + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.resource.subscriptions.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.resource.subscriptions.models.ActionType + """ + + _validation = { + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplayAutoGenerated"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["_models.OperationDisplayAutoGenerated"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplayAutoGenerated + """ + super().__init__(**kwargs) + self.name = name + self.is_data_action: Optional[bool] = None + self.display = display + self.origin: Optional[Union[str, "_models.Origin"]] = None + self.action_type: Optional[Union[str, "_models.ActionType"]] = None + + +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". + :vartype resource: str + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". + :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.provider: Optional[str] = None + self.resource: Optional[str] = None + self.operation: Optional[str] = None + self.description: Optional[str] = None + + +class OperationDisplayAutoGenerated(_serialization.Model): + """Localized display information for this particular operation. + + :ivar provider: Service provider: Microsoft.Resources. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + :ivar description: Description of the operation. + :vartype description: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Resources. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + :keyword description: Description of the operation. + :paramtype description: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class OperationListResult(_serialization.Model): + """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link + to get the next set of results. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of operations supported by the resource provider. + :vartype value: list[~azure.mgmt.resource.subscriptions.models.Operation] + :ivar next_link: URL to get the next set of operation list results (if there are any). + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value: Optional[list["_models.Operation"]] = None + self.next_link: Optional[str] = None + + +class OperationListResultAutoGenerated(_serialization.Model): + """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link + to get the next set of results. + + :ivar value: List of operations supported by the resource provider. + :vartype value: list[~azure.mgmt.resource.subscriptions.models.OperationAutoGenerated] + :ivar next_link: URL to get the next set of operation list results (if there are any). + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[OperationAutoGenerated]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.OperationAutoGenerated"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: List of operations supported by the resource provider. + :paramtype value: list[~azure.mgmt.resource.subscriptions.models.OperationAutoGenerated] + :keyword next_link: URL to get the next set of operation list results (if there are any). + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PairedRegion(_serialization.Model): + """Information regarding paired region. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the paired region. + :vartype name: str + :ivar id: The fully qualified ID of the location. For example, + /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. + :vartype id: str + :ivar subscription_id: The subscription ID. + :vartype subscription_id: str + """ + + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "subscription_id": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.name: Optional[str] = None + self.id: Optional[str] = None + self.subscription_id: Optional[str] = None + + +class Peers(_serialization.Model): + """Information about shared availability zone. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar subscription_id: The subscription ID. + :vartype subscription_id: str + :ivar availability_zone: The availabilityZone. + :vartype availability_zone: str + """ + + _validation = { + "subscription_id": {"readonly": True}, + "availability_zone": {"readonly": True}, + } + + _attribute_map = { + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "availability_zone": {"key": "availabilityZone", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.subscription_id: Optional[str] = None + self.availability_zone: Optional[str] = None + + +class ResourceName(_serialization.Model): + """Name and Type of the Resource. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the resource. Required. + :vartype name: str + :ivar type: The type of the resource. Required. + :vartype type: str + """ + + _validation = { + "name": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: str, type: str, **kwargs: Any) -> None: + """ + :keyword name: Name of the resource. Required. + :paramtype name: str + :keyword type: The type of the resource. Required. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class Subscription(_serialization.Model): + """Subscription information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The fully qualified ID for the subscription. For example, + /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74. + :vartype id: str + :ivar subscription_id: The subscription ID. + :vartype subscription_id: str + :ivar display_name: The subscription display name. + :vartype display_name: str + :ivar tenant_id: The subscription tenant ID. + :vartype tenant_id: str + :ivar state: The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, + and Deleted. Known values are: "Enabled", "Warned", "PastDue", "Disabled", and "Deleted". + :vartype state: str or ~azure.mgmt.resource.subscriptions.models.SubscriptionState + :ivar subscription_policies: The subscription policies. + :vartype subscription_policies: ~azure.mgmt.resource.subscriptions.models.SubscriptionPolicies + :ivar authorization_source: The authorization source of the request. Valid values are one or + more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, + RoleBased'. + :vartype authorization_source: str + :ivar managed_by_tenants: An array containing the tenants managing the subscription. + :vartype managed_by_tenants: list[~azure.mgmt.resource.subscriptions.models.ManagedByTenant] + :ivar tags: The tags attached to the subscription. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "subscription_id": {"readonly": True}, + "display_name": {"readonly": True}, + "tenant_id": {"readonly": True}, + "state": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "state": {"key": "state", "type": "str"}, + "subscription_policies": {"key": "subscriptionPolicies", "type": "SubscriptionPolicies"}, + "authorization_source": {"key": "authorizationSource", "type": "str"}, + "managed_by_tenants": {"key": "managedByTenants", "type": "[ManagedByTenant]"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__( + self, + *, + subscription_policies: Optional["_models.SubscriptionPolicies"] = None, + authorization_source: Optional[str] = None, + managed_by_tenants: Optional[list["_models.ManagedByTenant"]] = None, + tags: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword subscription_policies: The subscription policies. + :paramtype subscription_policies: + ~azure.mgmt.resource.subscriptions.models.SubscriptionPolicies + :keyword authorization_source: The authorization source of the request. Valid values are one or + more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, + RoleBased'. + :paramtype authorization_source: str + :keyword managed_by_tenants: An array containing the tenants managing the subscription. + :paramtype managed_by_tenants: list[~azure.mgmt.resource.subscriptions.models.ManagedByTenant] + :keyword tags: The tags attached to the subscription. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.subscription_id: Optional[str] = None + self.display_name: Optional[str] = None + self.tenant_id: Optional[str] = None + self.state: Optional[Union[str, "_models.SubscriptionState"]] = None + self.subscription_policies = subscription_policies + self.authorization_source = authorization_source + self.managed_by_tenants = managed_by_tenants + self.tags = tags + + +class SubscriptionListResult(_serialization.Model): + """Subscription list operation response. + + All required parameters must be populated in order to send to server. + + :ivar value: An array of subscriptions. + :vartype value: list[~azure.mgmt.resource.subscriptions.models.Subscription] + :ivar next_link: The URL to get the next set of results. Required. + :vartype next_link: str + """ + + _validation = { + "next_link": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Subscription]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, next_link: str, value: Optional[list["_models.Subscription"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of subscriptions. + :paramtype value: list[~azure.mgmt.resource.subscriptions.models.Subscription] + :keyword next_link: The URL to get the next set of results. Required. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class SubscriptionPolicies(_serialization.Model): + """Subscription policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar location_placement_id: The subscription location placement ID. The ID indicates which + regions are visible for a subscription. For example, a subscription with a location placement + Id of Public_2014-09-01 has access to Azure public regions. + :vartype location_placement_id: str + :ivar quota_id: The subscription quota ID. + :vartype quota_id: str + :ivar spending_limit: The subscription spending limit. Known values are: "On", "Off", and + "CurrentPeriodOff". + :vartype spending_limit: str or ~azure.mgmt.resource.subscriptions.models.SpendingLimit + """ + + _validation = { + "location_placement_id": {"readonly": True}, + "quota_id": {"readonly": True}, + "spending_limit": {"readonly": True}, + } + + _attribute_map = { + "location_placement_id": {"key": "locationPlacementId", "type": "str"}, + "quota_id": {"key": "quotaId", "type": "str"}, + "spending_limit": {"key": "spendingLimit", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.location_placement_id: Optional[str] = None + self.quota_id: Optional[str] = None + self.spending_limit: Optional[Union[str, "_models.SpendingLimit"]] = None + + +class TenantIdDescription(_serialization.Model): + """Tenant Id information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The fully qualified ID of the tenant. For example, + /tenants/8d65815f-a5b6-402f-9298-045155da7d74. + :vartype id: str + :ivar tenant_id: The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. + :vartype tenant_id: str + :ivar tenant_category: Category of the tenant. Known values are: "Home", "ProjectedBy", and + "ManagedBy". + :vartype tenant_category: str or ~azure.mgmt.resource.subscriptions.models.TenantCategory + :ivar country: Country/region name of the address for the tenant. + :vartype country: str + :ivar country_code: Country/region abbreviation for the tenant. + :vartype country_code: str + :ivar display_name: The display name of the tenant. + :vartype display_name: str + :ivar domains: The list of domains for the tenant. + :vartype domains: list[str] + :ivar default_domain: The default domain for the tenant. + :vartype default_domain: str + :ivar tenant_type: The tenant type. Only available for 'Home' tenant category. + :vartype tenant_type: str + :ivar tenant_branding_logo_url: The tenant's branding logo URL. Only available for 'Home' + tenant category. + :vartype tenant_branding_logo_url: str + """ + + _validation = { + "id": {"readonly": True}, + "tenant_id": {"readonly": True}, + "tenant_category": {"readonly": True}, + "country": {"readonly": True}, + "country_code": {"readonly": True}, + "display_name": {"readonly": True}, + "domains": {"readonly": True}, + "default_domain": {"readonly": True}, + "tenant_type": {"readonly": True}, + "tenant_branding_logo_url": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "tenant_category": {"key": "tenantCategory", "type": "str"}, + "country": {"key": "country", "type": "str"}, + "country_code": {"key": "countryCode", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "domains": {"key": "domains", "type": "[str]"}, + "default_domain": {"key": "defaultDomain", "type": "str"}, + "tenant_type": {"key": "tenantType", "type": "str"}, + "tenant_branding_logo_url": {"key": "tenantBrandingLogoUrl", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.tenant_id: Optional[str] = None + self.tenant_category: Optional[Union[str, "_models.TenantCategory"]] = None + self.country: Optional[str] = None + self.country_code: Optional[str] = None + self.display_name: Optional[str] = None + self.domains: Optional[list[str]] = None + self.default_domain: Optional[str] = None + self.tenant_type: Optional[str] = None + self.tenant_branding_logo_url: Optional[str] = None + + +class TenantListResult(_serialization.Model): + """Tenant Ids information. + + All required parameters must be populated in order to send to server. + + :ivar value: An array of tenants. + :vartype value: list[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] + :ivar next_link: The URL to use for getting the next set of results. Required. + :vartype next_link: str + """ + + _validation = { + "next_link": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[TenantIdDescription]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, next_link: str, value: Optional[list["_models.TenantIdDescription"]] = None, **kwargs: Any + ) -> None: + """ + :keyword value: An array of tenants. + :paramtype value: list[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] + :keyword next_link: The URL to use for getting the next set of results. Required. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_patch.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py new file mode 100644 index 000000000000..610e41a85c9f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py @@ -0,0 +1,81 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class LocationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The location type.""" + + REGION = "Region" + EDGE_ZONE = "EdgeZone" + + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". + """ + + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class RegionCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The category of the region.""" + + RECOMMENDED = "Recommended" + EXTENDED = "Extended" + OTHER = "Other" + + +class RegionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the region.""" + + PHYSICAL = "Physical" + LOGICAL = "Logical" + + +class ResourceNameStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Is the resource name Allowed or Reserved.""" + + ALLOWED = "Allowed" + RESERVED = "Reserved" + + +class SpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The subscription spending limit.""" + + ON = "On" + OFF = "Off" + CURRENT_PERIOD_OFF = "CurrentPeriodOff" + + +class SubscriptionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted.""" + + ENABLED = "Enabled" + WARNED = "Warned" + PAST_DUE = "PastDue" + DISABLED = "Disabled" + DELETED = "Deleted" + + +class TenantCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Category of the tenant.""" + + HOME = "Home" + PROJECTED_BY = "ProjectedBy" + MANAGED_BY = "ManagedBy" diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/__init__.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/__init__.py new file mode 100644 index 000000000000..d43f10f233ab --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/__init__.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import SubscriptionsOperations # type: ignore +from ._operations import TenantsOperations # type: ignore +from ._operations import _SubscriptionClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "SubscriptionsOperations", + "TenantsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_operations.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_operations.py new file mode 100644 index 000000000000..b5675187f526 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_operations.py @@ -0,0 +1,853 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import SubscriptionClientConfiguration +from .._utils.serialization import Deserializer, Serializer +from .._utils.utils import ClientMixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_operations_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscriptions_list_locations_request( # pylint: disable=name-too-long + subscription_id: str, *, include_extended_locations: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/locations") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if include_extended_locations is not None: + _params["includeExtendedLocations"] = _SERIALIZER.query( + "include_extended_locations", include_extended_locations, "bool" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscriptions_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscriptions_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscriptions_check_zone_peers_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/checkZonePeers/") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_tenants_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/tenants") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_check_resource_name_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/checkResourceName") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.subscriptions.SubscriptionClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Resources REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class SubscriptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.subscriptions.SubscriptionClient`'s + :attr:`subscriptions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_locations( + self, subscription_id: str, include_extended_locations: Optional[bool] = None, **kwargs: Any + ) -> ItemPaged["_models.Location"]: + """Gets all available geo-locations. + + This operation provides all the locations that are available for resource providers; however, + each resource provider may support a subset of this list. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param include_extended_locations: Whether to include extended locations. Default value is + None. + :type include_extended_locations: bool + :return: An iterator like instance of either Location or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.Location] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscriptions_list_locations_request( + subscription_id=subscription_id, + include_extended_locations=include_extended_locations, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("LocationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: + """Gets details about a specified subscription. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :return: Subscription or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.Subscription + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + _request = build_subscriptions_get_request( + subscription_id=subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Subscription", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Subscription"]: + """Gets all subscriptions for a tenant. + + :return: An iterator like instance of either Subscription or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.Subscription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_subscriptions_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def check_zone_peers( + self, + subscription_id: str, + parameters: _models.CheckZonePeersRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckZonePeersResult: + """Compares a subscriptions logical zone mapping. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param parameters: Parameters for checking zone peers. Required. + :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckZonePeersResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_zone_peers( + self, subscription_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckZonePeersResult: + """Compares a subscriptions logical zone mapping. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param parameters: Parameters for checking zone peers. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckZonePeersResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_zone_peers( + self, subscription_id: str, parameters: Union[_models.CheckZonePeersRequest, IO[bytes]], **kwargs: Any + ) -> _models.CheckZonePeersResult: + """Compares a subscriptions logical zone mapping. + + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param parameters: Parameters for checking zone peers. Is either a CheckZonePeersRequest type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest or IO[bytes] + :return: CheckZonePeersResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckZonePeersResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckZonePeersRequest") + + _request = build_subscriptions_check_zone_peers_request( + subscription_id=subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponseAutoGenerated, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckZonePeersResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class TenantsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.subscriptions.SubscriptionClient`'s + :attr:`tenants` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.TenantIdDescription"]: + """Gets the tenants for your account. + + :return: An iterator like instance of either TenantIdDescription or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TenantListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_tenants_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("TenantListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class _SubscriptionClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SubscriptionClientConfiguration] +): + + @overload + def check_resource_name( + self, + resource_name_definition: Optional[_models.ResourceName] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckResourceNameResult: + """Checks resource name validity. + + A resource name is valid if it is not a reserved word, does not contains a reserved word and + does not start with a reserved word. + + :param resource_name_definition: Resource object with values for resource name and resource + type. Default value is None. + :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckResourceNameResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_resource_name( + self, + resource_name_definition: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckResourceNameResult: + """Checks resource name validity. + + A resource name is valid if it is not a reserved word, does not contains a reserved word and + does not start with a reserved word. + + :param resource_name_definition: Resource object with values for resource name and resource + type. Default value is None. + :type resource_name_definition: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckResourceNameResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_resource_name( + self, resource_name_definition: Optional[Union[_models.ResourceName, IO[bytes]]] = None, **kwargs: Any + ) -> _models.CheckResourceNameResult: + """Checks resource name validity. + + A resource name is valid if it is not a reserved word, does not contains a reserved word and + does not start with a reserved word. + + :param resource_name_definition: Resource object with values for resource name and resource + type. Is either a ResourceName type or a IO[bytes] type. Default value is None. + :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName or + IO[bytes] + :return: CheckResourceNameResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if resource_name_definition else None + cls: ClsType[_models.CheckResourceNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if resource_name_definition else None + _json = None + _content = None + if isinstance(resource_name_definition, (IOBase, bytes)): + _content = resource_name_definition + else: + if resource_name_definition is not None: + _json = self._serialize.body(resource_name_definition, "ResourceName") + else: + _json = None + + _request = build_subscription_check_resource_name_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckResourceNameResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_patch.py b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/py.typed b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/azure/mgmt/resource/subscriptions/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-subscriptions/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/check_resource_name.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/check_resource_name.py new file mode 100644 index 000000000000..9f72b2a4e1ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/check_resource_name.py @@ -0,0 +1,39 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python check_resource_name.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.check_resource_name() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/CheckResourceName.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations.py new file mode 100644 index 000000000000..30c85433136e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python get_locations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.subscriptions.list_locations( + subscription_id="a1ffc958-d2c7-493e-9f1e-125a0477f536", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/GetLocations.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations_with_extended_locations.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations_with_extended_locations.py new file mode 100644 index 000000000000..d3b001ae1e38 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_locations_with_extended_locations.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python get_locations_with_extended_locations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.subscriptions.list_locations( + subscription_id="a1ffc958-d2c7-493e-9f1e-125a0477f536", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/GetLocationsWithExtendedLocations.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscription.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscription.py new file mode 100644 index 000000000000..bb8cc294511c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscription.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python get_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.subscriptions.get( + subscription_id="291bba3f-e0a5-47bc-a099-3bdcb2a50a05", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/GetSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscriptions.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscriptions.py new file mode 100644 index 000000000000..552b61491eb7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_subscriptions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python get_subscriptions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.subscriptions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/GetSubscriptions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_tenants.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_tenants.py new file mode 100644 index 000000000000..769cee8be243 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/get_tenants.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python get_tenants.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.tenants.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/GetTenants.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/post_check_zone_peers.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/post_check_zone_peers.py new file mode 100644 index 000000000000..987e3a1079a9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_samples/post_check_zone_peers.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.subscriptions import SubscriptionClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-subscriptions +# USAGE + python post_check_zone_peers.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = SubscriptionClient( + credential=DefaultAzureCredential(), + ) + + response = client.subscriptions.check_zone_peers( + subscription_id="8d65815f-a5b6-402f-9298-045155da7d74", + parameters={"location": "eastus", "subscriptionIds": ["subscriptions/11111111-1111-1111-1111-111111111111"]}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/subscriptions/stable/2022-12-01/examples/PostCheckZonePeers.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/conftest.py new file mode 100644 index 000000000000..3a655a68c15d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + subscription_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + subscription_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + subscription_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + subscription_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription.py new file mode 100644 index 000000000000..44687506daed --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscription(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_check_resource_name(self, resource_group): + response = self.client.check_resource_name( + api_version="2022-12-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_async.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_async.py new file mode 100644 index 000000000000..df24a5a1b8e6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_check_resource_name(self, resource_group): + response = await self.client.check_resource_name( + api_version="2022-12-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations.py new file mode 100644 index 000000000000..854df62b3cea --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2022-12-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations_async.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations_async.py new file mode 100644 index 000000000000..a4df00309613 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2022-12-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations.py new file mode 100644 index 000000000000..b02b4addda74 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionSubscriptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_list_locations(self, resource_group): + response = self.client.subscriptions.list_locations( + subscription_id="str", + api_version="2022-12-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_get(self, resource_group): + response = self.client.subscriptions.get( + subscription_id="str", + api_version="2022-12-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_list(self, resource_group): + response = self.client.subscriptions.list( + api_version="2022-12-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_check_zone_peers(self, resource_group): + response = self.client.subscriptions.check_zone_peers( + subscription_id="str", + parameters={"location": "str", "subscriptionIds": ["str"]}, + api_version="2022-12-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations_async.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations_async.py new file mode 100644 index 000000000000..a615ee0a8f1a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_subscriptions_operations_async.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionSubscriptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_list_locations(self, resource_group): + response = self.client.subscriptions.list_locations( + subscription_id="str", + api_version="2022-12-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_get(self, resource_group): + response = await self.client.subscriptions.get( + subscription_id="str", + api_version="2022-12-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_list(self, resource_group): + response = self.client.subscriptions.list( + api_version="2022-12-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_check_zone_peers(self, resource_group): + response = await self.client.subscriptions.check_zone_peers( + subscription_id="str", + parameters={"location": "str", "subscriptionIds": ["str"]}, + api_version="2022-12-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations.py new file mode 100644 index 000000000000..6a9cf04ca45e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionTenantsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_tenants_list(self, resource_group): + response = self.client.tenants.list( + api_version="2022-12-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations_async.py b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations_async.py new file mode 100644 index 000000000000..cd39b2d42d63 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/generated_tests/test_subscription_tenants_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSubscriptionTenantsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_tenants_list(self, resource_group): + response = self.client.tenants.list( + api_version="2022-12-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/pyproject.toml b/sdk/resources/azure-mgmt-resource-subscriptions/pyproject.toml new file mode 100644 index 000000000000..d372337860b2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/pyproject.toml @@ -0,0 +1,88 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-subscriptions" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Subscriptions Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.subscriptions._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-subscriptions" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Subscriptions Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +no_sub = true +title = "SubscriptionClient" diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/conftest.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/conftest.py new file mode 100644 index 000000000000..3a655a68c15d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + subscription_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + subscription_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + subscription_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + subscription_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=subscription_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_async_test.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_async_test.py new file mode 100644 index 000000000000..635216207340 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestSubscriptionOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_test.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_test.py new file mode 100644 index 000000000000..f69e08d2ceb4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestSubscriptionOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_async_test.py new file mode 100644 index 000000000000..a804097b3d79 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_async_test.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestSubscriptionSubscriptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_list_locations(self, resource_group): + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + response = self.client.subscriptions.list_locations( + subscription_id=SUBSCRIPTION_ID, + ) + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_get(self, resource_group): + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + response = await self.client.subscriptions.get( + subscription_id=SUBSCRIPTION_ID, + ) + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_subscriptions_list(self, resource_group): + response = self.client.subscriptions.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_test.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_test.py new file mode 100644 index 000000000000..8bd1ba53d813 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_subscriptions_operations_test.py @@ -0,0 +1,46 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestSubscriptionSubscriptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_list_locations(self, resource_group): + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + response = self.client.subscriptions.list_locations( + subscription_id=SUBSCRIPTION_ID, + ) + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_get(self, resource_group): + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + response = self.client.subscriptions.get( + subscription_id=SUBSCRIPTION_ID, + ) + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_subscriptions_list(self, resource_group): + response = self.client.subscriptions.list() + result = [r for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_async_test.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_async_test.py new file mode 100644 index 000000000000..e72224545eec --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions.aio import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestSubscriptionTenantsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_tenants_list(self, resource_group): + response = self.client.tenants.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_test.py b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_test.py new file mode 100644 index 000000000000..a10a16cd4e33 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-subscriptions/tests/test_subscription_tenants_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.subscriptions import SubscriptionClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestSubscriptionTenantsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SubscriptionClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_tenants_list(self, resource_group): + response = self.client.tenants.list() + result = [r for r in response] + assert result From c74b66f9cebb5c04f6cd877c9f51452692c54d6c Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:27:51 -0800 Subject: [PATCH 56/84] [AutoRelease] t2-resource-policy-2026-02-05-48388(can only be merged by SDK owner) (#45029) * code and test * update --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 --- .../azure-mgmt-resource-policy/CHANGELOG.md | 7 + .../azure-mgmt-resource-policy/LICENSE | 21 + .../azure-mgmt-resource-policy/MANIFEST.in | 8 + .../azure-mgmt-resource-policy/README.md | 61 + .../azure-mgmt-resource-policy/_metadata.json | 11 + .../apiview-properties.json | 229 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../azure/mgmt/resource/policy/__init__.py | 32 + .../mgmt/resource/policy/_configuration.py | 69 + .../azure/mgmt/resource/policy/_patch.py | 21 + .../mgmt/resource/policy/_policy_client.py | 176 + .../mgmt/resource/policy/_utils/__init__.py | 6 + .../resource/policy/_utils/serialization.py | 2041 ++++ .../azure/mgmt/resource/policy/_version.py | 9 + .../mgmt/resource/policy/aio/__init__.py | 29 + .../resource/policy/aio/_configuration.py | 69 + .../azure/mgmt/resource/policy/aio/_patch.py | 21 + .../resource/policy/aio/_policy_client.py | 183 + .../policy/aio/operations/__init__.py | 41 + .../policy/aio/operations/_operations.py | 7433 +++++++++++ .../resource/policy/aio/operations/_patch.py | 21 + .../mgmt/resource/policy/models/__init__.py | 140 + .../resource/policy/models/_models_py3.py | 2333 ++++ .../mgmt/resource/policy/models/_patch.py | 21 + .../policy/models/_policy_client_enums.py | 153 + .../resource/policy/operations/__init__.py | 41 + .../resource/policy/operations/_operations.py | 10155 ++++++++++++++++ .../mgmt/resource/policy/operations/_patch.py | 21 + .../azure/mgmt/resource/policy/py.typed | 1 + .../dev_requirements.txt | 5 + .../create_or_update_policy_definition.py | 66 + ...pdate_policy_definition_advanced_params.py | 82 + ...e_policy_definition_at_management_group.py | 67 + ...ate_or_update_policy_definition_version.py | 68 + ..._definition_version_at_management_group.py | 69 + .../create_or_update_policy_exemption.py | 53 + ...olicy_exemption_with_resource_selectors.py | 60 + .../create_or_update_policy_set_definition.py | 68 + ...licy_set_definition_at_management_group.py | 62 + ...or_update_policy_set_definition_version.py | 70 + ..._definition_version_at_management_group.py | 64 + ...pdate_policy_set_definition_with_groups.py | 77 + ...inition_with_groups_at_management_group.py | 76 + .../create_or_update_variable.py | 43 + ..._or_update_variable_at_management_group.py | 44 + .../create_or_update_variable_value.py | 51 + ...date_variable_value_at_management_group.py | 52 + .../create_policy_assignment.py | 53 + .../create_policy_assignment_by_id.py | 53 + ...licy_assignment_non_compliance_messages.py | 62 + .../create_policy_assignment_with_identity.py | 55 + ...e_policy_assignment_with_identity_by_id.py | 55 + ...create_policy_assignment_with_overrides.py | 58 + ...licy_assignment_with_resource_selectors.py | 57 + ..._assignment_with_user_assigned_identity.py | 60 + ...e_policy_assignment_without_enforcement.py | 53 + .../delete_policy_assignment.py | 43 + .../delete_policy_assignment_by_id.py | 42 + .../delete_policy_definition.py | 41 + ...e_policy_definition_at_management_group.py | 42 + .../delete_policy_definition_version.py | 42 + ..._definition_version_at_management_group.py | 43 + .../delete_policy_exemption.py | 42 + .../delete_policy_set_definition.py | 41 + ...licy_set_definition_at_management_group.py | 42 + .../delete_policy_set_definition_version.py | 42 + ..._definition_version_at_management_group.py | 43 + .../generated_samples/delete_variable.py | 41 + .../delete_variable_at_management_group.py | 42 + .../delete_variable_value.py | 42 + ...lete_variable_value_at_management_group.py | 43 + .../get_built_in_policy_set_definition.py | 42 + ..._built_in_policy_set_definition_version.py | 43 + .../get_builtin_policy_definition.py | 42 + .../get_builtin_policy_definition_version.py | 43 + .../get_data_policy_manifest.py | 42 + .../get_policy_assignment.py | 43 + .../get_policy_assignment_by_id.py | 42 + .../get_policy_assignment_with_identity.py | 43 + ...t_policy_assignment_with_identity_by_id.py | 42 + .../get_policy_assignment_with_overrides.py | 43 + ...licy_assignment_with_resource_selectors.py | 43 + ..._assignment_with_user_assigned_identity.py | 43 + .../get_policy_definition.py | 42 + ...t_policy_definition_at_management_group.py | 43 + .../get_policy_definition_version.py | 43 + ..._definition_version_at_management_group.py | 44 + .../generated_samples/get_policy_exemption.py | 43 + ...olicy_exemption_with_resource_selectors.py | 43 + .../get_policy_set_definition.py | 42 + ...licy_set_definition_at_management_group.py | 43 + .../get_policy_set_definition_version.py | 43 + ..._definition_version_at_management_group.py | 44 + .../generated_samples/get_variable.py | 42 + .../get_variable_at_management_group.py | 43 + .../generated_samples/get_variable_value.py | 43 + .../get_variable_value_at_management_group.py | 44 + ...all_built_in_policy_definition_versions.py | 40 + ...built_in_policy_set_definition_versions.py | 40 + .../list_all_policy_definition_versions.py | 40 + ...definition_versions_by_management_group.py | 42 + ...list_all_policy_set_definition_versions.py | 40 + ...definition_versions_by_management_group.py | 42 + ...ist_built_in_policy_definition_versions.py | 43 + .../list_built_in_policy_definitions.py | 41 + ...built_in_policy_set_definition_versions.py | 43 + .../list_built_in_policy_set_definitions.py | 41 + .../list_data_policy_manifests.py | 41 + ..._data_policy_manifests_namespace_filter.py | 41 + .../list_policy_assignments.py | 41 + ...policy_assignments_for_management_group.py | 43 + .../list_policy_assignments_for_resource.py | 47 + ...t_policy_assignments_for_resource_group.py | 43 + .../list_policy_definition_versions.py | 43 + ...definition_versions_by_management_group.py | 44 + .../list_policy_definitions.py | 41 + ..._policy_definitions_by_management_group.py | 43 + ..._policy_exemptions_for_management_group.py | 43 + .../list_policy_exemptions_for_resource.py | 47 + ...st_policy_exemptions_for_resource_group.py | 43 + ...list_policy_exemptions_for_subscription.py | 41 + .../list_policy_set_definition_versions.py | 43 + ...definition_versions_by_management_group.py | 44 + .../list_policy_set_definitions.py | 41 + ...icy_set_definitions_by_management_group.py | 43 + ...st_variable_values_for_management_group.py | 44 + .../list_variable_values_for_subscription.py | 43 + .../list_variables_for_management_group.py | 43 + .../list_variables_for_subscription.py | 41 + .../update_policy_assignment_with_identity.py | 44 + ...e_policy_assignment_with_identity_by_id.py | 43 + ...update_policy_assignment_with_overrides.py | 54 + ...licy_assignment_with_resource_selectors.py | 53 + ..._assignment_with_user_assigned_identity.py | 52 + ...olicy_exemption_with_resource_selectors.py | 54 + .../generated_tests/conftest.py | 35 + ...policy_data_policy_manifests_operations.py | 40 + ..._data_policy_manifests_operations_async.py | 41 + ...st_policy_policy_assignments_operations.py | 256 + ...icy_policy_assignments_operations_async.py | 257 + ...y_policy_definition_versions_operations.py | 239 + ...cy_definition_versions_operations_async.py | 240 + ...st_policy_policy_definitions_operations.py | 200 + ...icy_policy_definitions_operations_async.py | 201 + ...est_policy_policy_exemptions_operations.py | 140 + ...licy_policy_exemptions_operations_async.py | 141 + ...licy_set_definition_versions_operations.py | 275 + ...et_definition_versions_operations_async.py | 276 + ...olicy_policy_set_definitions_operations.py | 236 + ...policy_set_definitions_operations_async.py | 237 + .../test_policy_variable_values_operations.py | 145 + ...policy_variable_values_operations_async.py | 146 + .../test_policy_variables_operations.py | 137 + .../test_policy_variables_operations_async.py | 138 + .../azure-mgmt-resource-policy/pyproject.toml | 87 + .../tests/conftest.py | 35 + ..._policy_manifests_operations_async_test.py | 27 + ...y_data_policy_manifests_operations_test.py | 26 + ...olicy_assignments_operations_async_test.py | 36 + ...licy_policy_assignments_operations_test.py | 35 + ...finition_versions_operations_async_test.py | 34 + ...icy_definition_versions_operations_test.py | 33 + ...olicy_definitions_operations_async_test.py | 34 + ...licy_policy_definitions_operations_test.py | 33 + ...policy_exemptions_operations_async_test.py | 36 + ...olicy_policy_exemptions_operations_test.py | 35 + ...finition_versions_operations_async_test.py | 27 + ...set_definition_versions_operations_test.py | 26 + ...y_set_definitions_operations_async_test.py | 34 + ..._policy_set_definitions_operations_test.py | 33 + ..._policy_variables_operations_async_test.py | 27 + .../test_policy_variables_operations_test.py | 26 + 174 files changed, 32342 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-policy/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-policy/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-policy/README.md create mode 100644 sdk/resources/azure-mgmt-resource-policy/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-policy/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/LICENSE b/sdk/resources/azure-mgmt-resource-policy/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/MANIFEST.in b/sdk/resources/azure-mgmt-resource-policy/MANIFEST.in new file mode 100644 index 000000000000..b0078f5508b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/policy/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-policy/README.md b/sdk/resources/azure-mgmt-resource-policy/README.md new file mode 100644 index 000000000000..cf1a9d1392b4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Policy Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-policy +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.policy import PolicyClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = PolicyClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Policy Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-policy/_metadata.json b/sdk/resources/azure-mgmt-resource-policy/_metadata.json new file mode 100644 index 000000000000..a92976f3f261 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "3805079312b2cd71f794e1a5a9b1e74e72e2986f", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Authorization/policy/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-policy-2023-04 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Authorization/policy/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/apiview-properties.json b/sdk/resources/azure-mgmt-resource-policy/apiview-properties.json new file mode 100644 index 000000000000..517a6d871ee6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/apiview-properties.json @@ -0,0 +1,229 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.policy.models.Alias": null, + "azure.mgmt.resource.policy.models.AliasPath": null, + "azure.mgmt.resource.policy.models.AliasPathMetadata": null, + "azure.mgmt.resource.policy.models.AliasPattern": null, + "azure.mgmt.resource.policy.models.DataEffect": null, + "azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition": null, + "azure.mgmt.resource.policy.models.DataPolicyManifest": null, + "azure.mgmt.resource.policy.models.DataPolicyManifestListResult": null, + "azure.mgmt.resource.policy.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.policy.models.ErrorResponse": null, + "azure.mgmt.resource.policy.models.Identity": null, + "azure.mgmt.resource.policy.models.NonComplianceMessage": null, + "azure.mgmt.resource.policy.models.Override": null, + "azure.mgmt.resource.policy.models.ParameterDefinitionsValue": null, + "azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata": null, + "azure.mgmt.resource.policy.models.ParameterValuesValue": null, + "azure.mgmt.resource.policy.models.PolicyAssignment": null, + "azure.mgmt.resource.policy.models.PolicyAssignmentListResult": null, + "azure.mgmt.resource.policy.models.PolicyAssignmentUpdate": null, + "azure.mgmt.resource.policy.models.PolicyDefinition": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionGroup": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionListResult": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionReference": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionVersion": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult": null, + "azure.mgmt.resource.policy.models.PolicyExemption": null, + "azure.mgmt.resource.policy.models.PolicyExemptionListResult": null, + "azure.mgmt.resource.policy.models.PolicyExemptionUpdate": null, + "azure.mgmt.resource.policy.models.PolicySetDefinition": null, + "azure.mgmt.resource.policy.models.PolicySetDefinitionListResult": null, + "azure.mgmt.resource.policy.models.PolicySetDefinitionVersion": null, + "azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult": null, + "azure.mgmt.resource.policy.models.PolicyVariableColumn": null, + "azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue": null, + "azure.mgmt.resource.policy.models.ResourceSelector": null, + "azure.mgmt.resource.policy.models.ResourceTypeAliases": null, + "azure.mgmt.resource.policy.models.Selector": null, + "azure.mgmt.resource.policy.models.SystemData": null, + "azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue": null, + "azure.mgmt.resource.policy.models.Variable": null, + "azure.mgmt.resource.policy.models.VariableListResult": null, + "azure.mgmt.resource.policy.models.VariableValue": null, + "azure.mgmt.resource.policy.models.VariableValueListResult": null, + "azure.mgmt.resource.policy.models.AliasPatternType": null, + "azure.mgmt.resource.policy.models.AliasPathTokenType": null, + "azure.mgmt.resource.policy.models.AliasPathAttributes": null, + "azure.mgmt.resource.policy.models.AliasType": null, + "azure.mgmt.resource.policy.models.CreatedByType": null, + "azure.mgmt.resource.policy.models.PolicyType": null, + "azure.mgmt.resource.policy.models.ParameterType": null, + "azure.mgmt.resource.policy.models.SelectorKind": null, + "azure.mgmt.resource.policy.models.OverrideKind": null, + "azure.mgmt.resource.policy.models.ResourceIdentityType": null, + "azure.mgmt.resource.policy.models.EnforcementMode": null, + "azure.mgmt.resource.policy.models.ExemptionCategory": null, + "azure.mgmt.resource.policy.models.AssignmentScopeValidation": null, + "azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations.get_by_policy_mode": null, + "azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations.get_by_policy_mode": null, + "azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.create": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.create": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.update": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.delete_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.delete_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.create_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.create_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.get_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.get_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.update_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.update_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.update": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.delete": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.get": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.list": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.delete": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.get": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.list": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.get_at_management_group": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py new file mode 100644 index 000000000000..02f33f3e073a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._policy_client import PolicyClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py new file mode 100644 index 000000000000..adb4296d0647 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class PolicyClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-policy/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py new file mode 100644 index 000000000000..6d154e35759f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py @@ -0,0 +1,176 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import PolicyClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + DataPolicyManifestsOperations, + PolicyAssignmentsOperations, + PolicyDefinitionVersionsOperations, + PolicyDefinitionsOperations, + PolicyExemptionsOperations, + PolicySetDefinitionVersionsOperations, + PolicySetDefinitionsOperations, + VariableValuesOperations, + VariablesOperations, +) + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Policy Client. + + :ivar data_policy_manifests: DataPolicyManifestsOperations operations + :vartype data_policy_manifests: + azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations + :ivar policy_definition_versions: PolicyDefinitionVersionsOperations operations + :vartype policy_definition_versions: + azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations + :ivar policy_set_definitions: PolicySetDefinitionsOperations operations + :vartype policy_set_definitions: + azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations + :ivar policy_set_definition_versions: PolicySetDefinitionVersionsOperations operations + :vartype policy_set_definition_versions: + azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations + :ivar policy_exemptions: PolicyExemptionsOperations operations + :vartype policy_exemptions: azure.mgmt.resource.policy.operations.PolicyExemptionsOperations + :ivar variables: VariablesOperations operations + :vartype variables: azure.mgmt.resource.policy.operations.VariablesOperations + :ivar variable_values: VariableValuesOperations operations + :vartype variable_values: azure.mgmt.resource.policy.operations.VariableValuesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = PolicyClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.data_policy_manifests = DataPolicyManifestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definition_versions = PolicyDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definitions = PolicySetDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definition_versions = PolicySetDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_exemptions = PolicyExemptionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.variables = VariablesOperations(self._client, self._config, self._serialize, self._deserialize) + self.variable_values = VariableValuesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py new file mode 100644 index 000000000000..18537e83bff7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._policy_client import PolicyClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py new file mode 100644 index 000000000000..1395d715583c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-policy/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py new file mode 100644 index 000000000000..7918f89e1426 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py @@ -0,0 +1,183 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import PolicyClientConfiguration +from .operations import ( + DataPolicyManifestsOperations, + PolicyAssignmentsOperations, + PolicyDefinitionVersionsOperations, + PolicyDefinitionsOperations, + PolicyExemptionsOperations, + PolicySetDefinitionVersionsOperations, + PolicySetDefinitionsOperations, + VariableValuesOperations, + VariablesOperations, +) + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Policy Client. + + :ivar data_policy_manifests: DataPolicyManifestsOperations operations + :vartype data_policy_manifests: + azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: + azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations + :ivar policy_definition_versions: PolicyDefinitionVersionsOperations operations + :vartype policy_definition_versions: + azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations + :ivar policy_set_definitions: PolicySetDefinitionsOperations operations + :vartype policy_set_definitions: + azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations + :ivar policy_set_definition_versions: PolicySetDefinitionVersionsOperations operations + :vartype policy_set_definition_versions: + azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: + azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations + :ivar policy_exemptions: PolicyExemptionsOperations operations + :vartype policy_exemptions: + azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations + :ivar variables: VariablesOperations operations + :vartype variables: azure.mgmt.resource.policy.aio.operations.VariablesOperations + :ivar variable_values: VariableValuesOperations operations + :vartype variable_values: azure.mgmt.resource.policy.aio.operations.VariableValuesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = PolicyClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.data_policy_manifests = DataPolicyManifestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definition_versions = PolicyDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definitions = PolicySetDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definition_versions = PolicySetDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_exemptions = PolicyExemptionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.variables = VariablesOperations(self._client, self._config, self._serialize, self._deserialize) + self.variable_values = VariableValuesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py new file mode 100644 index 000000000000..f302859689f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataPolicyManifestsOperations # type: ignore +from ._operations import PolicyDefinitionsOperations # type: ignore +from ._operations import PolicyDefinitionVersionsOperations # type: ignore +from ._operations import PolicySetDefinitionsOperations # type: ignore +from ._operations import PolicySetDefinitionVersionsOperations # type: ignore +from ._operations import PolicyAssignmentsOperations # type: ignore +from ._operations import PolicyExemptionsOperations # type: ignore +from ._operations import VariablesOperations # type: ignore +from ._operations import VariableValuesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataPolicyManifestsOperations", + "PolicyDefinitionsOperations", + "PolicyDefinitionVersionsOperations", + "PolicySetDefinitionsOperations", + "PolicySetDefinitionVersionsOperations", + "PolicyAssignmentsOperations", + "PolicyExemptionsOperations", + "VariablesOperations", + "VariableValuesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py new file mode 100644 index 000000000000..b166b31b9016 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py @@ -0,0 +1,7433 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_data_policy_manifests_get_by_policy_mode_request, + build_data_policy_manifests_list_request, + build_policy_assignments_create_by_id_request, + build_policy_assignments_create_request, + build_policy_assignments_delete_by_id_request, + build_policy_assignments_delete_request, + build_policy_assignments_get_by_id_request, + build_policy_assignments_get_request, + build_policy_assignments_list_for_management_group_request, + build_policy_assignments_list_for_resource_group_request, + build_policy_assignments_list_for_resource_request, + build_policy_assignments_list_request, + build_policy_assignments_update_by_id_request, + build_policy_assignments_update_request, + build_policy_definition_versions_create_or_update_at_management_group_request, + build_policy_definition_versions_create_or_update_request, + build_policy_definition_versions_delete_at_management_group_request, + build_policy_definition_versions_delete_request, + build_policy_definition_versions_get_at_management_group_request, + build_policy_definition_versions_get_built_in_request, + build_policy_definition_versions_get_request, + build_policy_definition_versions_list_all_at_management_group_request, + build_policy_definition_versions_list_all_builtins_request, + build_policy_definition_versions_list_all_request, + build_policy_definition_versions_list_built_in_request, + build_policy_definition_versions_list_by_management_group_request, + build_policy_definition_versions_list_request, + build_policy_definitions_create_or_update_at_management_group_request, + build_policy_definitions_create_or_update_request, + build_policy_definitions_delete_at_management_group_request, + build_policy_definitions_delete_request, + build_policy_definitions_get_at_management_group_request, + build_policy_definitions_get_built_in_request, + build_policy_definitions_get_request, + build_policy_definitions_list_built_in_request, + build_policy_definitions_list_by_management_group_request, + build_policy_definitions_list_request, + build_policy_exemptions_create_or_update_request, + build_policy_exemptions_delete_request, + build_policy_exemptions_get_request, + build_policy_exemptions_list_for_management_group_request, + build_policy_exemptions_list_for_resource_group_request, + build_policy_exemptions_list_for_resource_request, + build_policy_exemptions_list_request, + build_policy_exemptions_update_request, + build_policy_set_definition_versions_create_or_update_at_management_group_request, + build_policy_set_definition_versions_create_or_update_request, + build_policy_set_definition_versions_delete_at_management_group_request, + build_policy_set_definition_versions_delete_request, + build_policy_set_definition_versions_get_at_management_group_request, + build_policy_set_definition_versions_get_built_in_request, + build_policy_set_definition_versions_get_request, + build_policy_set_definition_versions_list_all_at_management_group_request, + build_policy_set_definition_versions_list_all_builtins_request, + build_policy_set_definition_versions_list_all_request, + build_policy_set_definition_versions_list_built_in_request, + build_policy_set_definition_versions_list_by_management_group_request, + build_policy_set_definition_versions_list_request, + build_policy_set_definitions_create_or_update_at_management_group_request, + build_policy_set_definitions_create_or_update_request, + build_policy_set_definitions_delete_at_management_group_request, + build_policy_set_definitions_delete_request, + build_policy_set_definitions_get_at_management_group_request, + build_policy_set_definitions_get_built_in_request, + build_policy_set_definitions_get_request, + build_policy_set_definitions_list_built_in_request, + build_policy_set_definitions_list_by_management_group_request, + build_policy_set_definitions_list_request, + build_variable_values_create_or_update_at_management_group_request, + build_variable_values_create_or_update_request, + build_variable_values_delete_at_management_group_request, + build_variable_values_delete_request, + build_variable_values_get_at_management_group_request, + build_variable_values_get_request, + build_variable_values_list_for_management_group_request, + build_variable_values_list_request, + build_variables_create_or_update_at_management_group_request, + build_variables_create_or_update_request, + build_variables_delete_at_management_group_request, + build_variables_delete_request, + build_variables_get_at_management_group_request, + build_variables_get_request, + build_variables_list_for_management_group_request, + build_variables_list_request, +) +from .._configuration import PolicyClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class DataPolicyManifestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`data_policy_manifests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_by_policy_mode(self, policy_mode: str, **kwargs: Any) -> _models.DataPolicyManifest: + """Retrieves a data policy manifest. + + This operation retrieves the data policy manifest with the given policy mode. + + :param policy_mode: The policy mode of the data policy manifest to get. Required. + :type policy_mode: str + :return: DataPolicyManifest or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.DataPolicyManifest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifest] = kwargs.pop("cls", None) + + _request = build_data_policy_manifests_get_by_policy_mode_request( + policy_mode=policy_mode, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataPolicyManifest", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.DataPolicyManifest"]: + """Retrieves data policy manifests. + + This operation retrieves a list of all the data policy manifests that match the optional given + $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not + provided, the unfiltered list includes all data policy manifests for data resource types. If + $filter=namespace is provided, the returned list only includes all data policy manifests that + have a namespace matching the provided value. + + :param filter: The filter to apply on the operation. Valid values for $filter are: "namespace + eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq + '{value}' is provided, the returned list only includes all data policy manifests that have a + namespace matching the provided value. Default value is None. + :type filter: str + :return: An iterator like instance of either DataPolicyManifest or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifestListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_data_policy_manifests_list_request( + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DataPolicyManifestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_definition_name: str, **kwargs: Any) -> None: + """Deletes a policy definition in a subscription. + + This operation deletes the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a policy definition in a subscription. + + This operation retrieves the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a built-in policy definition. + + This operation retrieves the built-in policy definition with the given name. + + :param policy_definition_name: The name of the built-in policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: Union[_models.PolicyDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Retrieve a policy definition in a management group. + + This operation retrieves the policy definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinition"]: + """Retrieves policy definitions in a subscription. + + This operation retrieves a list of all the policy definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the subscription, including those that apply + directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list + only includes all policy definitions whose type match the {value}. Possible policyType values + are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, + the returned list only includes all policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinition"]: + """Retrieve built-in policy definitions. + + This operation retrieves a list of all the built-in policy definitions that match the optional + given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes + all built-in policy definitions whose type match the {value}. Possible policyType values are + NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the + returned list only includes all built-in policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_built_in_request( + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinition"]: + """Retrieve policy definitions in a management group. + + This operation retrieves a list of all the policy definitions in a given management group that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the management group, including those that + apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given management group. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is + provided, the returned list only includes all policy definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicyDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list_all_builtins(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all built-in policy definition versions. + + This operation lists all the built-in policy definition versions for all built-in policy + definitions. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions at management group scope. + + This operation lists all the policy definition versions for all policy definitions at the + management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions within a subscription. + + This operation lists all the policy definition versions for all policy definitions within a + subscription. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any) -> None: + """Deletes a policy definition version in a subscription. + + This operation deletes the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a policy definition version in a subscription. + + This operation retrieves the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a built-in policy definition version. + + This operation retrieves the built-in policy definition version with the given name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_built_in_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieve a policy definition version in a management group. + + This operation retrieves the policy definition version in the given management group with the + given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieves policy definition versions for a given policy definition in a subscription. + + This operation retrieves a list of all the policy definition versions for the given policy + definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve built-in policy definition versions. + + This operation retrieves a list of all the built-in policy definition versions for the given + policy definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_built_in_request( + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_name: str, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve policy definition versions in a management group policy definition. + + This operation retrieves a list of all the policy definition versions for the given policy + definition in the given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicySetDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_set_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_set_definition_name: str, **kwargs: Any) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given subscription with the given name. + + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given subscription with the given + name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a built in policy set definition. + + This operation retrieves the built-in policy set definition with the given name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinition"]: + """Retrieves the policy set definitions for a subscription. + + This operation retrieves a list of all the policy set definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy set definitions associated with the subscription, including those that + apply directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy set definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the + returned list only includes all policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinition"]: + """Retrieves built-in policy set definitions. + + This operation retrieves a list of all the built-in policy set definitions that match the + optional given $filter. If $filter='category -eq {value}' is provided, the returned list only + includes all built-in policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_built_in_request( + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: Union[_models.PolicySetDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_id: str, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinition"]: + """Retrieves all policy set definitions in management group. + + This operation retrieves a list of all the policy set definitions in a given management group + that match the optional given $filter. Valid values for $filter are: 'atExactScope()', + 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered + list includes all policy set definitions associated with the management group, including those + that apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given management group. If $filter='policyType -eq {value}' is provided, the + returned list only includes all policy set definitions whose type match the {value}. Possible + policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is + provided, the returned list only includes all policy set definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicySetDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_set_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list_all_builtins(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all built-in policy set definition versions. + + This operation lists all the built-in policy set definition versions for all built-in policy + set definitions. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions at management group scope. + + This operation lists all the policy set definition versions for all policy set definitions at + the management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions within a subscription. + + This operation lists all the policy set definition versions for all policy set definitions + within a subscription. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinitionVersion + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a built in policy set definition version. + + This operation retrieves the built-in policy set definition version with the given name and + version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves the policy set definition versions for a given policy set definition in a + subscription. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves built-in policy set definition versions. + + This operation retrieves a list of all the built-in policy set definition versions for the + given built-in policy set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Is either a + PolicySetDefinitionVersion type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given management group with the + given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given management group with + the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves all policy set definition versions for a given policy set definition in a management + group. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition in a given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete( + self, scope: str, policy_assignment_name: str, **kwargs: Any + ) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes a policy assignment, given its name and the scope it was created in. The + scope of a policy assignment is the part of its ID preceding + '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignment, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, policy_assignment_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves a policy assignment. + + This operation retrieves a single policy assignment, given its name and the scope it was + created at. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_for_resource_group( + self, + resource_group_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource group. + + This operation retrieves the list of all policy assignments associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy assignments associated with the resource + group, including those that apply directly or apply from containing scopes, as well as any + applied to resources contained within the resource group. If $filter=atScope() is provided, the + returned list includes all policy assignments that apply to the resource group, which is + everything in the unfiltered list except those applied to resources contained within the + resource group. If $filter=atExactScope() is provided, the returned list only includes all + policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource. + + This operation retrieves the list of all policy assignments associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq + '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments + associated with the resource, including those that apply directly or from all containing + scopes, as well as any applied to resources contained within the resource. If $filter=atScope() + is provided, the returned list includes all policy assignments that apply to the resource, + which is everything in the unfiltered list except those applied to resources contained within + the resource. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value} + that apply to the resource. Three parameters plus the resource name are used to identify a + specific resource. If the resource is not part of a parent resource (the more common case), the + parent resource path should not be provided (or provided as ''). For example a web app could be + specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', + {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent + resource, then all parameters should be provided. For example a virtual machine DNS name could + be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a management group. + + This operation retrieves the list of all policy assignments applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or + 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes + all policy assignments that are assigned to the management group or the management group's + ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a subscription. + + This operation retrieves the list of all policy assignments associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the + unfiltered list includes all policy assignments associated with the subscription, including + those that apply directly or from management groups that contain the given subscription, as + well as any applied to objects contained within the subscription. If $filter=atScope() is + provided, the returned list includes all policy assignments that apply to the subscription, + which is everything in the unfiltered list except those applied to objects contained within the + subscription. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes the policy with the given ID. Policy assignment IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + formats for {scope} are: '/providers/Microsoft.Management/managementGroups/{managementGroup}' + (management group), '/subscriptions/{subscriptionId}' (subscription), + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' (resource group), or + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}' + (resource). + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_by_id( + self, policy_assignment_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves the policy assignment with the given ID. + + The operation retrieves the policy assignment with the given ID. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PolicyExemptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_exemptions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> None: + """Deletes a policy exemption. + + This operation deletes a policy exemption, given its name and the scope it was created in. The + scope of a policy exemption is the part of its ID preceding + '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_delete_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemption, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemption, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Is either a PolicyExemption type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemption") + + _request = build_policy_exemptions_create_or_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> _models.PolicyExemption: + """Retrieves a policy exemption. + + This operation retrieves a single policy exemption, given its name and the scope it was created + at. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_get_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemptionUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemptionUpdate, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Is either a + PolicyExemptionUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemptionUpdate") + + _request = build_policy_exemptions_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a subscription. + + This operation retrieves the list of all policy exemptions associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy exemptions associated with the subscription, + including those that apply directly or from management groups that contain the given + subscription, as well as any applied to objects contained within the subscription. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource group. + + This operation retrieves the list of all policy exemptions associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If + $filter is not provided, the unfiltered list includes all policy exemptions associated with the + resource group, including those that apply directly or apply from containing scopes, as well as + any applied to resources contained within the resource group. + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource. + + This operation retrieves the list of all policy exemptions associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or + 'policyAssignmentId eq '{value}''. If $filter is not provided, the unfiltered list includes all + policy exemptions associated with the resource, including those that apply directly or from all + containing scopes, as well as any applied to resources contained within the resource. Three + parameters plus the resource name are used to identify a specific resource. If the resource is + not part of a parent resource (the more common case), the parent resource path should not be + provided (or provided as ''). For example a web app could be specified as + ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == + 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all + parameters should be provided. For example a virtual machine DNS name could be specified as + ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a management group. + + This operation retrieves the list of all policy exemptions applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', + 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter=atScope() is provided, the + returned list includes all policy exemptions that are assigned to the management group or the + management group's ancestors. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class VariablesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`variables` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, variable_name: str, **kwargs: Any) -> None: + """Deletes a variable. + + This operation deletes a variable, given its name and the subscription it was created in. The + scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, variable_name: str, parameters: _models.Variable, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, variable_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, variable_name: str, parameters: Union[_models.Variable, IO[bytes]], **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, variable_name: str, **kwargs: Any) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the subscription it was created + at. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group(self, management_group_id: str, variable_name: str, **kwargs: Any) -> None: + """Deletes a variable. + + This operation deletes a variable, given its name and the management group it was created in. + The scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: _models.Variable, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: Union[_models.Variable, IO[bytes]], + **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the management group it was + created at. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Variable"]: + """Retrieves all variables that are at this subscription level. + + This operation retrieves the list of all variables associated with the given subscription. + + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group(self, management_group_id: str, **kwargs: Any) -> AsyncItemPaged["_models.Variable"]: + """Retrieves all variables that are at this management group level. + + This operation retrieves the list of all variables applicable to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_for_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class VariableValuesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`variable_values` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the subscription it was created in, + and the variable it belongs to. The scope of a variable value is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, subscription it was created + at and the variable it's created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, variable_name: str, **kwargs: Any) -> AsyncItemPaged["_models.VariableValue"]: + """List variable values for a variable. + + This operation retrieves the list of all variable values associated with the given variable + that is at a subscription level. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.VariableValue"]: + """List variable values at management group level. + + This operation retrieves the list of all variable values applicable the variable indicated at + the management group scope. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_for_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the management group it was created + in, and the variable it belongs to. The scope of a variable value is the part of its ID + preceding '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, management group it was + created at and the variable it's created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py new file mode 100644 index 000000000000..28b5db51f4e5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Alias, + AliasPath, + AliasPathMetadata, + AliasPattern, + DataEffect, + DataManifestCustomResourceFunctionDefinition, + DataPolicyManifest, + DataPolicyManifestListResult, + ErrorAdditionalInfo, + ErrorResponse, + Identity, + NonComplianceMessage, + Override, + ParameterDefinitionsValue, + ParameterDefinitionsValueMetadata, + ParameterValuesValue, + PolicyAssignment, + PolicyAssignmentListResult, + PolicyAssignmentUpdate, + PolicyDefinition, + PolicyDefinitionGroup, + PolicyDefinitionListResult, + PolicyDefinitionReference, + PolicyDefinitionVersion, + PolicyDefinitionVersionListResult, + PolicyExemption, + PolicyExemptionListResult, + PolicyExemptionUpdate, + PolicySetDefinition, + PolicySetDefinitionListResult, + PolicySetDefinitionVersion, + PolicySetDefinitionVersionListResult, + PolicyVariableColumn, + PolicyVariableValueColumnValue, + ResourceSelector, + ResourceTypeAliases, + Selector, + SystemData, + UserAssignedIdentitiesValue, + Variable, + VariableListResult, + VariableValue, + VariableValueListResult, +) + +from ._policy_client_enums import ( # type: ignore + AliasPathAttributes, + AliasPathTokenType, + AliasPatternType, + AliasType, + AssignmentScopeValidation, + CreatedByType, + EnforcementMode, + ExemptionCategory, + OverrideKind, + ParameterType, + PolicyType, + ResourceIdentityType, + SelectorKind, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Alias", + "AliasPath", + "AliasPathMetadata", + "AliasPattern", + "DataEffect", + "DataManifestCustomResourceFunctionDefinition", + "DataPolicyManifest", + "DataPolicyManifestListResult", + "ErrorAdditionalInfo", + "ErrorResponse", + "Identity", + "NonComplianceMessage", + "Override", + "ParameterDefinitionsValue", + "ParameterDefinitionsValueMetadata", + "ParameterValuesValue", + "PolicyAssignment", + "PolicyAssignmentListResult", + "PolicyAssignmentUpdate", + "PolicyDefinition", + "PolicyDefinitionGroup", + "PolicyDefinitionListResult", + "PolicyDefinitionReference", + "PolicyDefinitionVersion", + "PolicyDefinitionVersionListResult", + "PolicyExemption", + "PolicyExemptionListResult", + "PolicyExemptionUpdate", + "PolicySetDefinition", + "PolicySetDefinitionListResult", + "PolicySetDefinitionVersion", + "PolicySetDefinitionVersionListResult", + "PolicyVariableColumn", + "PolicyVariableValueColumnValue", + "ResourceSelector", + "ResourceTypeAliases", + "Selector", + "SystemData", + "UserAssignedIdentitiesValue", + "Variable", + "VariableListResult", + "VariableValue", + "VariableValueListResult", + "AliasPathAttributes", + "AliasPathTokenType", + "AliasPatternType", + "AliasType", + "AssignmentScopeValidation", + "CreatedByType", + "EnforcementMode", + "ExemptionCategory", + "OverrideKind", + "ParameterType", + "PolicyType", + "ResourceIdentityType", + "SelectorKind", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py new file mode 100644 index 000000000000..5292feea9241 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py @@ -0,0 +1,2333 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +import datetime +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class Alias(_serialization.Model): + """The alias type. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The alias name. + :vartype name: str + :ivar paths: The paths for an alias. + :vartype paths: list[~azure.mgmt.resource.policy.models.AliasPath] + :ivar type: The type of the alias. Known values are: "NotSpecified", "PlainText", and "Mask". + :vartype type: str or ~azure.mgmt.resource.policy.models.AliasType + :ivar default_path: The default path for an alias. + :vartype default_path: str + :ivar default_pattern: The default pattern for an alias. + :vartype default_pattern: ~azure.mgmt.resource.policy.models.AliasPattern + :ivar default_metadata: The default alias path metadata. Applies to the default path and to any + alias path that doesn't have metadata. + :vartype default_metadata: ~azure.mgmt.resource.policy.models.AliasPathMetadata + """ + + _validation = { + "default_metadata": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "paths": {"key": "paths", "type": "[AliasPath]"}, + "type": {"key": "type", "type": "str"}, + "default_path": {"key": "defaultPath", "type": "str"}, + "default_pattern": {"key": "defaultPattern", "type": "AliasPattern"}, + "default_metadata": {"key": "defaultMetadata", "type": "AliasPathMetadata"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + paths: Optional[list["_models.AliasPath"]] = None, + type: Optional[Union[str, "_models.AliasType"]] = None, + default_path: Optional[str] = None, + default_pattern: Optional["_models.AliasPattern"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The alias name. + :paramtype name: str + :keyword paths: The paths for an alias. + :paramtype paths: list[~azure.mgmt.resource.policy.models.AliasPath] + :keyword type: The type of the alias. Known values are: "NotSpecified", "PlainText", and + "Mask". + :paramtype type: str or ~azure.mgmt.resource.policy.models.AliasType + :keyword default_path: The default path for an alias. + :paramtype default_path: str + :keyword default_pattern: The default pattern for an alias. + :paramtype default_pattern: ~azure.mgmt.resource.policy.models.AliasPattern + """ + super().__init__(**kwargs) + self.name = name + self.paths = paths + self.type = type + self.default_path = default_path + self.default_pattern = default_pattern + self.default_metadata: Optional["_models.AliasPathMetadata"] = None + + +class AliasPath(_serialization.Model): + """The type of the paths for alias. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar path: The path of an alias. + :vartype path: str + :ivar api_versions: The API versions. + :vartype api_versions: list[str] + :ivar pattern: The pattern for an alias path. + :vartype pattern: ~azure.mgmt.resource.policy.models.AliasPattern + :ivar metadata: The metadata of the alias path. If missing, fall back to the default metadata + of the alias. + :vartype metadata: ~azure.mgmt.resource.policy.models.AliasPathMetadata + """ + + _validation = { + "metadata": {"readonly": True}, + } + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "api_versions": {"key": "apiVersions", "type": "[str]"}, + "pattern": {"key": "pattern", "type": "AliasPattern"}, + "metadata": {"key": "metadata", "type": "AliasPathMetadata"}, + } + + def __init__( + self, + *, + path: Optional[str] = None, + api_versions: Optional[list[str]] = None, + pattern: Optional["_models.AliasPattern"] = None, + **kwargs: Any + ) -> None: + """ + :keyword path: The path of an alias. + :paramtype path: str + :keyword api_versions: The API versions. + :paramtype api_versions: list[str] + :keyword pattern: The pattern for an alias path. + :paramtype pattern: ~azure.mgmt.resource.policy.models.AliasPattern + """ + super().__init__(**kwargs) + self.path = path + self.api_versions = api_versions + self.pattern = pattern + self.metadata: Optional["_models.AliasPathMetadata"] = None + + +class AliasPathMetadata(_serialization.Model): + """AliasPathMetadata. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The type of the token that the alias path is referring to. Known values are: + "NotSpecified", "Any", "String", "Object", "Array", "Integer", "Number", and "Boolean". + :vartype type: str or ~azure.mgmt.resource.policy.models.AliasPathTokenType + :ivar attributes: The attributes of the token that the alias path is referring to. Known values + are: "None" and "Modifiable". + :vartype attributes: str or ~azure.mgmt.resource.policy.models.AliasPathAttributes + """ + + _validation = { + "type": {"readonly": True}, + "attributes": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "attributes": {"key": "attributes", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[Union[str, "_models.AliasPathTokenType"]] = None + self.attributes: Optional[Union[str, "_models.AliasPathAttributes"]] = None + + +class AliasPattern(_serialization.Model): + """The type of the pattern for an alias path. + + :ivar phrase: The alias pattern phrase. + :vartype phrase: str + :ivar variable: The alias pattern variable. + :vartype variable: str + :ivar type: The type of alias pattern. Known values are: "NotSpecified" and "Extract". + :vartype type: str or ~azure.mgmt.resource.policy.models.AliasPatternType + """ + + _attribute_map = { + "phrase": {"key": "phrase", "type": "str"}, + "variable": {"key": "variable", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + phrase: Optional[str] = None, + variable: Optional[str] = None, + type: Optional[Union[str, "_models.AliasPatternType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword phrase: The alias pattern phrase. + :paramtype phrase: str + :keyword variable: The alias pattern variable. + :paramtype variable: str + :keyword type: The type of alias pattern. Known values are: "NotSpecified" and "Extract". + :paramtype type: str or ~azure.mgmt.resource.policy.models.AliasPatternType + """ + super().__init__(**kwargs) + self.phrase = phrase + self.variable = variable + self.type = type + + +class DataEffect(_serialization.Model): + """The data effect definition. + + :ivar name: The data effect name. + :vartype name: str + :ivar details_schema: The data effect details schema. + :vartype details_schema: JSON + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "details_schema": {"key": "detailsSchema", "type": "object"}, + } + + def __init__(self, *, name: Optional[str] = None, details_schema: Optional[JSON] = None, **kwargs: Any) -> None: + """ + :keyword name: The data effect name. + :paramtype name: str + :keyword details_schema: The data effect details schema. + :paramtype details_schema: JSON + """ + super().__init__(**kwargs) + self.name = name + self.details_schema = details_schema + + +class DataManifestCustomResourceFunctionDefinition(_serialization.Model): # pylint: disable=name-too-long + """The custom resource function definition. + + :ivar name: The function name as it will appear in the policy rule. eg - 'vault'. + :vartype name: str + :ivar fully_qualified_resource_type: The fully qualified control plane resource type that this + function represents. eg - 'Microsoft.KeyVault/vaults'. + :vartype fully_qualified_resource_type: str + :ivar default_properties: The top-level properties that can be selected on the function's + output. eg - [ "name", "location" ] if vault().name and vault().location are supported. + :vartype default_properties: list[str] + :ivar allow_custom_properties: A value indicating whether the custom properties within the + property bag are allowed. Needs api-version to be specified in the policy rule eg - + vault('2019-06-01'). + :vartype allow_custom_properties: bool + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "fully_qualified_resource_type": {"key": "fullyQualifiedResourceType", "type": "str"}, + "default_properties": {"key": "defaultProperties", "type": "[str]"}, + "allow_custom_properties": {"key": "allowCustomProperties", "type": "bool"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + fully_qualified_resource_type: Optional[str] = None, + default_properties: Optional[list[str]] = None, + allow_custom_properties: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The function name as it will appear in the policy rule. eg - 'vault'. + :paramtype name: str + :keyword fully_qualified_resource_type: The fully qualified control plane resource type that + this function represents. eg - 'Microsoft.KeyVault/vaults'. + :paramtype fully_qualified_resource_type: str + :keyword default_properties: The top-level properties that can be selected on the function's + output. eg - [ "name", "location" ] if vault().name and vault().location are supported. + :paramtype default_properties: list[str] + :keyword allow_custom_properties: A value indicating whether the custom properties within the + property bag are allowed. Needs api-version to be specified in the policy rule eg - + vault('2019-06-01'). + :paramtype allow_custom_properties: bool + """ + super().__init__(**kwargs) + self.name = name + self.fully_qualified_resource_type = fully_qualified_resource_type + self.default_properties = default_properties + self.allow_custom_properties = allow_custom_properties + + +class DataPolicyManifest(_serialization.Model): + """The data policy manifest. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the data policy manifest. + :vartype id: str + :ivar name: The name of the data policy manifest (it's the same as the Policy Mode). + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/dataPolicyManifests). + :vartype type: str + :ivar namespaces: The list of namespaces for the data policy manifest. + :vartype namespaces: list[str] + :ivar policy_mode: The policy mode of the data policy manifest. + :vartype policy_mode: str + :ivar is_built_in_only: A value indicating whether policy mode is allowed only in built-in + definitions. + :vartype is_built_in_only: bool + :ivar resource_type_aliases: An array of resource type aliases. + :vartype resource_type_aliases: list[~azure.mgmt.resource.policy.models.ResourceTypeAliases] + :ivar effects: The effect definition. + :vartype effects: list[~azure.mgmt.resource.policy.models.DataEffect] + :ivar field_values: The non-alias field accessor values that can be used in the policy rule. + :vartype field_values: list[str] + :ivar standard: The standard resource functions (subscription and/or resourceGroup). + :vartype standard: list[str] + :ivar custom: An array of data manifest custom resource definition. + :vartype custom: + list[~azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "namespaces": {"key": "properties.namespaces", "type": "[str]"}, + "policy_mode": {"key": "properties.policyMode", "type": "str"}, + "is_built_in_only": {"key": "properties.isBuiltInOnly", "type": "bool"}, + "resource_type_aliases": {"key": "properties.resourceTypeAliases", "type": "[ResourceTypeAliases]"}, + "effects": {"key": "properties.effects", "type": "[DataEffect]"}, + "field_values": {"key": "properties.fieldValues", "type": "[str]"}, + "standard": {"key": "properties.resourceFunctions.standard", "type": "[str]"}, + "custom": { + "key": "properties.resourceFunctions.custom", + "type": "[DataManifestCustomResourceFunctionDefinition]", + }, + } + + def __init__( + self, + *, + namespaces: Optional[list[str]] = None, + policy_mode: Optional[str] = None, + is_built_in_only: Optional[bool] = None, + resource_type_aliases: Optional[list["_models.ResourceTypeAliases"]] = None, + effects: Optional[list["_models.DataEffect"]] = None, + field_values: Optional[list[str]] = None, + standard: Optional[list[str]] = None, + custom: Optional[list["_models.DataManifestCustomResourceFunctionDefinition"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword namespaces: The list of namespaces for the data policy manifest. + :paramtype namespaces: list[str] + :keyword policy_mode: The policy mode of the data policy manifest. + :paramtype policy_mode: str + :keyword is_built_in_only: A value indicating whether policy mode is allowed only in built-in + definitions. + :paramtype is_built_in_only: bool + :keyword resource_type_aliases: An array of resource type aliases. + :paramtype resource_type_aliases: list[~azure.mgmt.resource.policy.models.ResourceTypeAliases] + :keyword effects: The effect definition. + :paramtype effects: list[~azure.mgmt.resource.policy.models.DataEffect] + :keyword field_values: The non-alias field accessor values that can be used in the policy rule. + :paramtype field_values: list[str] + :keyword standard: The standard resource functions (subscription and/or resourceGroup). + :paramtype standard: list[str] + :keyword custom: An array of data manifest custom resource definition. + :paramtype custom: + list[~azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.namespaces = namespaces + self.policy_mode = policy_mode + self.is_built_in_only = is_built_in_only + self.resource_type_aliases = resource_type_aliases + self.effects = effects + self.field_values = field_values + self.standard = standard + self.custom = custom + + +class DataPolicyManifestListResult(_serialization.Model): + """List of data policy manifests. + + :ivar value: An array of data policy manifests. + :vartype value: list[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[DataPolicyManifest]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.DataPolicyManifest"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of data policy manifests. + :paramtype value: list[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.policy.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.policy.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorResponse"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class Identity(_serialization.Model): + """Identity for the resource. Policy assignments support a maximum of one identity. That is + either a system assigned identity or a single user assigned identity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of the resource identity. This property will only be + provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the resource identity. This property will only be provided + for a system assigned identity. + :vartype tenant_id: str + :ivar type: The identity type. This is the only required field when adding a system or user + assigned identity to a resource. Known values are: "SystemAssigned", "UserAssigned", and + "None". + :vartype type: str or ~azure.mgmt.resource.policy.models.ResourceIdentityType + :ivar user_assigned_identities: The user identity associated with the policy. The user identity + dictionary key references will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue] + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentitiesValue}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentitiesValue"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The identity type. This is the only required field when adding a system or user + assigned identity to a resource. Known values are: "SystemAssigned", "UserAssigned", and + "None". + :paramtype type: str or ~azure.mgmt.resource.policy.models.ResourceIdentityType + :keyword user_assigned_identities: The user identity associated with the policy. The user + identity dictionary key references will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue] + """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.tenant_id: Optional[str] = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class NonComplianceMessage(_serialization.Model): + """A message that describes why a resource is non-compliant with the policy. This is shown in + 'deny' error messages and on resource's non-compliant compliance results. + + All required parameters must be populated in order to send to server. + + :ivar message: A message that describes why a resource is non-compliant with the policy. This + is shown in 'deny' error messages and on resource's non-compliant compliance results. Required. + :vartype message: str + :ivar policy_definition_reference_id: The policy definition reference ID within a policy set + definition the message is intended for. This is only applicable if the policy assignment + assigns a policy set definition. If this is not provided the message applies to all policies + assigned by this policy assignment. + :vartype policy_definition_reference_id: str + """ + + _validation = { + "message": {"required": True}, + } + + _attribute_map = { + "message": {"key": "message", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + } + + def __init__(self, *, message: str, policy_definition_reference_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword message: A message that describes why a resource is non-compliant with the policy. + This is shown in 'deny' error messages and on resource's non-compliant compliance results. + Required. + :paramtype message: str + :keyword policy_definition_reference_id: The policy definition reference ID within a policy set + definition the message is intended for. This is only applicable if the policy assignment + assigns a policy set definition. If this is not provided the message applies to all policies + assigned by this policy assignment. + :paramtype policy_definition_reference_id: str + """ + super().__init__(**kwargs) + self.message = message + self.policy_definition_reference_id = policy_definition_reference_id + + +class Override(_serialization.Model): + """The policy property value override. + + :ivar kind: The override kind. "policyEffect" + :vartype kind: str or ~azure.mgmt.resource.policy.models.OverrideKind + :ivar value: The value to override the policy property. + :vartype value: str + :ivar selectors: The list of the selector expressions. + :vartype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + + _attribute_map = { + "kind": {"key": "kind", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "selectors": {"key": "selectors", "type": "[Selector]"}, + } + + def __init__( + self, + *, + kind: Optional[Union[str, "_models.OverrideKind"]] = None, + value: Optional[str] = None, + selectors: Optional[list["_models.Selector"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword kind: The override kind. "policyEffect" + :paramtype kind: str or ~azure.mgmt.resource.policy.models.OverrideKind + :keyword value: The value to override the policy property. + :paramtype value: str + :keyword selectors: The list of the selector expressions. + :paramtype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + super().__init__(**kwargs) + self.kind = kind + self.value = value + self.selectors = selectors + + +class ParameterDefinitionsValue(_serialization.Model): + """The definition of a parameter that can be provided to the policy. + + :ivar type: The data type of the parameter. Known values are: "String", "Array", "Object", + "Boolean", "Integer", "Float", and "DateTime". + :vartype type: str or ~azure.mgmt.resource.policy.models.ParameterType + :ivar allowed_values: The allowed values for the parameter. + :vartype allowed_values: list[JSON] + :ivar default_value: The default value for the parameter if no value is provided. + :vartype default_value: JSON + :ivar schema: Provides validation of parameter inputs during assignment using a self-defined + JSON schema. This property is only supported for object-type parameters and follows the + Json.NET Schema 2019-09 implementation. You can learn more about using schemas at + https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/. + :vartype schema: JSON + :ivar metadata: General metadata for the parameter. + :vartype metadata: ~azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "allowed_values": {"key": "allowedValues", "type": "[object]"}, + "default_value": {"key": "defaultValue", "type": "object"}, + "schema": {"key": "schema", "type": "object"}, + "metadata": {"key": "metadata", "type": "ParameterDefinitionsValueMetadata"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ParameterType"]] = None, + allowed_values: Optional[list[JSON]] = None, + default_value: Optional[JSON] = None, + schema: Optional[JSON] = None, + metadata: Optional["_models.ParameterDefinitionsValueMetadata"] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The data type of the parameter. Known values are: "String", "Array", "Object", + "Boolean", "Integer", "Float", and "DateTime". + :paramtype type: str or ~azure.mgmt.resource.policy.models.ParameterType + :keyword allowed_values: The allowed values for the parameter. + :paramtype allowed_values: list[JSON] + :keyword default_value: The default value for the parameter if no value is provided. + :paramtype default_value: JSON + :keyword schema: Provides validation of parameter inputs during assignment using a self-defined + JSON schema. This property is only supported for object-type parameters and follows the + Json.NET Schema 2019-09 implementation. You can learn more about using schemas at + https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/. + :paramtype schema: JSON + :keyword metadata: General metadata for the parameter. + :paramtype metadata: ~azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata + """ + super().__init__(**kwargs) + self.type = type + self.allowed_values = allowed_values + self.default_value = default_value + self.schema = schema + self.metadata = metadata + + +class ParameterDefinitionsValueMetadata(_serialization.Model): + """General metadata for the parameter. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, JSON] + :ivar display_name: The display name for the parameter. + :vartype display_name: str + :ivar description: The description of the parameter. + :vartype description: str + :ivar strong_type: Used when assigning the policy definition through the portal. Provides a + context aware list of values for the user to choose from. + :vartype strong_type: str + :ivar assign_permissions: Set to true to have Azure portal create role assignments on the + resource ID or resource scope value of this parameter during policy assignment. This property + is useful in case you wish to assign permissions outside the assignment scope. + :vartype assign_permissions: bool + """ + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "display_name": {"key": "displayName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "strong_type": {"key": "strongType", "type": "str"}, + "assign_permissions": {"key": "assignPermissions", "type": "bool"}, + } + + def __init__( + self, + *, + additional_properties: Optional[dict[str, JSON]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + strong_type: Optional[str] = None, + assign_permissions: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, JSON] + :keyword display_name: The display name for the parameter. + :paramtype display_name: str + :keyword description: The description of the parameter. + :paramtype description: str + :keyword strong_type: Used when assigning the policy definition through the portal. Provides a + context aware list of values for the user to choose from. + :paramtype strong_type: str + :keyword assign_permissions: Set to true to have Azure portal create role assignments on the + resource ID or resource scope value of this parameter during policy assignment. This property + is useful in case you wish to assign permissions outside the assignment scope. + :paramtype assign_permissions: bool + """ + super().__init__(**kwargs) + self.additional_properties = additional_properties + self.display_name = display_name + self.description = description + self.strong_type = strong_type + self.assign_permissions = assign_permissions + + +class ParameterValuesValue(_serialization.Model): + """The value of a parameter. + + :ivar value: The value of the parameter. + :vartype value: JSON + """ + + _attribute_map = { + "value": {"key": "value", "type": "object"}, + } + + def __init__(self, *, value: Optional[JSON] = None, **kwargs: Any) -> None: + """ + :keyword value: The value of the parameter. + :paramtype value: JSON + """ + super().__init__(**kwargs) + self.value = value + + +class PolicyAssignment(_serialization.Model): + """The policy assignment. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy assignment. + :vartype id: str + :ivar type: The type of the policy assignment. + :vartype type: str + :ivar name: The name of the policy assignment. + :vartype name: str + :ivar location: The location of the policy assignment. Only required when utilizing managed + identity. + :vartype location: str + :ivar identity: The managed identity associated with the policy assignment. + :vartype identity: ~azure.mgmt.resource.policy.models.Identity + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar display_name: The display name of the policy assignment. + :vartype display_name: str + :ivar policy_definition_id: The ID of the policy definition or policy set definition being + assigned. + :vartype policy_definition_id: str + :ivar definition_version: The version of the policy definition to use. + :vartype definition_version: str + :ivar latest_definition_version: The latest version of the policy definition available. This is + only present if requested via the $expand query parameter. + :vartype latest_definition_version: str + :ivar effective_definition_version: The effective version of the policy definition in use. This + is only present if requested via the $expand query parameter. + :vartype effective_definition_version: str + :ivar scope: The scope for the policy assignment. + :vartype scope: str + :ivar not_scopes: The policy's excluded scopes. + :vartype not_scopes: list[str] + :ivar parameters: The parameter values for the assigned policy rule. The keys are the parameter + names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :ivar description: This message will be part of response in case of policy violation. + :vartype description: str + :ivar metadata: The policy assignment metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar enforcement_mode: The policy assignment enforcement mode. Possible values are Default and + DoNotEnforce. Known values are: "Default" and "DoNotEnforce". + :vartype enforcement_mode: str or ~azure.mgmt.resource.policy.models.EnforcementMode + :ivar non_compliance_messages: The messages that describe why a resource is non-compliant with + the policy. + :vartype non_compliance_messages: list[~azure.mgmt.resource.policy.models.NonComplianceMessage] + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar overrides: The policy property value override. + :vartype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "system_data": {"readonly": True}, + "latest_definition_version": {"readonly": True}, + "effective_definition_version": {"readonly": True}, + "scope": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "policy_definition_id": {"key": "properties.policyDefinitionId", "type": "str"}, + "definition_version": {"key": "properties.definitionVersion", "type": "str"}, + "latest_definition_version": {"key": "properties.latestDefinitionVersion", "type": "str"}, + "effective_definition_version": {"key": "properties.effectiveDefinitionVersion", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "not_scopes": {"key": "properties.notScopes", "type": "[str]"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterValuesValue}"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "enforcement_mode": {"key": "properties.enforcementMode", "type": "str"}, + "non_compliance_messages": {"key": "properties.nonComplianceMessages", "type": "[NonComplianceMessage]"}, + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "overrides": {"key": "properties.overrides", "type": "[Override]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + identity: Optional["_models.Identity"] = None, + display_name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + definition_version: Optional[str] = None, + not_scopes: Optional[list[str]] = None, + parameters: Optional[dict[str, "_models.ParameterValuesValue"]] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + enforcement_mode: Union[str, "_models.EnforcementMode"] = "Default", + non_compliance_messages: Optional[list["_models.NonComplianceMessage"]] = None, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + overrides: Optional[list["_models.Override"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the policy assignment. Only required when utilizing managed + identity. + :paramtype location: str + :keyword identity: The managed identity associated with the policy assignment. + :paramtype identity: ~azure.mgmt.resource.policy.models.Identity + :keyword display_name: The display name of the policy assignment. + :paramtype display_name: str + :keyword policy_definition_id: The ID of the policy definition or policy set definition being + assigned. + :paramtype policy_definition_id: str + :keyword definition_version: The version of the policy definition to use. + :paramtype definition_version: str + :keyword not_scopes: The policy's excluded scopes. + :paramtype not_scopes: list[str] + :keyword parameters: The parameter values for the assigned policy rule. The keys are the + parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :keyword description: This message will be part of response in case of policy violation. + :paramtype description: str + :keyword metadata: The policy assignment metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword enforcement_mode: The policy assignment enforcement mode. Possible values are Default + and DoNotEnforce. Known values are: "Default" and "DoNotEnforce". + :paramtype enforcement_mode: str or ~azure.mgmt.resource.policy.models.EnforcementMode + :keyword non_compliance_messages: The messages that describe why a resource is non-compliant + with the policy. + :paramtype non_compliance_messages: + list[~azure.mgmt.resource.policy.models.NonComplianceMessage] + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword overrides: The policy property value override. + :paramtype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.type: Optional[str] = None + self.name: Optional[str] = None + self.location = location + self.identity = identity + self.system_data: Optional["_models.SystemData"] = None + self.display_name = display_name + self.policy_definition_id = policy_definition_id + self.definition_version = definition_version + self.latest_definition_version: Optional[str] = None + self.effective_definition_version: Optional[str] = None + self.scope: Optional[str] = None + self.not_scopes = not_scopes + self.parameters = parameters + self.description = description + self.metadata = metadata + self.enforcement_mode = enforcement_mode + self.non_compliance_messages = non_compliance_messages + self.resource_selectors = resource_selectors + self.overrides = overrides + + +class PolicyAssignmentListResult(_serialization.Model): + """List of policy assignments. + + :ivar value: An array of policy assignments. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicyAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy assignments. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyAssignmentUpdate(_serialization.Model): + """The policy assignment for Patch request. + + :ivar location: The location of the policy assignment. Only required when utilizing managed + identity. + :vartype location: str + :ivar identity: The managed identity associated with the policy assignment. + :vartype identity: ~azure.mgmt.resource.policy.models.Identity + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar overrides: The policy property value override. + :vartype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "overrides": {"key": "properties.overrides", "type": "[Override]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + identity: Optional["_models.Identity"] = None, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + overrides: Optional[list["_models.Override"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the policy assignment. Only required when utilizing managed + identity. + :paramtype location: str + :keyword identity: The managed identity associated with the policy assignment. + :paramtype identity: ~azure.mgmt.resource.policy.models.Identity + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword overrides: The policy property value override. + :paramtype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + super().__init__(**kwargs) + self.location = location + self.identity = identity + self.resource_selectors = resource_selectors + self.overrides = overrides + + +class PolicyDefinition(_serialization.Model): + """The policy definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition. + :vartype id: str + :ivar name: The name of the policy definition. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policyDefinitions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :vartype mode: str + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + :ivar metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar version: The policy definition version in #.#.# format. + :vartype version: str + :ivar versions: A list of available versions for this policy definition. + :vartype versions: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "mode": {"key": "properties.mode", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "version": {"key": "properties.version", "type": "str"}, + "versions": {"key": "properties.versions", "type": "[str]"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + mode: str = "Indexed", + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + version: Optional[str] = None, + versions: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :paramtype mode: str + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + :keyword metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword version: The policy definition version in #.#.# format. + :paramtype version: str + :keyword versions: A list of available versions for this policy definition. + :paramtype versions: list[str] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.mode = mode + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + self.metadata = metadata + self.parameters = parameters + self.version = version + self.versions = versions + + +class PolicyDefinitionGroup(_serialization.Model): + """The policy definition group. + + All required parameters must be populated in order to send to server. + + :ivar name: The name of the group. Required. + :vartype name: str + :ivar display_name: The group's display name. + :vartype display_name: str + :ivar category: The group's category. + :vartype category: str + :ivar description: The group's description. + :vartype description: str + :ivar additional_metadata_id: A resource ID of a resource that contains additional metadata + about the group. + :vartype additional_metadata_id: str + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "additional_metadata_id": {"key": "additionalMetadataId", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + display_name: Optional[str] = None, + category: Optional[str] = None, + description: Optional[str] = None, + additional_metadata_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the group. Required. + :paramtype name: str + :keyword display_name: The group's display name. + :paramtype display_name: str + :keyword category: The group's category. + :paramtype category: str + :keyword description: The group's description. + :paramtype description: str + :keyword additional_metadata_id: A resource ID of a resource that contains additional metadata + about the group. + :paramtype additional_metadata_id: str + """ + super().__init__(**kwargs) + self.name = name + self.display_name = display_name + self.category = category + self.description = description + self.additional_metadata_id = additional_metadata_id + + +class PolicyDefinitionListResult(_serialization.Model): + """List of policy definitions. + + :ivar value: An array of policy definitions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicyDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyDefinitionReference(_serialization.Model): + """The policy definition reference. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar policy_definition_id: The ID of the policy definition or policy set definition. Required. + :vartype policy_definition_id: str + :ivar definition_version: The version of the policy definition to use. + :vartype definition_version: str + :ivar latest_definition_version: The latest version of the policy definition available. This is + only present if requested via the $expand query parameter. + :vartype latest_definition_version: str + :ivar effective_definition_version: The effective version of the policy definition in use. This + is only present if requested via the $expand query parameter. + :vartype effective_definition_version: str + :ivar parameters: The parameter values for the referenced policy rule. The keys are the + parameter names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :ivar policy_definition_reference_id: A unique id (within the policy set definition) for this + policy definition reference. + :vartype policy_definition_reference_id: str + :ivar group_names: The name of the groups that this policy definition reference belongs to. + :vartype group_names: list[str] + """ + + _validation = { + "policy_definition_id": {"required": True}, + "latest_definition_version": {"readonly": True}, + "effective_definition_version": {"readonly": True}, + } + + _attribute_map = { + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "definition_version": {"key": "definitionVersion", "type": "str"}, + "latest_definition_version": {"key": "latestDefinitionVersion", "type": "str"}, + "effective_definition_version": {"key": "effectiveDefinitionVersion", "type": "str"}, + "parameters": {"key": "parameters", "type": "{ParameterValuesValue}"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + "group_names": {"key": "groupNames", "type": "[str]"}, + } + + def __init__( + self, + *, + policy_definition_id: str, + definition_version: Optional[str] = None, + parameters: Optional[dict[str, "_models.ParameterValuesValue"]] = None, + policy_definition_reference_id: Optional[str] = None, + group_names: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_definition_id: The ID of the policy definition or policy set definition. + Required. + :paramtype policy_definition_id: str + :keyword definition_version: The version of the policy definition to use. + :paramtype definition_version: str + :keyword parameters: The parameter values for the referenced policy rule. The keys are the + parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :keyword policy_definition_reference_id: A unique id (within the policy set definition) for + this policy definition reference. + :paramtype policy_definition_reference_id: str + :keyword group_names: The name of the groups that this policy definition reference belongs to. + :paramtype group_names: list[str] + """ + super().__init__(**kwargs) + self.policy_definition_id = policy_definition_id + self.definition_version = definition_version + self.latest_definition_version: Optional[str] = None + self.effective_definition_version: Optional[str] = None + self.parameters = parameters + self.policy_definition_reference_id = policy_definition_reference_id + self.group_names = group_names + + +class PolicyDefinitionVersion(_serialization.Model): + """The ID of the policy definition version. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition version. + :vartype id: str + :ivar name: The name of the policy definition version. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policyDefinitions/versions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :vartype mode: str + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + :ivar metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar version: The policy definition version in #.#.# format. + :vartype version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "mode": {"key": "properties.mode", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "version": {"key": "properties.version", "type": "str"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + mode: str = "Indexed", + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :paramtype mode: str + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + :keyword metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword version: The policy definition version in #.#.# format. + :paramtype version: str + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.mode = mode + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + self.metadata = metadata + self.parameters = parameters + self.version = version + + +class PolicyDefinitionVersionListResult(_serialization.Model): + """List of policy definition versions. + + :ivar value: An array of policy definitions versions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinitionVersion]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicyDefinitionVersion"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions versions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyExemption(_serialization.Model): + """The policy exemption. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar id: The ID of the policy exemption. + :vartype id: str + :ivar name: The name of the policy exemption. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policyExemptions). + :vartype type: str + :ivar policy_assignment_id: The ID of the policy assignment that is being exempted. Required. + :vartype policy_assignment_id: str + :ivar policy_definition_reference_ids: The policy definition reference ID list when the + associated policy assignment is an assignment of a policy set definition. + :vartype policy_definition_reference_ids: list[str] + :ivar exemption_category: The policy exemption category. Possible values are Waiver and + Mitigated. Required. Known values are: "Waiver" and "Mitigated". + :vartype exemption_category: str or ~azure.mgmt.resource.policy.models.ExemptionCategory + :ivar expires_on: The expiration date and time (in UTC ISO 8601 format yyyy-MM-ddTHH:mm:ssZ) of + the policy exemption. + :vartype expires_on: ~datetime.datetime + :ivar display_name: The display name of the policy exemption. + :vartype display_name: str + :ivar description: The description of the policy exemption. + :vartype description: str + :ivar metadata: The policy exemption metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar assignment_scope_validation: The option whether validate the exemption is at or under the + assignment scope. Known values are: "Default" and "DoNotValidate". + :vartype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + + _validation = { + "system_data": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "policy_assignment_id": {"required": True}, + "exemption_category": {"required": True}, + } + + _attribute_map = { + "system_data": {"key": "systemData", "type": "SystemData"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "policy_assignment_id": {"key": "properties.policyAssignmentId", "type": "str"}, + "policy_definition_reference_ids": {"key": "properties.policyDefinitionReferenceIds", "type": "[str]"}, + "exemption_category": {"key": "properties.exemptionCategory", "type": "str"}, + "expires_on": {"key": "properties.expiresOn", "type": "iso-8601"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "assignment_scope_validation": {"key": "properties.assignmentScopeValidation", "type": "str"}, + } + + def __init__( + self, + *, + policy_assignment_id: str, + exemption_category: Union[str, "_models.ExemptionCategory"], + policy_definition_reference_ids: Optional[list[str]] = None, + expires_on: Optional[datetime.datetime] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + assignment_scope_validation: Optional[Union[str, "_models.AssignmentScopeValidation"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_assignment_id: The ID of the policy assignment that is being exempted. + Required. + :paramtype policy_assignment_id: str + :keyword policy_definition_reference_ids: The policy definition reference ID list when the + associated policy assignment is an assignment of a policy set definition. + :paramtype policy_definition_reference_ids: list[str] + :keyword exemption_category: The policy exemption category. Possible values are Waiver and + Mitigated. Required. Known values are: "Waiver" and "Mitigated". + :paramtype exemption_category: str or ~azure.mgmt.resource.policy.models.ExemptionCategory + :keyword expires_on: The expiration date and time (in UTC ISO 8601 format yyyy-MM-ddTHH:mm:ssZ) + of the policy exemption. + :paramtype expires_on: ~datetime.datetime + :keyword display_name: The display name of the policy exemption. + :paramtype display_name: str + :keyword description: The description of the policy exemption. + :paramtype description: str + :keyword metadata: The policy exemption metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword assignment_scope_validation: The option whether validate the exemption is at or under + the assignment scope. Known values are: "Default" and "DoNotValidate". + :paramtype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + super().__init__(**kwargs) + self.system_data: Optional["_models.SystemData"] = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.policy_assignment_id = policy_assignment_id + self.policy_definition_reference_ids = policy_definition_reference_ids + self.exemption_category = exemption_category + self.expires_on = expires_on + self.display_name = display_name + self.description = description + self.metadata = metadata + self.resource_selectors = resource_selectors + self.assignment_scope_validation = assignment_scope_validation + + +class PolicyExemptionListResult(_serialization.Model): + """List of policy exemptions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of policy exemptions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyExemption] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyExemption]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[list["_models.PolicyExemption"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of policy exemptions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyExemption] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None + + +class PolicyExemptionUpdate(_serialization.Model): + """The policy exemption for Patch request. + + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar assignment_scope_validation: The option whether validate the exemption is at or under the + assignment scope. Known values are: "Default" and "DoNotValidate". + :vartype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + + _attribute_map = { + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "assignment_scope_validation": {"key": "properties.assignmentScopeValidation", "type": "str"}, + } + + def __init__( + self, + *, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + assignment_scope_validation: Optional[Union[str, "_models.AssignmentScopeValidation"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword assignment_scope_validation: The option whether validate the exemption is at or under + the assignment scope. Known values are: "Default" and "DoNotValidate". + :paramtype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + super().__init__(**kwargs) + self.resource_selectors = resource_selectors + self.assignment_scope_validation = assignment_scope_validation + + +class PolicySetDefinition(_serialization.Model): + """The policy set definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy set definition. + :vartype id: str + :ivar name: The name of the policy set definition. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policySetDefinitions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy set definition. Possible values are NotSpecified, + BuiltIn, Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and + "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar display_name: The display name of the policy set definition. + :vartype display_name: str + :ivar description: The policy set definition description. + :vartype description: str + :ivar metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The policy set definition parameters that can be used in policy definition + references. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar policy_definitions: An array of policy definition references. + :vartype policy_definitions: list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :ivar policy_definition_groups: The metadata describing groups of policy definition references + within the policy set definition. + :vartype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :ivar version: The policy set definition version in #.#.# format. + :vartype version: str + :ivar versions: A list of available versions for this policy set definition. + :vartype versions: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "policy_definitions": {"key": "properties.policyDefinitions", "type": "[PolicyDefinitionReference]"}, + "policy_definition_groups": {"key": "properties.policyDefinitionGroups", "type": "[PolicyDefinitionGroup]"}, + "version": {"key": "properties.version", "type": "str"}, + "versions": {"key": "properties.versions", "type": "[str]"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + policy_definitions: Optional[list["_models.PolicyDefinitionReference"]] = None, + policy_definition_groups: Optional[list["_models.PolicyDefinitionGroup"]] = None, + version: Optional[str] = None, + versions: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy set definition. Possible values are NotSpecified, + BuiltIn, Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and + "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword display_name: The display name of the policy set definition. + :paramtype display_name: str + :keyword description: The policy set definition description. + :paramtype description: str + :keyword metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The policy set definition parameters that can be used in policy definition + references. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword policy_definitions: An array of policy definition references. + :paramtype policy_definitions: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :keyword policy_definition_groups: The metadata describing groups of policy definition + references within the policy set definition. + :paramtype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :keyword version: The policy set definition version in #.#.# format. + :paramtype version: str + :keyword versions: A list of available versions for this policy set definition. + :paramtype versions: list[str] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.display_name = display_name + self.description = description + self.metadata = metadata + self.parameters = parameters + self.policy_definitions = policy_definitions + self.policy_definition_groups = policy_definition_groups + self.version = version + self.versions = versions + + +class PolicySetDefinitionListResult(_serialization.Model): + """List of policy set definitions. + + :ivar value: An array of policy set definitions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicySetDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicySetDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy set definitions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicySetDefinitionVersion(_serialization.Model): + """The policy set definition version. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy set definition version. + :vartype id: str + :ivar name: The name of the policy set definition version. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policySetDefinitions/versions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar display_name: The display name of the policy set definition. + :vartype display_name: str + :ivar description: The policy set definition description. + :vartype description: str + :ivar metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The policy set definition parameters that can be used in policy definition + references. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar policy_definitions: An array of policy definition references. + :vartype policy_definitions: list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :ivar policy_definition_groups: The metadata describing groups of policy definition references + within the policy set definition. + :vartype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :ivar version: The policy set definition version in #.#.# format. + :vartype version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "policy_definitions": {"key": "properties.policyDefinitions", "type": "[PolicyDefinitionReference]"}, + "policy_definition_groups": {"key": "properties.policyDefinitionGroups", "type": "[PolicyDefinitionGroup]"}, + "version": {"key": "properties.version", "type": "str"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + policy_definitions: Optional[list["_models.PolicyDefinitionReference"]] = None, + policy_definition_groups: Optional[list["_models.PolicyDefinitionGroup"]] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword display_name: The display name of the policy set definition. + :paramtype display_name: str + :keyword description: The policy set definition description. + :paramtype description: str + :keyword metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The policy set definition parameters that can be used in policy definition + references. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword policy_definitions: An array of policy definition references. + :paramtype policy_definitions: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :keyword policy_definition_groups: The metadata describing groups of policy definition + references within the policy set definition. + :paramtype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :keyword version: The policy set definition version in #.#.# format. + :paramtype version: str + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.display_name = display_name + self.description = description + self.metadata = metadata + self.parameters = parameters + self.policy_definitions = policy_definitions + self.policy_definition_groups = policy_definition_groups + self.version = version + + +class PolicySetDefinitionVersionListResult(_serialization.Model): + """List of policy set definition versions. + + :ivar value: An array of policy set definition versions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicySetDefinitionVersion]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicySetDefinitionVersion"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy set definition versions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyVariableColumn(_serialization.Model): + """The variable column. + + All required parameters must be populated in order to send to server. + + :ivar column_name: The name of this policy variable column. Required. + :vartype column_name: str + """ + + _validation = { + "column_name": {"required": True}, + } + + _attribute_map = { + "column_name": {"key": "columnName", "type": "str"}, + } + + def __init__(self, *, column_name: str, **kwargs: Any) -> None: + """ + :keyword column_name: The name of this policy variable column. Required. + :paramtype column_name: str + """ + super().__init__(**kwargs) + self.column_name = column_name + + +class PolicyVariableValueColumnValue(_serialization.Model): + """The name value tuple for this variable value column. + + All required parameters must be populated in order to send to server. + + :ivar column_name: Column name for the variable value. Required. + :vartype column_name: str + :ivar column_value: Column value for the variable value; this can be an integer, double, + boolean, null or a string. Required. + :vartype column_value: JSON + """ + + _validation = { + "column_name": {"required": True}, + "column_value": {"required": True}, + } + + _attribute_map = { + "column_name": {"key": "columnName", "type": "str"}, + "column_value": {"key": "columnValue", "type": "object"}, + } + + def __init__(self, *, column_name: str, column_value: JSON, **kwargs: Any) -> None: + """ + :keyword column_name: Column name for the variable value. Required. + :paramtype column_name: str + :keyword column_value: Column value for the variable value; this can be an integer, double, + boolean, null or a string. Required. + :paramtype column_value: JSON + """ + super().__init__(**kwargs) + self.column_name = column_name + self.column_value = column_value + + +class ResourceSelector(_serialization.Model): + """The resource selector to filter policies by resource properties. + + :ivar name: The name of the resource selector. + :vartype name: str + :ivar selectors: The list of the selector expressions. + :vartype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "selectors": {"key": "selectors", "type": "[Selector]"}, + } + + def __init__( + self, *, name: Optional[str] = None, selectors: Optional[list["_models.Selector"]] = None, **kwargs: Any + ) -> None: + """ + :keyword name: The name of the resource selector. + :paramtype name: str + :keyword selectors: The list of the selector expressions. + :paramtype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + super().__init__(**kwargs) + self.name = name + self.selectors = selectors + + +class ResourceTypeAliases(_serialization.Model): + """The resource type aliases definition. + + :ivar resource_type: The resource type name. + :vartype resource_type: str + :ivar aliases: The aliases for property names. + :vartype aliases: list[~azure.mgmt.resource.policy.models.Alias] + """ + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "aliases": {"key": "aliases", "type": "[Alias]"}, + } + + def __init__( + self, *, resource_type: Optional[str] = None, aliases: Optional[list["_models.Alias"]] = None, **kwargs: Any + ) -> None: + """ + :keyword resource_type: The resource type name. + :paramtype resource_type: str + :keyword aliases: The aliases for property names. + :paramtype aliases: list[~azure.mgmt.resource.policy.models.Alias] + """ + super().__init__(**kwargs) + self.resource_type = resource_type + self.aliases = aliases + + +class Selector(_serialization.Model): + """The selector expression. + + :ivar kind: The selector kind. Known values are: "resourceLocation", "resourceType", + "resourceWithoutLocation", and "policyDefinitionReferenceId". + :vartype kind: str or ~azure.mgmt.resource.policy.models.SelectorKind + :ivar in_property: The list of values to filter in. + :vartype in_property: list[str] + :ivar not_in: The list of values to filter out. + :vartype not_in: list[str] + """ + + _attribute_map = { + "kind": {"key": "kind", "type": "str"}, + "in_property": {"key": "in", "type": "[str]"}, + "not_in": {"key": "notIn", "type": "[str]"}, + } + + def __init__( + self, + *, + kind: Optional[Union[str, "_models.SelectorKind"]] = None, + in_property: Optional[list[str]] = None, + not_in: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword kind: The selector kind. Known values are: "resourceLocation", "resourceType", + "resourceWithoutLocation", and "policyDefinitionReferenceId". + :paramtype kind: str or ~azure.mgmt.resource.policy.models.SelectorKind + :keyword in_property: The list of values to filter in. + :paramtype in_property: list[str] + :keyword not_in: The list of values to filter out. + :paramtype not_in: list[str] + """ + super().__init__(**kwargs) + self.kind = kind + self.in_property = in_property + self.not_in = not_in + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class UserAssignedIdentitiesValue(_serialization.Model): + """UserAssignedIdentitiesValue. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar client_id: The client id of user assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.client_id: Optional[str] = None + + +class Variable(_serialization.Model): + """The variable. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar id: The ID of the variable. + :vartype id: str + :ivar name: The name of the variable. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/variables). + :vartype type: str + :ivar columns: Variable column definitions. Required. + :vartype columns: list[~azure.mgmt.resource.policy.models.PolicyVariableColumn] + """ + + _validation = { + "system_data": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "columns": {"required": True}, + } + + _attribute_map = { + "system_data": {"key": "systemData", "type": "SystemData"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "columns": {"key": "properties.columns", "type": "[PolicyVariableColumn]"}, + } + + def __init__(self, *, columns: list["_models.PolicyVariableColumn"], **kwargs: Any) -> None: + """ + :keyword columns: Variable column definitions. Required. + :paramtype columns: list[~azure.mgmt.resource.policy.models.PolicyVariableColumn] + """ + super().__init__(**kwargs) + self.system_data: Optional["_models.SystemData"] = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.columns = columns + + +class VariableListResult(_serialization.Model): + """List of variables. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of variables. + :vartype value: list[~azure.mgmt.resource.policy.models.Variable] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Variable]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[list["_models.Variable"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of variables. + :paramtype value: list[~azure.mgmt.resource.policy.models.Variable] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None + + +class VariableValue(_serialization.Model): + """The variable value. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar id: The ID of the variable. + :vartype id: str + :ivar name: The name of the variable. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/variables/values). + :vartype type: str + :ivar values: Variable value column value array. Required. + :vartype values: list[~azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue] + """ + + _validation = { + "system_data": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "values": {"required": True}, + } + + _attribute_map = { + "system_data": {"key": "systemData", "type": "SystemData"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "values": {"key": "properties.values", "type": "[PolicyVariableValueColumnValue]"}, + } + + def __init__(self, *, values: list["_models.PolicyVariableValueColumnValue"], **kwargs: Any) -> None: + """ + :keyword values: Variable value column value array. Required. + :paramtype values: list[~azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue] + """ + super().__init__(**kwargs) + self.system_data: Optional["_models.SystemData"] = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.values = values + + +class VariableValueListResult(_serialization.Model): + """List of variable values. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of variable values. + :vartype value: list[~azure.mgmt.resource.policy.models.VariableValue] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[VariableValue]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[list["_models.VariableValue"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of variable values. + :paramtype value: list[~azure.mgmt.resource.policy.models.VariableValue] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py new file mode 100644 index 000000000000..72647fa2a336 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AliasPathAttributes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The attributes of the token that the alias path is referring to.""" + + NONE = "None" + """The token that the alias path is referring to has no attributes.""" + MODIFIABLE = "Modifiable" + """The token that the alias path is referring to is modifiable by policies with 'modify' effect.""" + + +class AliasPathTokenType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the token that the alias path is referring to.""" + + NOT_SPECIFIED = "NotSpecified" + """The token type is not specified.""" + ANY = "Any" + """The token type can be anything.""" + STRING = "String" + """The token type is string.""" + OBJECT = "Object" + """The token type is object.""" + ARRAY = "Array" + """The token type is array.""" + INTEGER = "Integer" + """The token type is integer.""" + NUMBER = "Number" + """The token type is number.""" + BOOLEAN = "Boolean" + """The token type is boolean.""" + + +class AliasPatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of alias pattern.""" + + NOT_SPECIFIED = "NotSpecified" + """NotSpecified is not allowed.""" + EXTRACT = "Extract" + """Extract is the only allowed value.""" + + +class AliasType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the alias.""" + + NOT_SPECIFIED = "NotSpecified" + """Alias type is unknown (same as not providing alias type).""" + PLAIN_TEXT = "PlainText" + """Alias value is not secret.""" + MASK = "Mask" + """Alias value is secret.""" + + +class AssignmentScopeValidation(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The option whether validate the exemption is at or under the assignment scope.""" + + DEFAULT = "Default" + """This option will validate the exemption is at or under the assignment scope.""" + DO_NOT_VALIDATE = "DoNotValidate" + """This option will bypass the validation the exemption scope is at or under the policy assignment + scope.""" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class EnforcementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy assignment enforcement mode. Possible values are Default and DoNotEnforce.""" + + DEFAULT = "Default" + """The policy effect is enforced during resource creation or update.""" + DO_NOT_ENFORCE = "DoNotEnforce" + """The policy effect is not enforced during resource creation or update.""" + + +class ExemptionCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy exemption category. Possible values are Waiver and Mitigated.""" + + WAIVER = "Waiver" + """This category of exemptions usually means the scope is not applicable for the policy.""" + MITIGATED = "Mitigated" + """This category of exemptions usually means the mitigation actions have been applied to the + scope.""" + + +class OverrideKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The override kind.""" + + POLICY_EFFECT = "policyEffect" + """It will override the policy effect type.""" + + +class ParameterType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The data type of the parameter.""" + + STRING = "String" + ARRAY = "Array" + OBJECT = "Object" + BOOLEAN = "Boolean" + INTEGER = "Integer" + FLOAT = "Float" + DATE_TIME = "DateTime" + + +class PolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static.""" + + NOT_SPECIFIED = "NotSpecified" + BUILT_IN = "BuiltIn" + CUSTOM = "Custom" + STATIC = "Static" + + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type. This is the only required field when adding a system or user assigned + identity to a resource. + """ + + SYSTEM_ASSIGNED = "SystemAssigned" + """Indicates that a system assigned identity is associated with the resource.""" + USER_ASSIGNED = "UserAssigned" + """Indicates that a system assigned identity is associated with the resource.""" + NONE = "None" + """Indicates that no identity is associated with the resource or that the existing identity should + be removed.""" + + +class SelectorKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The selector kind.""" + + RESOURCE_LOCATION = "resourceLocation" + """The selector kind to filter policies by the resource location.""" + RESOURCE_TYPE = "resourceType" + """The selector kind to filter policies by the resource type.""" + RESOURCE_WITHOUT_LOCATION = "resourceWithoutLocation" + """The selector kind to filter policies by the resource without location.""" + POLICY_DEFINITION_REFERENCE_ID = "policyDefinitionReferenceId" + """The selector kind to filter policies by the policy definition reference ID.""" diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py new file mode 100644 index 000000000000..f302859689f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataPolicyManifestsOperations # type: ignore +from ._operations import PolicyDefinitionsOperations # type: ignore +from ._operations import PolicyDefinitionVersionsOperations # type: ignore +from ._operations import PolicySetDefinitionsOperations # type: ignore +from ._operations import PolicySetDefinitionVersionsOperations # type: ignore +from ._operations import PolicyAssignmentsOperations # type: ignore +from ._operations import PolicyExemptionsOperations # type: ignore +from ._operations import VariablesOperations # type: ignore +from ._operations import VariableValuesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataPolicyManifestsOperations", + "PolicyDefinitionsOperations", + "PolicyDefinitionVersionsOperations", + "PolicySetDefinitionsOperations", + "PolicySetDefinitionVersionsOperations", + "PolicyAssignmentsOperations", + "PolicyExemptionsOperations", + "VariablesOperations", + "VariableValuesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py new file mode 100644 index 000000000000..29e62121956e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py @@ -0,0 +1,10155 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import PolicyClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_data_policy_manifests_get_by_policy_mode_request( # pylint: disable=name-too-long + policy_mode: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/dataPolicyManifests/{policyMode}") + path_format_arguments = { + "policyMode": _SERIALIZER.url("policy_mode", policy_mode, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_policy_manifests_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/dataPolicyManifests") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_request( # pylint: disable=name-too-long + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_built_in_request( # pylint: disable=name-too-long + policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}") + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_request( + subscription_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_built_in_request( # pylint: disable=name-too-long + *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_all_builtins_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/listPolicyDefinitionVersions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_all_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/listPolicyDefinitionVersions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_all_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/listPolicyDefinitionVersions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_create_or_update_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_delete_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_get_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_get_built_in_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_request( # pylint: disable=name-too-long + policy_definition_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_built_in_request( # pylint: disable=name-too-long + policy_definition_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions" + ) + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_create_or_update_request( # pylint: disable=name-too-long + policy_set_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_delete_request( # pylint: disable=name-too-long + policy_set_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_get_request( + policy_set_definition_name: str, subscription_id: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_get_built_in_request( # pylint: disable=name-too-long + policy_set_definition_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + ) + path_format_arguments = { + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_list_request( # pylint: disable=name-too-long + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_list_built_in_request( # pylint: disable=name-too-long + *, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policySetDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_set_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_set_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_set_definition_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_all_builtins_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/listPolicySetDefinitionVersions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_all_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/listPolicySetDefinitionVersions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_all_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/listPolicySetDefinitionVersions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_create_or_update_request( # pylint: disable=name-too-long + policy_set_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_delete_request( # pylint: disable=name-too-long + policy_set_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_get_request( # pylint: disable=name-too-long + policy_set_definition_name: str, + policy_definition_version: str, + subscription_id: str, + *, + expand: Optional[str] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_get_built_in_request( # pylint: disable=name-too-long + policy_set_definition_name: str, policy_definition_version: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_request( # pylint: disable=name-too-long + policy_set_definition_name: str, + subscription_id: str, + *, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_built_in_request( # pylint: disable=name-too-long + policy_set_definition_name: str, *, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions" + ) + path_format_arguments = { + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + *, + expand: Optional[str] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_name: str, + policy_set_definition_name: str, + *, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_request( + scope: str, policy_assignment_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_update_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", pattern=r"^.+$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_request( + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_update_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_delete_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_create_or_update_request( # pylint: disable=name-too-long + scope: str, policy_exemption_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_get_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_update_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyExemptions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_for_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyExemptions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_for_resource_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyExemptions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyExemptions", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_delete_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_create_or_update_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_get_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_delete_request( + variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_create_or_update_request( # pylint: disable=name-too-long + variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_get_request( + variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_list_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DataPolicyManifestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`data_policy_manifests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_by_policy_mode(self, policy_mode: str, **kwargs: Any) -> _models.DataPolicyManifest: + """Retrieves a data policy manifest. + + This operation retrieves the data policy manifest with the given policy mode. + + :param policy_mode: The policy mode of the data policy manifest to get. Required. + :type policy_mode: str + :return: DataPolicyManifest or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.DataPolicyManifest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifest] = kwargs.pop("cls", None) + + _request = build_data_policy_manifests_get_by_policy_mode_request( + policy_mode=policy_mode, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataPolicyManifest", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.DataPolicyManifest"]: + """Retrieves data policy manifests. + + This operation retrieves a list of all the data policy manifests that match the optional given + $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not + provided, the unfiltered list includes all data policy manifests for data resource types. If + $filter=namespace is provided, the returned list only includes all data policy manifests that + have a namespace matching the provided value. + + :param filter: The filter to apply on the operation. Valid values for $filter are: "namespace + eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq + '{value}' is provided, the returned list only includes all data policy manifests that have a + namespace matching the provided value. Default value is None. + :type filter: str + :return: An iterator like instance of either DataPolicyManifest or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifestListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_data_policy_manifests_list_request( + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DataPolicyManifestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a subscription. + + This operation deletes the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a policy definition in a subscription. + + This operation retrieves the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a built-in policy definition. + + This operation retrieves the built-in policy definition with the given name. + + :param policy_definition_name: The name of the built-in policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: Union[_models.PolicyDefinition, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Retrieve a policy definition in a management group. + + This operation retrieves the policy definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinition"]: + """Retrieves policy definitions in a subscription. + + This operation retrieves a list of all the policy definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the subscription, including those that apply + directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list + only includes all policy definitions whose type match the {value}. Possible policyType values + are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, + the returned list only includes all policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinition"]: + """Retrieve built-in policy definitions. + + This operation retrieves a list of all the built-in policy definitions that match the optional + given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes + all built-in policy definitions whose type match the {value}. Possible policyType values are + NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the + returned list only includes all built-in policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_built_in_request( + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinition"]: + """Retrieve policy definitions in a management group. + + This operation retrieves a list of all the policy definitions in a given management group that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the management group, including those that + apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given management group. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is + provided, the returned list only includes all policy definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicyDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all_builtins(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all built-in policy definition versions. + + This operation lists all the built-in policy definition versions for all built-in policy + definitions. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions at management group scope. + + This operation lists all the policy definition versions for all policy definitions at the + management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions within a subscription. + + This operation lists all the policy definition versions for all policy definitions within a + subscription. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy definition version in a subscription. + + This operation deletes the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a policy definition version in a subscription. + + This operation retrieves the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a built-in policy definition version. + + This operation retrieves the built-in policy definition version with the given name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_built_in_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieve a policy definition version in a management group. + + This operation retrieves the policy definition version in the given management group with the + given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieves policy definition versions for a given policy definition in a subscription. + + This operation retrieves a list of all the policy definition versions for the given policy + definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve built-in policy definition versions. + + This operation retrieves a list of all the built-in policy definition versions for the given + policy definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_built_in_request( + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_name: str, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve policy definition versions in a management group policy definition. + + This operation retrieves a list of all the policy definition versions for the given policy + definition in the given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicySetDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_set_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given subscription with the given name. + + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given subscription with the given + name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a built in policy set definition. + + This operation retrieves the built-in policy set definition with the given name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinition"]: + """Retrieves the policy set definitions for a subscription. + + This operation retrieves a list of all the policy set definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy set definitions associated with the subscription, including those that + apply directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy set definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the + returned list only includes all policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinition"]: + """Retrieves built-in policy set definitions. + + This operation retrieves a list of all the built-in policy set definitions that match the + optional given $filter. If $filter='category -eq {value}' is provided, the returned list only + includes all built-in policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_built_in_request( + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: Union[_models.PolicySetDefinition, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_id: str, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicySetDefinition"]: + """Retrieves all policy set definitions in management group. + + This operation retrieves a list of all the policy set definitions in a given management group + that match the optional given $filter. Valid values for $filter are: 'atExactScope()', + 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered + list includes all policy set definitions associated with the management group, including those + that apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given management group. If $filter='policyType -eq {value}' is provided, the + returned list only includes all policy set definitions whose type match the {value}. Possible + policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is + provided, the returned list only includes all policy set definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicySetDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_set_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all_builtins(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all built-in policy set definition versions. + + This operation lists all the built-in policy set definition versions for all built-in policy + set definitions. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions at management group scope. + + This operation lists all the policy set definition versions for all policy set definitions at + the management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions within a subscription. + + This operation lists all the policy set definition versions for all policy set definitions + within a subscription. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinitionVersion + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a built in policy set definition version. + + This operation retrieves the built-in policy set definition version with the given name and + version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves the policy set definition versions for a given policy set definition in a + subscription. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves built-in policy set definition versions. + + This operation retrieves a list of all the built-in policy set definition versions for the + given built-in policy set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Is either a + PolicySetDefinitionVersion type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given management group with the + given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given management group with + the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves all policy set definition versions for a given policy set definition in a management + group. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition in a given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes a policy assignment, given its name and the scope it was created in. The + scope of a policy assignment is the part of its ID preceding + '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignment, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get( + self, scope: str, policy_assignment_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves a policy assignment. + + This operation retrieves a single policy assignment, given its name and the scope it was + created at. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_for_resource_group( + self, + resource_group_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource group. + + This operation retrieves the list of all policy assignments associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy assignments associated with the resource + group, including those that apply directly or apply from containing scopes, as well as any + applied to resources contained within the resource group. If $filter=atScope() is provided, the + returned list includes all policy assignments that apply to the resource group, which is + everything in the unfiltered list except those applied to resources contained within the + resource group. If $filter=atExactScope() is provided, the returned list only includes all + policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource. + + This operation retrieves the list of all policy assignments associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq + '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments + associated with the resource, including those that apply directly or from all containing + scopes, as well as any applied to resources contained within the resource. If $filter=atScope() + is provided, the returned list includes all policy assignments that apply to the resource, + which is everything in the unfiltered list except those applied to resources contained within + the resource. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value} + that apply to the resource. Three parameters plus the resource name are used to identify a + specific resource. If the resource is not part of a parent resource (the more common case), the + parent resource path should not be provided (or provided as ''). For example a web app could be + specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', + {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent + resource, then all parameters should be provided. For example a virtual machine DNS name could + be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a management group. + + This operation retrieves the list of all policy assignments applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or + 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes + all policy assignments that are assigned to the management group or the management group's + ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a subscription. + + This operation retrieves the list of all policy assignments associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the + unfiltered list includes all policy assignments associated with the subscription, including + those that apply directly or from management groups that contain the given subscription, as + well as any applied to objects contained within the subscription. If $filter=atScope() is + provided, the returned list includes all policy assignments that apply to the subscription, + which is everything in the unfiltered list except those applied to objects contained within the + subscription. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes the policy with the given ID. Policy assignment IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + formats for {scope} are: '/providers/Microsoft.Management/managementGroups/{managementGroup}' + (management group), '/subscriptions/{subscriptionId}' (subscription), + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' (resource group), or + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}' + (resource). + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_by_id( + self, policy_assignment_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves the policy assignment with the given ID. + + The operation retrieves the policy assignment with the given ID. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PolicyExemptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_exemptions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, policy_exemption_name: str, **kwargs: Any + ) -> None: + """Deletes a policy exemption. + + This operation deletes a policy exemption, given its name and the scope it was created in. The + scope of a policy exemption is the part of its ID preceding + '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_delete_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemption, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemption, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Is either a PolicyExemption type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemption") + + _request = build_policy_exemptions_create_or_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> _models.PolicyExemption: + """Retrieves a policy exemption. + + This operation retrieves a single policy exemption, given its name and the scope it was created + at. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_get_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemptionUpdate, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemptionUpdate, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Is either a + PolicyExemptionUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemptionUpdate") + + _request = build_policy_exemptions_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a subscription. + + This operation retrieves the list of all policy exemptions associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy exemptions associated with the subscription, + including those that apply directly or from management groups that contain the given + subscription, as well as any applied to objects contained within the subscription. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource group. + + This operation retrieves the list of all policy exemptions associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If + $filter is not provided, the unfiltered list includes all policy exemptions associated with the + resource group, including those that apply directly or apply from containing scopes, as well as + any applied to resources contained within the resource group. + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource. + + This operation retrieves the list of all policy exemptions associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or + 'policyAssignmentId eq '{value}''. If $filter is not provided, the unfiltered list includes all + policy exemptions associated with the resource, including those that apply directly or from all + containing scopes, as well as any applied to resources contained within the resource. Three + parameters plus the resource name are used to identify a specific resource. If the resource is + not part of a parent resource (the more common case), the parent resource path should not be + provided (or provided as ''). For example a web app could be specified as + ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == + 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all + parameters should be provided. For example a virtual machine DNS name could be specified as + ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a management group. + + This operation retrieves the list of all policy exemptions applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', + 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter=atScope() is provided, the + returned list includes all policy exemptions that are assigned to the management group or the + management group's ancestors. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class VariablesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`variables` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, variable_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a variable. + + This operation deletes a variable, given its name and the subscription it was created in. The + scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, variable_name: str, parameters: _models.Variable, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, variable_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, variable_name: str, parameters: Union[_models.Variable, IO[bytes]], **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, variable_name: str, **kwargs: Any) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the subscription it was created + at. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> None: + """Deletes a variable. + + This operation deletes a variable, given its name and the management group it was created in. + The scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: _models.Variable, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: Union[_models.Variable, IO[bytes]], + **kwargs: Any, + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_at_management_group(self, management_group_id: str, variable_name: str, **kwargs: Any) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the management group it was + created at. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Variable"]: + """Retrieves all variables that are at this subscription level. + + This operation retrieves the list of all variables associated with the given subscription. + + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group(self, management_group_id: str, **kwargs: Any) -> ItemPaged["_models.Variable"]: + """Retrieves all variables that are at this management group level. + + This operation retrieves the list of all variables applicable to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_for_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class VariableValuesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`variable_values` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the subscription it was created in, + and the variable it belongs to. The scope of a variable value is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, subscription it was created + at and the variable it's created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, variable_name: str, **kwargs: Any) -> ItemPaged["_models.VariableValue"]: + """List variable values for a variable. + + This operation retrieves the list of all variable values associated with the given variable + that is at a subscription level. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> ItemPaged["_models.VariableValue"]: + """List variable values at management group level. + + This operation retrieves the list of all variable values applicable the variable indicated at + the management group scope. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_for_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the management group it was created + in, and the variable it belongs to. The scope of a variable value is the part of its ID + preceding '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, management group it was + created at and the variable it's created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py new file mode 100644 index 000000000000..f65eaafdf6ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py @@ -0,0 +1,66 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.create_or_update( + policy_definition_name="ResourceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py new file mode 100644 index 000000000000..f55fd0ac68c4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py @@ -0,0 +1,82 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_advanced_params.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.create_or_update( + policy_definition_name="EventHubDiagnosticLogs", + parameters={ + "properties": { + "description": "Audit enabling of logs and retain them up to a year. This enables recreation of activity trails for investigation purposes when a security incident occurs or your network is compromised", + "displayName": "Event Hubs should have diagnostic logging enabled", + "metadata": {"category": "Event Hub"}, + "mode": "Indexed", + "parameters": { + "requiredRetentionDays": { + "allowedValues": [0, 30, 90, 180, 365], + "defaultValue": 365, + "metadata": { + "description": "The required diagnostic logs retention in days", + "displayName": "Required retention (days)", + }, + "type": "Integer", + } + }, + "policyRule": { + "if": {"equals": "Microsoft.EventHub/namespaces", "field": "type"}, + "then": { + "details": { + "existenceCondition": { + "allOf": [ + { + "equals": "true", + "field": "Microsoft.Insights/diagnosticSettings/logs[*].retentionPolicy.enabled", + }, + { + "equals": "[parameters('requiredRetentionDays')]", + "field": "Microsoft.Insights/diagnosticSettings/logs[*].retentionPolicy.days", + }, + ] + }, + "type": "Microsoft.Insights/diagnosticSettings", + }, + "effect": "AuditIfNotExists", + }, + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionAdvancedParams.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py new file mode 100644 index 000000000000..4f224ca49f83 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py @@ -0,0 +1,67 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.create_or_update_at_management_group( + management_group_id="MyManagementGroup", + policy_definition_name="ResourceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py new file mode 100644 index 000000000000..36cc0d983bd5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py @@ -0,0 +1,68 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.create_or_update( + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py new file mode 100644 index 000000000000..80c3c9d59f06 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py @@ -0,0 +1,69 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.create_or_update_at_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py new file mode 100644 index 000000000000..d866ff95c75a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_exemption.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.create_or_update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + parameters={ + "properties": { + "description": "Exempt demo cluster from limit sku", + "displayName": "Exempt demo cluster", + "exemptionCategory": "Waiver", + "metadata": {"reason": "Temporary exemption for a expensive VM demo"}, + "policyAssignmentId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement", + "policyDefinitionReferenceIds": ["Limit_Skus"], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/createOrUpdatePolicyExemption.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py new file mode 100644 index 000000000000..bbb5324203b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py @@ -0,0 +1,60 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_exemption_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.create_or_update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + parameters={ + "properties": { + "assignmentScopeValidation": "Default", + "description": "Exempt demo cluster from limit sku", + "displayName": "Exempt demo cluster", + "exemptionCategory": "Waiver", + "metadata": {"reason": "Temporary exemption for a expensive VM demo"}, + "policyAssignmentId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement", + "policyDefinitionReferenceIds": ["Limit_Skus"], + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/createOrUpdatePolicyExemptionWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py new file mode 100644 index 000000000000..b2c3fe5d6ce6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py @@ -0,0 +1,68 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.create_or_update( + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "parameters": { + "namePrefix": { + "defaultValue": "myPrefix", + "metadata": {"displayName": "Prefix to enforce on resource names"}, + "type": "String", + } + }, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "[parameters('namePrefix')]"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py new file mode 100644 index 000000000000..c4c885842014 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py @@ -0,0 +1,62 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py new file mode 100644 index 000000000000..031cbf732061 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py @@ -0,0 +1,70 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.create_or_update( + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "parameters": { + "namePrefix": { + "defaultValue": "myPrefix", + "metadata": {"displayName": "Prefix to enforce on resource names"}, + "type": "String", + } + }, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "[parameters('namePrefix')]"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py new file mode 100644 index 000000000000..2e03544efa6e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py @@ -0,0 +1,64 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.create_or_update_at_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py new file mode 100644 index 000000000000..7cb82d92e353 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py @@ -0,0 +1,77 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_with_groups.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.create_or_update( + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitionGroups": [ + { + "description": "Policies designed to control spend within a subscription.", + "displayName": "Cost Management Policies", + "name": "CostSaving", + }, + { + "description": "Policies that help enforce resource organization standards within a subscription.", + "displayName": "Organizational Policies", + "name": "Organizational", + }, + ], + "policyDefinitions": [ + { + "definitionVersion": "1.*.*", + "groupNames": ["CostSaving"], + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "definitionVersion": "1.*.*", + "groupNames": ["Organizational"], + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionWithGroups.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py new file mode 100644 index 000000000000..de0a96816915 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py @@ -0,0 +1,76 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_with_groups_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitionGroups": [ + { + "description": "Policies designed to control spend within a subscription.", + "displayName": "Cost Management Policies", + "name": "CostSaving", + }, + { + "description": "Policies that help enforce resource organization standards within a subscription.", + "displayName": "Organizational Policies", + "name": "Organizational", + }, + ], + "policyDefinitions": [ + { + "groupNames": ["CostSaving"], + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "groupNames": ["Organizational"], + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionWithGroupsAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py new file mode 100644 index 000000000000..89cbf2505824 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variables.create_or_update( + variable_name="DemoTestVariable", + parameters={"properties": {"columns": [{"columnName": "TestColumn"}]}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariable.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py new file mode 100644 index 000000000000..a075f0dbc3b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variables.create_or_update_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + parameters={"properties": {"columns": [{"columnName": "TestColumn"}]}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariableAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py new file mode 100644 index 000000000000..825d5a80e2ad --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py @@ -0,0 +1,51 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable_value.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variable_values.create_or_update( + variable_name="DemoTestVariable", + variable_value_name="TestValue", + parameters={ + "properties": { + "values": [ + {"columnName": "StringColumn", "columnValue": "SampleValue"}, + {"columnName": "IntegerColumn", "columnValue": 10}, + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariableValue.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py new file mode 100644 index 000000000000..2d97c14eea1f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable_value_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variable_values.create_or_update_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + variable_value_name="TestValue", + parameters={ + "properties": { + "values": [ + {"columnName": "StringColumn", "columnValue": "SampleValue"}, + {"columnName": "IntegerColumn", "columnValue": 10}, + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariableValueAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py new file mode 100644 index 000000000000..aa0bc1951369 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "metadata": {"assignedBy": "Special Someone"}, + "nonComplianceMessages": [{"message": "Resource names must start with 'DeptA' and end with '-LC'."}], + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignment.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py new file mode 100644 index 000000000000..94e796f90136 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + parameters={ + "properties": { + "definitionVersion": "1.*.*", + "description": "Allow only storage accounts of SKU Standard_GRS or Standard_LRS to be created", + "displayName": "Enforce storage account SKU", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Cheapskate Boss"}, + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py new file mode 100644 index 000000000000..a359570f354f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py @@ -0,0 +1,62 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_non_compliance_messages.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="securityInitAssignment", + parameters={ + "properties": { + "displayName": "Enforce security policies", + "nonComplianceMessages": [ + { + "message": "Resources must comply with all internal security policies. See for more info." + }, + { + "message": "Resource names must start with 'DeptA' and end with '-LC'.", + "policyDefinitionReferenceId": "10420126870854049575", + }, + { + "message": "Storage accounts must have firewall rules configured.", + "policyDefinitionReferenceId": "8572513655450389710", + }, + ], + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentNonComplianceMessages.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py new file mode 100644 index 000000000000..a76ddf832052 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py @@ -0,0 +1,55 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "eastus", + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Foo Bar"}, + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py new file mode 100644 index 000000000000..1909f06ca22a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py @@ -0,0 +1,55 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_identity_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "eastus", + "properties": { + "definitionVersion": "1.*.*", + "description": "Allow only storage accounts of SKU Standard_GRS or Standard_LRS to be created", + "displayName": "Enforce storage account SKU", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Cheapskate Boss"}, + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithIdentityById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py new file mode 100644 index 000000000000..8624ed97d9c0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py @@ -0,0 +1,58 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_overrides.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "description": "Limit the resource location and resource SKU", + "displayName": "Limit the resource location and resource SKU", + "metadata": {"assignedBy": "Special Someone"}, + "overrides": [ + { + "kind": "policyEffect", + "selectors": [{"in": ["Limit_Skus", "Limit_Locations"], "kind": "policyDefinitionReferenceId"}], + "value": "Audit", + } + ], + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithOverrides.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py new file mode 100644 index 000000000000..bf192cdef215 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py @@ -0,0 +1,57 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "description": "Limit the resource location and resource SKU", + "displayName": "Limit the resource location and resource SKU", + "metadata": {"assignedBy": "Special Someone"}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement", + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py new file mode 100644 index 000000000000..6a61c49b9bdd --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py @@ -0,0 +1,60 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {} + }, + }, + "location": "eastus", + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Foo Bar"}, + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithUserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py new file mode 100644 index 000000000000..832f7c603611 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_without_enforcement.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "enforcementMode": "DoNotEnforce", + "metadata": {"assignedBy": "Special Someone"}, + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithoutEnforcement.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py new file mode 100644 index 000000000000..c748e634c9d3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_assignment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.delete( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyAssignment.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py new file mode 100644 index 000000000000..f0d7b17c75f3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_assignment_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.delete_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyAssignmentById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py new file mode 100644 index 000000000000..b2cecb119bf3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_definitions.delete( + policy_definition_name="ResourceNaming", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py new file mode 100644 index 000000000000..aa2e5e3137b9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_definitions.delete_at_management_group( + management_group_id="MyManagementGroup", + policy_definition_name="ResourceNaming", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py new file mode 100644 index 000000000000..0e2c938ec759 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_definition_versions.delete( + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py new file mode 100644 index 000000000000..16268fe9a212 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_definition_versions.delete_at_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py new file mode 100644 index 000000000000..6d232dfe8c25 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_exemption.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_exemptions.delete( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/deletePolicyExemption.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py new file mode 100644 index 000000000000..3c96c8c9e3a6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_set_definitions.delete( + policy_set_definition_name="CostManagement", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py new file mode 100644 index 000000000000..6b1e72fb0f5c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_set_definitions.delete_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py new file mode 100644 index 000000000000..51bf0707e2c7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_set_definition_versions.delete( + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py new file mode 100644 index 000000000000..d6cfec176671 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_set_definition_versions.delete_at_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py new file mode 100644 index 000000000000..0cd87280bc4d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.variables.delete( + variable_name="DemoTestVariable", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariable.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py new file mode 100644 index 000000000000..5a7459323877 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.variables.delete_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariableAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py new file mode 100644 index 000000000000..bcf9ecab1c46 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable_value.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.variable_values.delete( + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariableValue.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py new file mode 100644 index 000000000000..1bfaf14fdce7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable_value_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.variable_values.delete_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariableValueAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py new file mode 100644 index 000000000000..95af387b1ee5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_built_in_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.get_built_in( + policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltInPolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py new file mode 100644 index 000000000000..5c7b4fe5f760 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_built_in_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.get_built_in( + policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltInPolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py new file mode 100644 index 000000000000..438e7e01b788 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_builtin_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.get_built_in( + policy_definition_name="7433c107-6db4-4ad1-b57a-a76dce0154a1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltinPolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py new file mode 100644 index 000000000000..a384f86096eb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_builtin_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.get_built_in( + policy_definition_name="7433c107-6db4-4ad1-b57a-a76dce0154a1", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltinPolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py new file mode 100644 index 000000000000..1a79eb31fd05 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_data_policy_manifest.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.data_policy_manifests.get_by_policy_mode( + policy_mode="Microsoft.KeyVault.Data", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2020-09-01/examples/getDataPolicyManifest.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py new file mode 100644 index 000000000000..190c5389fc5b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignment.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py new file mode 100644 index 000000000000..5f00fa2e9f29 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py new file mode 100644 index 000000000000..2bdaa63dd312 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py new file mode 100644 index 000000000000..0ffcba7ede4e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_identity_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithIdentityById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py new file mode 100644 index 000000000000..b24ae0f2bebc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_overrides.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithOverrides.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py new file mode 100644 index 000000000000..434e44b7f811 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py new file mode 100644 index 000000000000..070db7d59fc7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithUserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py new file mode 100644 index 000000000000..dd5ea749063f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.get( + policy_definition_name="ResourceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py new file mode 100644 index 000000000000..ab5a9b98371c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.get_at_management_group( + management_group_id="MyManagementGroup", + policy_definition_name="ResourceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py new file mode 100644 index 000000000000..9863b1360530 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.get( + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py new file mode 100644 index 000000000000..e7f872f16e23 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.get_at_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py new file mode 100644 index 000000000000..d9eae16f8384 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_exemption.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/getPolicyExemption.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py new file mode 100644 index 000000000000..7d75b672778b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_exemption_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/getPolicyExemptionWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py new file mode 100644 index 000000000000..a7446c1726ca --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.get( + policy_set_definition_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py new file mode 100644 index 000000000000..54d50c033243 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.get_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py new file mode 100644 index 000000000000..4446c6afc50a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.get( + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py new file mode 100644 index 000000000000..0360da53741c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.get_at_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py new file mode 100644 index 000000000000..a5c344300f51 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variables.get( + variable_name="DemoTestVariable", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariable.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py new file mode 100644 index 000000000000..fb8ba6ad8112 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variables.get_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariableAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py new file mode 100644 index 000000000000..8717e590786e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable_value.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variable_values.get( + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariableValue.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py new file mode 100644 index 000000000000..3e3ebaad39f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable_value_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variable_values.get_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariableValueAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py new file mode 100644 index 000000000000..c2cc14995a1d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_built_in_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_all_builtins() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllBuiltInPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py new file mode 100644 index 000000000000..570ea95e8229 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_built_in_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_all_builtins() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllBuiltInPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py new file mode 100644 index 000000000000..753966d70c72 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.list_all() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py new file mode 100644 index 000000000000..f0c37614e70a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_all_at_management_group( + management_group_name="MyManagementGroup", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicyDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py new file mode 100644 index 000000000000..a7dcddd6e26d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.list_all() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py new file mode 100644 index 000000000000..2a7dd0b58a56 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_set_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_all_at_management_group( + management_group_name="MyManagementGroup", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicySetDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py new file mode 100644 index 000000000000..dec4b4ba6314 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_built_in( + policy_definition_name="06a78e20-9358-41c9-923c-fb736d382a12", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py new file mode 100644 index 000000000000..382439ab8e77 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.list_built_in() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicyDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py new file mode 100644 index 000000000000..b6b3e257e496 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_built_in( + policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py new file mode 100644 index 000000000000..039c1d302864 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_set_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.list_built_in() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicySetDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py new file mode 100644 index 000000000000..72fa51318efa --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_data_policy_manifests.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.data_policy_manifests.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2020-09-01/examples/listDataPolicyManifests.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py new file mode 100644 index 000000000000..c4b8c81de645 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_data_policy_manifests_namespace_filter.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.data_policy_manifests.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2020-09-01/examples/listDataPolicyManifestsNamespaceFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py new file mode 100644 index 000000000000..bb41649763fd --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_assignments.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignments.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py new file mode 100644 index 000000000000..905dbd340aa4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.list_for_management_group( + management_group_id="TestManagementGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignmentsForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py new file mode 100644 index 000000000000..d466fd6f688c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py @@ -0,0 +1,47 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments_for_resource.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_assignments.list_for_resource( + resource_group_name="TestResourceGroup", + resource_provider_namespace="Microsoft.Compute", + parent_resource_path="virtualMachines/MyTestVm", + resource_type="domainNames", + resource_name="MyTestComputer.cloudapp.net", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignmentsForResource.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py new file mode 100644 index 000000000000..0ba2def195ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments_for_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_assignments.list_for_resource_group( + resource_group_name="TestResourceGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignmentsForResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py new file mode 100644 index 000000000000..1516a56dfd53 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.list( + policy_definition_name="ResourceNaming", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py new file mode 100644 index 000000000000..ed6f7b4025e5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_by_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py new file mode 100644 index 000000000000..998a00be3403 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py new file mode 100644 index 000000000000..e7575f9876b1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definitions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.list_by_management_group( + management_group_id="MyManagementGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py new file mode 100644 index 000000000000..873b7eed1370 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.list_for_management_group( + management_group_id="DevOrg", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py new file mode 100644 index 000000000000..8315c35c4114 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py @@ -0,0 +1,47 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_resource.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_exemptions.list_for_resource( + resource_group_name="TestResourceGroup", + resource_provider_namespace="Microsoft.Compute", + parent_resource_path="virtualMachines/MyTestVm", + resource_type="domainNames", + resource_name="MyTestComputer.cloudapp.net", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForResource.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py new file mode 100644 index 000000000000..787aea63be6d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_exemptions.list_for_resource_group( + resource_group_name="TestResourceGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py new file mode 100644 index 000000000000..1cf11b5e582c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_exemptions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py new file mode 100644 index 000000000000..7741de50dc73 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.list( + policy_set_definition_name="CostManagement", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py new file mode 100644 index 000000000000..21269baede20 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_by_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py new file mode 100644 index 000000000000..708600c70528 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py new file mode 100644 index 000000000000..b7160f81cb8d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definitions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.list_by_management_group( + management_group_id="MyManagementGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py new file mode 100644 index 000000000000..00f9d01c0e9c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variable_values_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variable_values.list_for_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariableValuesForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py new file mode 100644 index 000000000000..b6cbe7624322 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variable_values_for_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variable_values.list( + variable_name="DemoTestVariable", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariableValuesForSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py new file mode 100644 index 000000000000..e57dbb4f5283 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variables_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variables.list_for_management_group( + management_group_id="DevOrg", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariablesForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py new file mode 100644 index 000000000000..ef937a8c21ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variables_for_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variables.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariablesForSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py new file mode 100644 index 000000000000..976fddd0b378 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={"identity": {"type": "SystemAssigned"}, "location": "eastus"}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py new file mode 100644 index 000000000000..e2a6827f7227 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_identity_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + parameters={"identity": {"type": "SystemAssigned"}, "location": "eastus"}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithIdentityById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py new file mode 100644 index 000000000000..5d194a7b03f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py @@ -0,0 +1,54 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_overrides.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "overrides": [ + { + "kind": "policyEffect", + "selectors": [{"in": ["Limit_Skus", "Limit_Locations"], "kind": "policyDefinitionReferenceId"}], + "value": "Audit", + } + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithOverrides.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py new file mode 100644 index 000000000000..2cbbbb2310ce --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py new file mode 100644 index 000000000000..05ce73c9e30f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {} + }, + }, + "location": "eastus", + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithUserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py new file mode 100644 index 000000000000..88445a05426f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py @@ -0,0 +1,54 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_exemption_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + parameters={ + "properties": { + "assignmentScopeValidation": "Default", + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/updatePolicyExemptionWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py new file mode 100644 index 000000000000..e95ee7df4d34 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + policy_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + policy_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py new file mode 100644 index 000000000000..43e4371bb1ae --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyDataPolicyManifestsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_policy_manifests_get_by_policy_mode(self, resource_group): + response = self.client.data_policy_manifests.get_by_policy_mode( + policy_mode="str", + api_version="2020-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list( + api_version="2020-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py new file mode 100644 index 000000000000..d6bebc8340f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyDataPolicyManifestsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_policy_manifests_get_by_policy_mode(self, resource_group): + response = await self.client.data_policy_manifests.get_by_policy_mode( + policy_mode="str", + api_version="2020-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list( + api_version="2020-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py new file mode 100644 index 000000000000..57b128e19c3b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py @@ -0,0 +1,256 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyAssignmentsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_delete(self, resource_group): + response = self.client.policy_assignments.delete( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_create(self, resource_group): + response = self.client.policy_assignments.create( + scope="str", + policy_assignment_name="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_get(self, resource_group): + response = self.client.policy_assignments.get( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_update(self, resource_group): + response = self.client.policy_assignments.update( + scope="str", + policy_assignment_name="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_resource(self, resource_group): + response = self.client.policy_assignments.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_management_group(self, resource_group): + response = self.client.policy_assignments.list_for_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_delete_by_id(self, resource_group): + response = self.client.policy_assignments.delete_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_create_by_id(self, resource_group): + response = self.client.policy_assignments.create_by_id( + policy_assignment_id="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_get_by_id(self, resource_group): + response = self.client.policy_assignments.get_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_update_by_id(self, resource_group): + response = self.client.policy_assignments.update_by_id( + policy_assignment_id="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py new file mode 100644 index 000000000000..4dc457727160 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py @@ -0,0 +1,257 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyAssignmentsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_delete(self, resource_group): + response = await self.client.policy_assignments.delete( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_create(self, resource_group): + response = await self.client.policy_assignments.create( + scope="str", + policy_assignment_name="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_get(self, resource_group): + response = await self.client.policy_assignments.get( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_update(self, resource_group): + response = await self.client.policy_assignments.update( + scope="str", + policy_assignment_name="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_resource(self, resource_group): + response = self.client.policy_assignments.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_management_group(self, resource_group): + response = self.client.policy_assignments.list_for_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_delete_by_id(self, resource_group): + response = await self.client.policy_assignments.delete_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_create_by_id(self, resource_group): + response = await self.client.policy_assignments.create_by_id( + policy_assignment_id="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_get_by_id(self, resource_group): + response = await self.client.policy_assignments.get_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_update_by_id(self, resource_group): + response = await self.client.policy_assignments.update_by_id( + policy_assignment_id="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py new file mode 100644 index 000000000000..784e7081ae10 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py @@ -0,0 +1,239 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = self.client.policy_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all(self, resource_group): + response = self.client.policy_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_create_or_update(self, resource_group): + response = self.client.policy_definition_versions.create_or_update( + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_delete(self, resource_group): + response = self.client.policy_definition_versions.delete( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_get(self, resource_group): + response = self.client.policy_definition_versions.get( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_get_built_in(self, resource_group): + response = self.client.policy_definition_versions.get_built_in( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_delete_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.delete_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_get_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.get_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list(self, resource_group): + response = self.client.policy_definition_versions.list( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_definition_versions.list_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_definition_versions.list_by_management_group( + management_group_name="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py new file mode 100644 index 000000000000..24f06e299437 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py @@ -0,0 +1,240 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = await self.client.policy_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all(self, resource_group): + response = await self.client.policy_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_create_or_update(self, resource_group): + response = await self.client.policy_definition_versions.create_or_update( + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_delete(self, resource_group): + response = await self.client.policy_definition_versions.delete( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_get(self, resource_group): + response = await self.client.policy_definition_versions.get( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_get_built_in(self, resource_group): + response = await self.client.policy_definition_versions.get_built_in( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_delete_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.delete_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_get_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.get_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list(self, resource_group): + response = self.client.policy_definition_versions.list( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_definition_versions.list_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_definition_versions.list_by_management_group( + management_group_name="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py new file mode 100644 index 000000000000..2b1965134aa6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py @@ -0,0 +1,200 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_create_or_update(self, resource_group): + response = self.client.policy_definitions.create_or_update( + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_delete(self, resource_group): + response = self.client.policy_definitions.delete( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_get(self, resource_group): + response = self.client.policy_definitions.get( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_get_built_in(self, resource_group): + response = self.client.policy_definitions.get_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_delete_at_management_group(self, resource_group): + response = self.client.policy_definitions.delete_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_get_at_management_group(self, resource_group): + response = self.client.policy_definitions.get_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py new file mode 100644 index 000000000000..bbec542c33e9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py @@ -0,0 +1,201 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_create_or_update(self, resource_group): + response = await self.client.policy_definitions.create_or_update( + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_delete(self, resource_group): + response = await self.client.policy_definitions.delete( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_get(self, resource_group): + response = await self.client.policy_definitions.get( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_get_built_in(self, resource_group): + response = await self.client.policy_definitions.get_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_delete_at_management_group(self, resource_group): + response = await self.client.policy_definitions.delete_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_get_at_management_group(self, resource_group): + response = await self.client.policy_definitions.get_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py new file mode 100644 index 000000000000..cfaf494b118a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyExemptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_delete(self, resource_group): + response = self.client.policy_exemptions.delete( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_create_or_update(self, resource_group): + response = self.client.policy_exemptions.create_or_update( + scope="str", + policy_exemption_name="str", + parameters={ + "exemptionCategory": "str", + "policyAssignmentId": "str", + "assignmentScopeValidation": "str", + "description": "str", + "displayName": "str", + "expiresOn": "2020-02-20 00:00:00", + "id": "str", + "metadata": {}, + "name": "str", + "policyDefinitionReferenceIds": ["str"], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_get(self, resource_group): + response = self.client.policy_exemptions.get( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_update(self, resource_group): + response = self.client.policy_exemptions.update( + scope="str", + policy_exemption_name="str", + parameters={ + "assignmentScopeValidation": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list( + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_resource(self, resource_group): + response = self.client.policy_exemptions.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_management_group(self, resource_group): + response = self.client.policy_exemptions.list_for_management_group( + management_group_id="str", + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py new file mode 100644 index 000000000000..7960bd6eb74c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py @@ -0,0 +1,141 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyExemptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_delete(self, resource_group): + response = await self.client.policy_exemptions.delete( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_create_or_update(self, resource_group): + response = await self.client.policy_exemptions.create_or_update( + scope="str", + policy_exemption_name="str", + parameters={ + "exemptionCategory": "str", + "policyAssignmentId": "str", + "assignmentScopeValidation": "str", + "description": "str", + "displayName": "str", + "expiresOn": "2020-02-20 00:00:00", + "id": "str", + "metadata": {}, + "name": "str", + "policyDefinitionReferenceIds": ["str"], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_get(self, resource_group): + response = await self.client.policy_exemptions.get( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_update(self, resource_group): + response = await self.client.policy_exemptions.update( + scope="str", + policy_exemption_name="str", + parameters={ + "assignmentScopeValidation": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list( + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_resource(self, resource_group): + response = self.client.policy_exemptions.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_management_group(self, resource_group): + response = self.client.policy_exemptions.list_for_management_group( + management_group_id="str", + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py new file mode 100644 index 000000000000..62b7d7194bf4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py @@ -0,0 +1,275 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all_builtins(self, resource_group): + response = self.client.policy_set_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all(self, resource_group): + response = self.client.policy_set_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_create_or_update(self, resource_group): + response = self.client.policy_set_definition_versions.create_or_update( + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_delete(self, resource_group): + response = self.client.policy_set_definition_versions.delete( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_get(self, resource_group): + response = self.client.policy_set_definition_versions.get( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_get_built_in(self, resource_group): + response = self.client.policy_set_definition_versions.get_built_in( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list(self, resource_group): + response = self.client.policy_set_definition_versions.list( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_set_definition_versions.list_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_delete_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.delete_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_get_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.get_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.list_by_management_group( + management_group_name="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py new file mode 100644 index 000000000000..8bcf4cb39fb2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py @@ -0,0 +1,276 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all_builtins(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_create_or_update(self, resource_group): + response = await self.client.policy_set_definition_versions.create_or_update( + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_delete(self, resource_group): + response = await self.client.policy_set_definition_versions.delete( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_get(self, resource_group): + response = await self.client.policy_set_definition_versions.get( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_get_built_in(self, resource_group): + response = await self.client.policy_set_definition_versions.get_built_in( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list(self, resource_group): + response = self.client.policy_set_definition_versions.list( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_set_definition_versions.list_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_delete_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.delete_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_get_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.get_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.list_by_management_group( + management_group_name="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py new file mode 100644 index 000000000000..640d2c73344f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py @@ -0,0 +1,236 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_create_or_update(self, resource_group): + response = self.client.policy_set_definitions.create_or_update( + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_delete(self, resource_group): + response = self.client.policy_set_definitions.delete( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_get(self, resource_group): + response = self.client.policy_set_definitions.get( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_get_built_in(self, resource_group): + response = self.client.policy_set_definitions.get_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_delete_at_management_group(self, resource_group): + response = self.client.policy_set_definitions.delete_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_get_at_management_group(self, resource_group): + response = self.client.policy_set_definitions.get_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py new file mode 100644 index 000000000000..f1fdf201e272 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py @@ -0,0 +1,237 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_create_or_update(self, resource_group): + response = await self.client.policy_set_definitions.create_or_update( + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_delete(self, resource_group): + response = await self.client.policy_set_definitions.delete( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_get(self, resource_group): + response = await self.client.policy_set_definitions.get( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_get_built_in(self, resource_group): + response = await self.client.policy_set_definitions.get_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_delete_at_management_group(self, resource_group): + response = await self.client.policy_set_definitions.delete_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_get_at_management_group(self, resource_group): + response = await self.client.policy_set_definitions.get_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py new file mode 100644 index 000000000000..e09d26b19c57 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py @@ -0,0 +1,145 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariableValuesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_delete(self, resource_group): + response = self.client.variable_values.delete( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_create_or_update(self, resource_group): + response = self.client.variable_values.create_or_update( + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_get(self, resource_group): + response = self.client.variable_values.get( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_list(self, resource_group): + response = self.client.variable_values.list( + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_list_for_management_group(self, resource_group): + response = self.client.variable_values.list_for_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_delete_at_management_group(self, resource_group): + response = self.client.variable_values.delete_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_create_or_update_at_management_group(self, resource_group): + response = self.client.variable_values.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_get_at_management_group(self, resource_group): + response = self.client.variable_values.get_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py new file mode 100644 index 000000000000..a7bbd7e294fc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py @@ -0,0 +1,146 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariableValuesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_delete(self, resource_group): + response = await self.client.variable_values.delete( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_create_or_update(self, resource_group): + response = await self.client.variable_values.create_or_update( + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_get(self, resource_group): + response = await self.client.variable_values.get( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_list(self, resource_group): + response = self.client.variable_values.list( + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_list_for_management_group(self, resource_group): + response = self.client.variable_values.list_for_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_delete_at_management_group(self, resource_group): + response = await self.client.variable_values.delete_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_create_or_update_at_management_group(self, resource_group): + response = await self.client.variable_values.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_get_at_management_group(self, resource_group): + response = await self.client.variable_values.get_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py new file mode 100644 index 000000000000..19f865cb0853 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariablesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_delete(self, resource_group): + response = self.client.variables.delete( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_create_or_update(self, resource_group): + response = self.client.variables.create_or_update( + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_get(self, resource_group): + response = self.client.variables.get( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_delete_at_management_group(self, resource_group): + response = self.client.variables.delete_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_create_or_update_at_management_group(self, resource_group): + response = self.client.variables.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_get_at_management_group(self, resource_group): + response = self.client.variables.get_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_list(self, resource_group): + response = self.client.variables.list( + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_list_for_management_group(self, resource_group): + response = self.client.variables.list_for_management_group( + management_group_id="str", + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py new file mode 100644 index 000000000000..df7d9ca1d591 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariablesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_delete(self, resource_group): + response = await self.client.variables.delete( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_create_or_update(self, resource_group): + response = await self.client.variables.create_or_update( + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_get(self, resource_group): + response = await self.client.variables.get( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_delete_at_management_group(self, resource_group): + response = await self.client.variables.delete_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_create_or_update_at_management_group(self, resource_group): + response = await self.client.variables.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_get_at_management_group(self, resource_group): + response = await self.client.variables.get_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_list(self, resource_group): + response = self.client.variables.list( + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_list_for_management_group(self, resource_group): + response = self.client.variables.list_for_management_group( + management_group_id="str", + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/pyproject.toml b/sdk/resources/azure-mgmt-resource-policy/pyproject.toml new file mode 100644 index 000000000000..ff0ca2bde3e1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-policy" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Policy Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.policy._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-policy" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Policy Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "PolicyClient" diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/conftest.py b/sdk/resources/azure-mgmt-resource-policy/tests/conftest.py new file mode 100644 index 000000000000..e95ee7df4d34 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + policy_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + policy_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py new file mode 100644 index 000000000000..e1034e05a9e4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyDataPolicyManifestsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py new file mode 100644 index 000000000000..4bd2212ec9d2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyDataPolicyManifestsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py new file mode 100644 index 000000000000..9a8da64bdf27 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyAssignmentsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert result + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py new file mode 100644 index 000000000000..861288ebd0b6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyAssignmentsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert result + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list() + result = [r for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py new file mode 100644 index 000000000000..6b887d662066 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = await self.client.policy_definition_versions.list_all_builtins() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all(self, resource_group): + response = await self.client.policy_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py new file mode 100644 index 000000000000..3dcbfa780bc5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = self.client.policy_definition_versions.list_all_builtins() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all(self, resource_group): + response = self.client.policy_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py new file mode 100644 index 000000000000..32d331e6880d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list() + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py new file mode 100644 index 000000000000..93ec578d34c9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list() + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py new file mode 100644 index 000000000000..dc2337c35ac7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyExemptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list() + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py new file mode 100644 index 000000000000..3d078607ddfc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyExemptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list() + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py new file mode 100644 index 000000000000..ea1f58d602ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py new file mode 100644 index 000000000000..aa04e847393c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all(self, resource_group): + response = self.client.policy_set_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py new file mode 100644 index 000000000000..d86dc3a171c7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list() + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py new file mode 100644 index 000000000000..7db6084261de --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list() + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py new file mode 100644 index 000000000000..9682e9c9c549 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyVariablesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_list(self, resource_group): + response = self.client.variables.list() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py new file mode 100644 index 000000000000..e70731415786 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyVariablesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_list(self, resource_group): + response = self.client.variables.list() + result = [r for r in response] + assert response From 1debcff1694e2673ed8cb4d1e610bbf2a3c9b017 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:28:05 -0800 Subject: [PATCH 57/84] [AutoRelease] t2-resource-managedapplications-2026-02-05-91819(can only be merged by SDK owner) (#45020) * code and test * update --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 --- .../CHANGELOG.md | 7 + .../LICENSE | 21 + .../MANIFEST.in | 8 + .../README.md | 61 + .../_metadata.json | 11 + .../apiview-properties.json | 110 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../resource/managedapplications/__init__.py | 32 + .../_application_client.py | 144 + .../managedapplications/_configuration.py | 75 + .../resource/managedapplications/_patch.py | 21 + .../managedapplications/_utils/__init__.py | 6 + .../_utils/serialization.py | 2041 ++++++++++ .../managedapplications/_utils/utils.py | 25 + .../resource/managedapplications/_version.py | 9 + .../managedapplications/aio/__init__.py | 29 + .../aio/_application_client.py | 149 + .../managedapplications/aio/_configuration.py | 75 + .../managedapplications/aio/_patch.py | 21 + .../aio/operations/__init__.py | 30 + .../aio/operations/_operations.py | 2856 +++++++++++++ .../aio/operations/_patch.py | 21 + .../managedapplications/models/__init__.py | 138 + .../models/_application_client_enums.py | 138 + .../managedapplications/models/_models_py3.py | 2141 ++++++++++ .../managedapplications/models/_patch.py | 21 + .../operations/__init__.py | 30 + .../operations/_operations.py | 3622 +++++++++++++++++ .../managedapplications/operations/_patch.py | 21 + .../resource/managedapplications/py.typed | 1 + .../dev_requirements.txt | 5 + .../create_or_update_application.py | 51 + ...create_or_update_application_definition.py | 53 + .../delete_application_definition.py | 42 + .../generated_samples/get_application.py | 43 + .../get_application_definition.py | 43 + ...plication_definitions_by_resource_group.py | 43 + .../list_applications_by_resource_group.py | 43 + .../list_solutions_operations.py | 41 + .../generated_samples/update_application.py | 43 + .../generated_tests/conftest.py | 35 + .../generated_tests/test_application.py | 29 + ...tion_application_definitions_operations.py | 148 + ...pplication_definitions_operations_async.py | 171 + ...est_application_applications_operations.py | 218 + ...plication_applications_operations_async.py | 255 ++ .../generated_tests/test_application_async.py | 30 + ...est_application_jit_requests_operations.py | 108 + ...plication_jit_requests_operations_async.py | 111 + .../pyproject.toml | 87 + .../tests/conftest.py | 35 + ...ation_definitions_operations_async_test.py | 29 + ...application_definitions_operations_test.py | 28 + ...tion_applications_operations_async_test.py | 36 + ...pplication_applications_operations_test.py | 35 + .../tests/test_application_async_test.py | 27 + ...tion_jit_requests_operations_async_test.py | 36 + ...pplication_jit_requests_operations_test.py | 35 + .../tests/test_application_test.py | 26 + 61 files changed, 13753 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/README.md create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_application_client.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/utils.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_application_client.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_application_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/delete_application_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application_definition.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_application_definitions_by_resource_group.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_applications_by_resource_group.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_solutions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/update_application.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_async.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_test.py diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-managedapplications/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/LICENSE b/sdk/resources/azure-mgmt-resource-managedapplications/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/MANIFEST.in b/sdk/resources/azure-mgmt-resource-managedapplications/MANIFEST.in new file mode 100644 index 000000000000..bc8cabf8b114 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/managedapplications/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/README.md b/sdk/resources/azure-mgmt-resource-managedapplications/README.md new file mode 100644 index 000000000000..afc0be85f0ca --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Managedapplications Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-managedapplications +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.managedapplications import ApplicationClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ApplicationClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Managedapplications Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/_metadata.json b/sdk/resources/azure-mgmt-resource-managedapplications/_metadata.json new file mode 100644 index 000000000000..09b94c7740f1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Solutions/managedapplications/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-managedapplications-2019-07 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Solutions/managedapplications/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/apiview-properties.json b/sdk/resources/azure-mgmt-resource-managedapplications/apiview-properties.json new file mode 100644 index 000000000000..5d3288c256ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/apiview-properties.json @@ -0,0 +1,110 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.managedapplications.models.Resource": null, + "azure.mgmt.resource.managedapplications.models.GenericResource": null, + "azure.mgmt.resource.managedapplications.models.Application": null, + "azure.mgmt.resource.managedapplications.models.ApplicationArtifact": null, + "azure.mgmt.resource.managedapplications.models.ApplicationAuthorization": null, + "azure.mgmt.resource.managedapplications.models.ApplicationBillingDetailsDefinition": null, + "azure.mgmt.resource.managedapplications.models.ApplicationClientDetails": null, + "azure.mgmt.resource.managedapplications.models.ApplicationDefinition": null, + "azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifact": null, + "azure.mgmt.resource.managedapplications.models.ApplicationDefinitionListResult": null, + "azure.mgmt.resource.managedapplications.models.ApplicationDeploymentPolicy": null, + "azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy": null, + "azure.mgmt.resource.managedapplications.models.ApplicationListResult": null, + "azure.mgmt.resource.managedapplications.models.ApplicationManagementPolicy": null, + "azure.mgmt.resource.managedapplications.models.ApplicationNotificationEndpoint": null, + "azure.mgmt.resource.managedapplications.models.ApplicationNotificationPolicy": null, + "azure.mgmt.resource.managedapplications.models.ApplicationPackageContact": null, + "azure.mgmt.resource.managedapplications.models.ApplicationPackageLockingPolicyDefinition": null, + "azure.mgmt.resource.managedapplications.models.ApplicationPackageSupportUrls": null, + "azure.mgmt.resource.managedapplications.models.ApplicationPatchable": null, + "azure.mgmt.resource.managedapplications.models.ApplicationPolicy": null, + "azure.mgmt.resource.managedapplications.models.ApplicationPropertiesPatchable": null, + "azure.mgmt.resource.managedapplications.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.managedapplications.models.ErrorDetail": null, + "azure.mgmt.resource.managedapplications.models.ErrorResponse": null, + "azure.mgmt.resource.managedapplications.models.Identity": null, + "azure.mgmt.resource.managedapplications.models.JitApproverDefinition": null, + "azure.mgmt.resource.managedapplications.models.JitAuthorizationPolicies": null, + "azure.mgmt.resource.managedapplications.models.JitRequestDefinition": null, + "azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult": null, + "azure.mgmt.resource.managedapplications.models.JitRequestPatchable": null, + "azure.mgmt.resource.managedapplications.models.JitSchedulingPolicy": null, + "azure.mgmt.resource.managedapplications.models.Operation": null, + "azure.mgmt.resource.managedapplications.models.OperationAutoGenerated": null, + "azure.mgmt.resource.managedapplications.models.OperationDisplay": null, + "azure.mgmt.resource.managedapplications.models.OperationDisplayAutoGenerated": null, + "azure.mgmt.resource.managedapplications.models.OperationListResult": null, + "azure.mgmt.resource.managedapplications.models.Plan": null, + "azure.mgmt.resource.managedapplications.models.PlanPatchable": null, + "azure.mgmt.resource.managedapplications.models.Sku": null, + "azure.mgmt.resource.managedapplications.models.UserAssignedResourceIdentity": null, + "azure.mgmt.resource.managedapplications.models.Origin": null, + "azure.mgmt.resource.managedapplications.models.ActionType": null, + "azure.mgmt.resource.managedapplications.models.JitApproverType": null, + "azure.mgmt.resource.managedapplications.models.ApplicationArtifactName": null, + "azure.mgmt.resource.managedapplications.models.ApplicationArtifactType": null, + "azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifactName": null, + "azure.mgmt.resource.managedapplications.models.ApplicationLockLevel": null, + "azure.mgmt.resource.managedapplications.models.DeploymentMode": null, + "azure.mgmt.resource.managedapplications.models.ApplicationManagementMode": null, + "azure.mgmt.resource.managedapplications.models.ResourceIdentityType": null, + "azure.mgmt.resource.managedapplications.models.ProvisioningState": null, + "azure.mgmt.resource.managedapplications.models.JitApprovalMode": null, + "azure.mgmt.resource.managedapplications.models.JitSchedulingType": null, + "azure.mgmt.resource.managedapplications.models.JitRequestState": null, + "azure.mgmt.resource.managedapplications.ApplicationClient.list_operations": null, + "azure.mgmt.resource.managedapplications.aio.ApplicationClient.list_operations": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.get": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.get": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.begin_delete": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.begin_delete": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.begin_create_or_update": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.begin_create_or_update": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.update": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.update": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.list_by_resource_group": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.list_by_resource_group": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.list_by_subscription": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.list_by_subscription": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.get_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.get_by_id": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.begin_delete_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.begin_delete_by_id": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.begin_create_or_update_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.begin_create_or_update_by_id": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.update_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.update_by_id": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationsOperations.begin_refresh_permissions": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations.begin_refresh_permissions": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.get": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.get": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.begin_delete": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.begin_delete": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.begin_create_or_update": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.begin_create_or_update": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.list_by_resource_group": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.list_by_resource_group": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.get_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.get_by_id": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.begin_delete_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.begin_delete_by_id": null, + "azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations.begin_create_or_update_by_id": null, + "azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations.begin_create_or_update_by_id": null, + "azure.mgmt.resource.managedapplications.operations.JitRequestsOperations.get": null, + "azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations.get": null, + "azure.mgmt.resource.managedapplications.operations.JitRequestsOperations.begin_create_or_update": null, + "azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations.begin_create_or_update": null, + "azure.mgmt.resource.managedapplications.operations.JitRequestsOperations.update": null, + "azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations.update": null, + "azure.mgmt.resource.managedapplications.operations.JitRequestsOperations.delete": null, + "azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations.delete": null, + "azure.mgmt.resource.managedapplications.operations.JitRequestsOperations.list_by_subscription": null, + "azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations.list_by_subscription": null, + "azure.mgmt.resource.managedapplications.operations.JitRequestsOperations.list_by_resource_group": null, + "azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations.list_by_resource_group": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/__init__.py new file mode 100644 index 000000000000..b5f21c6322ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._application_client import ApplicationClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_application_client.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_application_client.py new file mode 100644 index 000000000000..ee457fd90589 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_application_client.py @@ -0,0 +1,144 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import ApplicationClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + ApplicationDefinitionsOperations, + ApplicationsOperations, + JitRequestsOperations, + _ApplicationClientOperationsMixin, +) + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ApplicationClient(_ApplicationClientOperationsMixin): + """Application Client. + + :ivar applications: ApplicationsOperations operations + :vartype applications: + azure.mgmt.resource.managedapplications.operations.ApplicationsOperations + :ivar application_definitions: ApplicationDefinitionsOperations operations + :vartype application_definitions: + azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations + :ivar jit_requests: JitRequestsOperations operations + :vartype jit_requests: azure.mgmt.resource.managedapplications.operations.JitRequestsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ApplicationClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.applications = ApplicationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.application_definitions = ApplicationDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.jit_requests = JitRequestsOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_configuration.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_configuration.py new file mode 100644 index 000000000000..9eb5c66530a8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ApplicationClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ApplicationClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2019-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-managedapplications/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_patch.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/utils.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/utils.py new file mode 100644 index 000000000000..39b612f39a9b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_utils/utils.py @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, TYPE_CHECKING, TypeVar + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_version.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/__init__.py new file mode 100644 index 000000000000..0a6c2b1f1f57 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._application_client import ApplicationClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_application_client.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_application_client.py new file mode 100644 index 000000000000..880f4363acbe --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_application_client.py @@ -0,0 +1,149 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ApplicationClientConfiguration +from .operations import ( + ApplicationDefinitionsOperations, + ApplicationsOperations, + JitRequestsOperations, + _ApplicationClientOperationsMixin, +) + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ApplicationClient(_ApplicationClientOperationsMixin): + """Application Client. + + :ivar applications: ApplicationsOperations operations + :vartype applications: + azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations + :ivar application_definitions: ApplicationDefinitionsOperations operations + :vartype application_definitions: + azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations + :ivar jit_requests: JitRequestsOperations operations + :vartype jit_requests: + azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ApplicationClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.applications = ApplicationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.application_definitions = ApplicationDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.jit_requests = JitRequestsOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_configuration.py new file mode 100644 index 000000000000..bb3025ac2da9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ApplicationClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ApplicationClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2019-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-managedapplications/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_patch.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/__init__.py new file mode 100644 index 000000000000..cdaa4d1b9b46 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/__init__.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _ApplicationClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import ApplicationsOperations # type: ignore +from ._operations import ApplicationDefinitionsOperations # type: ignore +from ._operations import JitRequestsOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationsOperations", + "ApplicationDefinitionsOperations", + "JitRequestsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_operations.py new file mode 100644 index 000000000000..1271ab5d8fdf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_operations.py @@ -0,0 +1,2856 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import ClientMixinABC +from ...operations._operations import ( + build_application_definitions_create_or_update_by_id_request, + build_application_definitions_create_or_update_request, + build_application_definitions_delete_by_id_request, + build_application_definitions_delete_request, + build_application_definitions_get_by_id_request, + build_application_definitions_get_request, + build_application_definitions_list_by_resource_group_request, + build_application_list_operations_request, + build_applications_create_or_update_by_id_request, + build_applications_create_or_update_request, + build_applications_delete_by_id_request, + build_applications_delete_request, + build_applications_get_by_id_request, + build_applications_get_request, + build_applications_list_by_resource_group_request, + build_applications_list_by_subscription_request, + build_applications_refresh_permissions_request, + build_applications_update_by_id_request, + build_applications_update_request, + build_jit_requests_create_or_update_request, + build_jit_requests_delete_request, + build_jit_requests_get_request, + build_jit_requests_list_by_resource_group_request, + build_jit_requests_list_by_subscription_request, + build_jit_requests_update_request, +) +from .._configuration import ApplicationClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class _ApplicationClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], ApplicationClientConfiguration] +): + + @distributed_trace + def list_operations(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Solutions REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_application_list_operations_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ApplicationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.aio.ApplicationClient`'s + :attr:`applications` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, resource_group_name: str, application_name: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + _request = build_applications_get_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_applications_delete_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + application_name: str, + parameters: Union[_models.Application, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + _request = build_applications_create_or_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: Union[_models.Application, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + application_name=application_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.Application].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.Application]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + async def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[_models.ApplicationPatchable] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[Union[_models.ApplicationPatchable, IO[bytes]]] = None, + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + ApplicationPatchable type or a IO[bytes] type. Default value is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable or + IO[bytes] + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if parameters else None + cls: ClsType[Optional[_models.Application]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if parameters else None + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "ApplicationPatchable") + else: + _json = None + + _request = build_applications_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncItemPaged["_models.Application"]: + """Gets all the applications within a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_applications_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.Application"]: + """Gets all the applications within a subscription. + + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_applications_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_by_id(self, application_id: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + _request = build_applications_get_by_id_request( + application_id=application_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_by_id_initial(self, application_id: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_applications_delete_by_id_request( + application_id=application_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_by_id(self, application_id: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_by_id_initial( + application_id=application_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _create_or_update_by_id_initial( + self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + _request = build_applications_create_or_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update_by_id( + self, + application_id: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update_by_id( + self, application_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_by_id( + self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_by_id_initial( + application_id=application_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.Application].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.Application]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + async def update_by_id( + self, + application_id: str, + parameters: Optional[_models.Application] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_by_id( + self, + application_id: str, + parameters: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_by_id( + self, application_id: str, parameters: Optional[Union[_models.Application, IO[bytes]]] = None, **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + Application type or a IO[bytes] type. Default value is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if parameters else None + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if parameters else None + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "Application") + else: + _json = None + + _request = build_applications_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _refresh_permissions_initial( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_applications_refresh_permissions_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_refresh_permissions( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Refresh Permissions for application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._refresh_permissions_initial( + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + +class ApplicationDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.aio.ApplicationClient`'s + :attr:`application_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + _request = build_application_definitions_get_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_application_definitions_delete_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition to delete. + Required. + :type application_definition_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + _request = build_application_definitions_create_or_update_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ApplicationDefinition].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ApplicationDefinition]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.ApplicationDefinition"]: + """Lists the managed application definitions in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_application_definitions_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + _request = build_application_definitions_get_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_by_id_initial( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_application_definitions_delete_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_by_id_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _create_or_update_by_id_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + _request = build_application_definitions_create_or_update_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_by_id_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ApplicationDefinition].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ApplicationDefinition]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class JitRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.aio.ApplicationClient`'s + :attr:`jit_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> _models.JitRequestDefinition: + """Gets the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + _request = build_jit_requests_get_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestDefinition") + + _request = build_jit_requests_create_or_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.JitRequestDefinition].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.JitRequestDefinition]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + async def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestPatchable, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestPatchable, IO[bytes]], + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestPatchable type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable or + IO[bytes] + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestPatchable") + + _request = build_jit_requests_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> None: + """Deletes the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_jit_requests_delete_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def list_by_subscription(self, **kwargs: Any) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the subscription. + + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + _request = build_jit_requests_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + _request = build_jit_requests_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/__init__.py new file mode 100644 index 000000000000..4e1a1fb629ae --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/__init__.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Application, + ApplicationArtifact, + ApplicationAuthorization, + ApplicationBillingDetailsDefinition, + ApplicationClientDetails, + ApplicationDefinition, + ApplicationDefinitionArtifact, + ApplicationDefinitionListResult, + ApplicationDeploymentPolicy, + ApplicationJitAccessPolicy, + ApplicationListResult, + ApplicationManagementPolicy, + ApplicationNotificationEndpoint, + ApplicationNotificationPolicy, + ApplicationPackageContact, + ApplicationPackageLockingPolicyDefinition, + ApplicationPackageSupportUrls, + ApplicationPatchable, + ApplicationPolicy, + ApplicationPropertiesPatchable, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + GenericResource, + Identity, + JitApproverDefinition, + JitAuthorizationPolicies, + JitRequestDefinition, + JitRequestDefinitionListResult, + JitRequestPatchable, + JitSchedulingPolicy, + Operation, + OperationAutoGenerated, + OperationDisplay, + OperationDisplayAutoGenerated, + OperationListResult, + Plan, + PlanPatchable, + Resource, + Sku, + UserAssignedResourceIdentity, +) + +from ._application_client_enums import ( # type: ignore + ActionType, + ApplicationArtifactName, + ApplicationArtifactType, + ApplicationDefinitionArtifactName, + ApplicationLockLevel, + ApplicationManagementMode, + DeploymentMode, + JitApprovalMode, + JitApproverType, + JitRequestState, + JitSchedulingType, + Origin, + ProvisioningState, + ResourceIdentityType, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Application", + "ApplicationArtifact", + "ApplicationAuthorization", + "ApplicationBillingDetailsDefinition", + "ApplicationClientDetails", + "ApplicationDefinition", + "ApplicationDefinitionArtifact", + "ApplicationDefinitionListResult", + "ApplicationDeploymentPolicy", + "ApplicationJitAccessPolicy", + "ApplicationListResult", + "ApplicationManagementPolicy", + "ApplicationNotificationEndpoint", + "ApplicationNotificationPolicy", + "ApplicationPackageContact", + "ApplicationPackageLockingPolicyDefinition", + "ApplicationPackageSupportUrls", + "ApplicationPatchable", + "ApplicationPolicy", + "ApplicationPropertiesPatchable", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "GenericResource", + "Identity", + "JitApproverDefinition", + "JitAuthorizationPolicies", + "JitRequestDefinition", + "JitRequestDefinitionListResult", + "JitRequestPatchable", + "JitSchedulingPolicy", + "Operation", + "OperationAutoGenerated", + "OperationDisplay", + "OperationDisplayAutoGenerated", + "OperationListResult", + "Plan", + "PlanPatchable", + "Resource", + "Sku", + "UserAssignedResourceIdentity", + "ActionType", + "ApplicationArtifactName", + "ApplicationArtifactType", + "ApplicationDefinitionArtifactName", + "ApplicationLockLevel", + "ApplicationManagementMode", + "DeploymentMode", + "JitApprovalMode", + "JitApproverType", + "JitRequestState", + "JitSchedulingType", + "Origin", + "ProvisioningState", + "ResourceIdentityType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_application_client_enums.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_application_client_enums.py new file mode 100644 index 000000000000..ce93a089dad3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_application_client_enums.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class ApplicationArtifactName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application artifact name.""" + + NOT_SPECIFIED = "NotSpecified" + VIEW_DEFINITION = "ViewDefinition" + AUTHORIZATIONS = "Authorizations" + CUSTOM_ROLE_DEFINITION = "CustomRoleDefinition" + + +class ApplicationArtifactType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application artifact type.""" + + NOT_SPECIFIED = "NotSpecified" + TEMPLATE = "Template" + CUSTOM = "Custom" + + +class ApplicationDefinitionArtifactName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application artifact name.""" + + NOT_SPECIFIED = "NotSpecified" + APPLICATION_RESOURCE_TEMPLATE = "ApplicationResourceTemplate" + CREATE_UI_DEFINITION = "CreateUiDefinition" + MAIN_TEMPLATE_PARAMETERS = "MainTemplateParameters" + + +class ApplicationLockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application lock level.""" + + CAN_NOT_DELETE = "CanNotDelete" + READ_ONLY = "ReadOnly" + NONE = "None" + + +class ApplicationManagementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The management mode.""" + + NOT_SPECIFIED = "NotSpecified" + UNMANAGED = "Unmanaged" + MANAGED = "Managed" + + +class DeploymentMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The deployment mode.""" + + NOT_SPECIFIED = "NotSpecified" + INCREMENTAL = "Incremental" + COMPLETE = "Complete" + + +class JitApprovalMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The Jit approval mode.""" + + NOT_SPECIFIED = "NotSpecified" + AUTO_APPROVE = "AutoApprove" + MANUAL_APPROVE = "ManualApprove" + + +class JitApproverType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The approver type.""" + + USER = "user" + GROUP = "group" + + +class JitRequestState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The JIT request state.""" + + NOT_SPECIFIED = "NotSpecified" + PENDING = "Pending" + APPROVED = "Approved" + DENIED = "Denied" + FAILED = "Failed" + CANCELED = "Canceled" + EXPIRED = "Expired" + TIMEOUT = "Timeout" + + +class JitSchedulingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The JIT request scheduling type.""" + + NOT_SPECIFIED = "NotSpecified" + ONCE = "Once" + RECURRING = "Recurring" + + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". + """ + + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provisioning status of the managed application.""" + + NOT_SPECIFIED = "NotSpecified" + ACCEPTED = "Accepted" + RUNNING = "Running" + READY = "Ready" + CREATING = "Creating" + CREATED = "Created" + DELETING = "Deleting" + DELETED = "Deleted" + CANCELED = "Canceled" + FAILED = "Failed" + SUCCEEDED = "Succeeded" + UPDATING = "Updating" + + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type.""" + + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" + NONE = "None" diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_models_py3.py new file mode 100644 index 000000000000..c9b872b4907d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_models_py3.py @@ -0,0 +1,2141 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +import datetime +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class Resource(_serialization.Model): + """Resource information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, location: Optional[str] = None, tags: Optional[dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.location = location + self.tags = tags + + +class GenericResource(Resource): + """Resource information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku + """ + super().__init__(location=location, tags=tags, **kwargs) + self.managed_by = managed_by + self.sku = sku + + +class Application(GenericResource): + """Information about managed application. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku + :ivar plan: The plan information. + :vartype plan: ~azure.mgmt.resource.managedapplications.models.Plan + :ivar kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. Required. + :vartype kind: str + :ivar identity: The identity of the resource. + :vartype identity: ~azure.mgmt.resource.managedapplications.models.Identity + :ivar managed_resource_group_id: The managed resource group Id. + :vartype managed_resource_group_id: str + :ivar application_definition_id: The fully qualified path of managed application definition Id. + :vartype application_definition_id: str + :ivar parameters: Name and value pairs that define the managed application parameters. It can + be a JObject or a well formed JSON string. + :vartype parameters: JSON + :ivar outputs: Name and value pairs that define the managed application outputs. + :vartype outputs: JSON + :ivar provisioning_state: The managed application provisioning state. Known values are: + "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", + "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.models.ProvisioningState + :ivar billing_details: The managed application billing details. + :vartype billing_details: + ~azure.mgmt.resource.managedapplications.models.ApplicationBillingDetailsDefinition + :ivar jit_access_policy: The managed application Jit access policy. + :vartype jit_access_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy + :ivar publisher_tenant_id: The publisher tenant Id. + :vartype publisher_tenant_id: str + :ivar authorizations: The read-only authorizations property that is retrieved from the + application package. + :vartype authorizations: + list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] + :ivar management_mode: The managed application management mode. Known values are: + "NotSpecified", "Unmanaged", and "Managed". + :vartype management_mode: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode + :ivar customer_support: The read-only customer support property that is retrieved from the + application package. + :vartype customer_support: + ~azure.mgmt.resource.managedapplications.models.ApplicationPackageContact + :ivar support_urls: The read-only support URLs property that is retrieved from the application + package. + :vartype support_urls: + ~azure.mgmt.resource.managedapplications.models.ApplicationPackageSupportUrls + :ivar artifacts: The collection of managed application artifacts. + :vartype artifacts: list[~azure.mgmt.resource.managedapplications.models.ApplicationArtifact] + :ivar created_by: The client entity that created the JIT request. + :vartype created_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails + :ivar updated_by: The client entity that last updated the JIT request. + :vartype updated_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True, "pattern": r"^[-\w\._,\(\)]+$"}, + "outputs": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "billing_details": {"readonly": True}, + "publisher_tenant_id": {"readonly": True}, + "authorizations": {"readonly": True}, + "management_mode": {"readonly": True}, + "customer_support": {"readonly": True}, + "support_urls": {"readonly": True}, + "artifacts": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "plan": {"key": "plan", "type": "Plan"}, + "kind": {"key": "kind", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "managed_resource_group_id": {"key": "properties.managedResourceGroupId", "type": "str"}, + "application_definition_id": {"key": "properties.applicationDefinitionId", "type": "str"}, + "parameters": {"key": "properties.parameters", "type": "object"}, + "outputs": {"key": "properties.outputs", "type": "object"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "billing_details": {"key": "properties.billingDetails", "type": "ApplicationBillingDetailsDefinition"}, + "jit_access_policy": {"key": "properties.jitAccessPolicy", "type": "ApplicationJitAccessPolicy"}, + "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, + "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, + "management_mode": {"key": "properties.managementMode", "type": "str"}, + "customer_support": {"key": "properties.customerSupport", "type": "ApplicationPackageContact"}, + "support_urls": {"key": "properties.supportUrls", "type": "ApplicationPackageSupportUrls"}, + "artifacts": {"key": "properties.artifacts", "type": "[ApplicationArtifact]"}, + "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, + "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, + } + + def __init__( + self, + *, + kind: str, + location: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + plan: Optional["_models.Plan"] = None, + identity: Optional["_models.Identity"] = None, + managed_resource_group_id: Optional[str] = None, + application_definition_id: Optional[str] = None, + parameters: Optional[JSON] = None, + jit_access_policy: Optional["_models.ApplicationJitAccessPolicy"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku + :keyword plan: The plan information. + :paramtype plan: ~azure.mgmt.resource.managedapplications.models.Plan + :keyword kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. Required. + :paramtype kind: str + :keyword identity: The identity of the resource. + :paramtype identity: ~azure.mgmt.resource.managedapplications.models.Identity + :keyword managed_resource_group_id: The managed resource group Id. + :paramtype managed_resource_group_id: str + :keyword application_definition_id: The fully qualified path of managed application definition + Id. + :paramtype application_definition_id: str + :keyword parameters: Name and value pairs that define the managed application parameters. It + can be a JObject or a well formed JSON string. + :paramtype parameters: JSON + :keyword jit_access_policy: The managed application Jit access policy. + :paramtype jit_access_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy + """ + super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) + self.plan = plan + self.kind = kind + self.identity = identity + self.managed_resource_group_id = managed_resource_group_id + self.application_definition_id = application_definition_id + self.parameters = parameters + self.outputs: Optional[JSON] = None + self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None + self.billing_details: Optional["_models.ApplicationBillingDetailsDefinition"] = None + self.jit_access_policy = jit_access_policy + self.publisher_tenant_id: Optional[str] = None + self.authorizations: Optional[list["_models.ApplicationAuthorization"]] = None + self.management_mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None + self.customer_support: Optional["_models.ApplicationPackageContact"] = None + self.support_urls: Optional["_models.ApplicationPackageSupportUrls"] = None + self.artifacts: Optional[list["_models.ApplicationArtifact"]] = None + self.created_by: Optional["_models.ApplicationClientDetails"] = None + self.updated_by: Optional["_models.ApplicationClientDetails"] = None + + +class ApplicationArtifact(_serialization.Model): + """Managed application artifact. + + All required parameters must be populated in order to send to server. + + :ivar name: The managed application artifact name. Required. Known values are: "NotSpecified", + "ViewDefinition", "Authorizations", and "CustomRoleDefinition". + :vartype name: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactName + :ivar uri: The managed application artifact blob uri. Required. + :vartype uri: str + :ivar type: The managed application artifact type. Required. Known values are: "NotSpecified", + "Template", and "Custom". + :vartype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType + """ + + _validation = { + "name": {"required": True}, + "uri": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "uri": {"key": "uri", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Union[str, "_models.ApplicationArtifactName"], + uri: str, + type: Union[str, "_models.ApplicationArtifactType"], + **kwargs: Any + ) -> None: + """ + :keyword name: The managed application artifact name. Required. Known values are: + "NotSpecified", "ViewDefinition", "Authorizations", and "CustomRoleDefinition". + :paramtype name: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactName + :keyword uri: The managed application artifact blob uri. Required. + :paramtype uri: str + :keyword type: The managed application artifact type. Required. Known values are: + "NotSpecified", "Template", and "Custom". + :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType + """ + super().__init__(**kwargs) + self.name = name + self.uri = uri + self.type = type + + +class ApplicationAuthorization(_serialization.Model): + """The managed application provider authorization. + + All required parameters must be populated in order to send to server. + + :ivar principal_id: The provider's principal identifier. This is the identity that the provider + will use to call ARM to manage the managed application resources. Required. + :vartype principal_id: str + :ivar role_definition_id: The provider's role definition identifier. This role will define all + the permissions that the provider must have on the managed application's container resource + group. This role definition cannot have permission to delete the resource group. Required. + :vartype role_definition_id: str + """ + + _validation = { + "principal_id": {"required": True}, + "role_definition_id": {"required": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + } + + def __init__(self, *, principal_id: str, role_definition_id: str, **kwargs: Any) -> None: + """ + :keyword principal_id: The provider's principal identifier. This is the identity that the + provider will use to call ARM to manage the managed application resources. Required. + :paramtype principal_id: str + :keyword role_definition_id: The provider's role definition identifier. This role will define + all the permissions that the provider must have on the managed application's container resource + group. This role definition cannot have permission to delete the resource group. Required. + :paramtype role_definition_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + + +class ApplicationBillingDetailsDefinition(_serialization.Model): + """Managed application billing details definition. + + :ivar resource_usage_id: The managed application resource usage Id. + :vartype resource_usage_id: str + """ + + _attribute_map = { + "resource_usage_id": {"key": "resourceUsageId", "type": "str"}, + } + + def __init__(self, *, resource_usage_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword resource_usage_id: The managed application resource usage Id. + :paramtype resource_usage_id: str + """ + super().__init__(**kwargs) + self.resource_usage_id = resource_usage_id + + +class ApplicationClientDetails(_serialization.Model): + """The application client details to track the entity creating/updating the managed app resource. + + :ivar oid: The client Oid. + :vartype oid: str + :ivar puid: The client Puid. + :vartype puid: str + :ivar application_id: The client application Id. + :vartype application_id: str + """ + + _attribute_map = { + "oid": {"key": "oid", "type": "str"}, + "puid": {"key": "puid", "type": "str"}, + "application_id": {"key": "applicationId", "type": "str"}, + } + + def __init__( + self, + *, + oid: Optional[str] = None, + puid: Optional[str] = None, + application_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword oid: The client Oid. + :paramtype oid: str + :keyword puid: The client Puid. + :paramtype puid: str + :keyword application_id: The client application Id. + :paramtype application_id: str + """ + super().__init__(**kwargs) + self.oid = oid + self.puid = puid + self.application_id = application_id + + +class ApplicationDefinition(GenericResource): + """Information about managed application definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku + :ivar lock_level: The managed application lock level. Required. Known values are: + "CanNotDelete", "ReadOnly", and "None". + :vartype lock_level: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationLockLevel + :ivar display_name: The managed application definition display name. + :vartype display_name: str + :ivar is_enabled: A value indicating whether the package is enabled or not. + :vartype is_enabled: bool + :ivar authorizations: The managed application provider authorizations. + :vartype authorizations: + list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] + :ivar artifacts: The collection of managed application artifacts. The portal will use the files + specified as artifacts to construct the user experience of creating a managed application from + a managed application definition. + :vartype artifacts: + list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifact] + :ivar description: The managed application definition description. + :vartype description: str + :ivar package_file_uri: The managed application definition package file Uri. Use this element. + :vartype package_file_uri: str + :ivar main_template: The inline main template json which has resources to be provisioned. It + can be a JObject or well-formed JSON string. + :vartype main_template: JSON + :ivar create_ui_definition: The createUiDefinition json for the backing template with + Microsoft.Solutions/applications resource. It can be a JObject or well-formed JSON string. + :vartype create_ui_definition: JSON + :ivar notification_policy: The managed application notification policy. + :vartype notification_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationNotificationPolicy + :ivar locking_policy: The managed application locking policy. + :vartype locking_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationPackageLockingPolicyDefinition + :ivar deployment_policy: The managed application deployment policy. + :vartype deployment_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationDeploymentPolicy + :ivar management_policy: The managed application management policy that determines publisher's + access to the managed resource group. + :vartype management_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationManagementPolicy + :ivar policies: The managed application provider policies. + :vartype policies: list[~azure.mgmt.resource.managedapplications.models.ApplicationPolicy] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "lock_level": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "lock_level": {"key": "properties.lockLevel", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, + "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, + "artifacts": {"key": "properties.artifacts", "type": "[ApplicationDefinitionArtifact]"}, + "description": {"key": "properties.description", "type": "str"}, + "package_file_uri": {"key": "properties.packageFileUri", "type": "str"}, + "main_template": {"key": "properties.mainTemplate", "type": "object"}, + "create_ui_definition": {"key": "properties.createUiDefinition", "type": "object"}, + "notification_policy": {"key": "properties.notificationPolicy", "type": "ApplicationNotificationPolicy"}, + "locking_policy": {"key": "properties.lockingPolicy", "type": "ApplicationPackageLockingPolicyDefinition"}, + "deployment_policy": {"key": "properties.deploymentPolicy", "type": "ApplicationDeploymentPolicy"}, + "management_policy": {"key": "properties.managementPolicy", "type": "ApplicationManagementPolicy"}, + "policies": {"key": "properties.policies", "type": "[ApplicationPolicy]"}, + } + + def __init__( + self, + *, + lock_level: Union[str, "_models.ApplicationLockLevel"], + location: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + display_name: Optional[str] = None, + is_enabled: Optional[bool] = None, + authorizations: Optional[list["_models.ApplicationAuthorization"]] = None, + artifacts: Optional[list["_models.ApplicationDefinitionArtifact"]] = None, + description: Optional[str] = None, + package_file_uri: Optional[str] = None, + main_template: Optional[JSON] = None, + create_ui_definition: Optional[JSON] = None, + notification_policy: Optional["_models.ApplicationNotificationPolicy"] = None, + locking_policy: Optional["_models.ApplicationPackageLockingPolicyDefinition"] = None, + deployment_policy: Optional["_models.ApplicationDeploymentPolicy"] = None, + management_policy: Optional["_models.ApplicationManagementPolicy"] = None, + policies: Optional[list["_models.ApplicationPolicy"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku + :keyword lock_level: The managed application lock level. Required. Known values are: + "CanNotDelete", "ReadOnly", and "None". + :paramtype lock_level: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationLockLevel + :keyword display_name: The managed application definition display name. + :paramtype display_name: str + :keyword is_enabled: A value indicating whether the package is enabled or not. + :paramtype is_enabled: bool + :keyword authorizations: The managed application provider authorizations. + :paramtype authorizations: + list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] + :keyword artifacts: The collection of managed application artifacts. The portal will use the + files specified as artifacts to construct the user experience of creating a managed application + from a managed application definition. + :paramtype artifacts: + list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifact] + :keyword description: The managed application definition description. + :paramtype description: str + :keyword package_file_uri: The managed application definition package file Uri. Use this + element. + :paramtype package_file_uri: str + :keyword main_template: The inline main template json which has resources to be provisioned. It + can be a JObject or well-formed JSON string. + :paramtype main_template: JSON + :keyword create_ui_definition: The createUiDefinition json for the backing template with + Microsoft.Solutions/applications resource. It can be a JObject or well-formed JSON string. + :paramtype create_ui_definition: JSON + :keyword notification_policy: The managed application notification policy. + :paramtype notification_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationNotificationPolicy + :keyword locking_policy: The managed application locking policy. + :paramtype locking_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationPackageLockingPolicyDefinition + :keyword deployment_policy: The managed application deployment policy. + :paramtype deployment_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationDeploymentPolicy + :keyword management_policy: The managed application management policy that determines + publisher's access to the managed resource group. + :paramtype management_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationManagementPolicy + :keyword policies: The managed application provider policies. + :paramtype policies: list[~azure.mgmt.resource.managedapplications.models.ApplicationPolicy] + """ + super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) + self.lock_level = lock_level + self.display_name = display_name + self.is_enabled = is_enabled + self.authorizations = authorizations + self.artifacts = artifacts + self.description = description + self.package_file_uri = package_file_uri + self.main_template = main_template + self.create_ui_definition = create_ui_definition + self.notification_policy = notification_policy + self.locking_policy = locking_policy + self.deployment_policy = deployment_policy + self.management_policy = management_policy + self.policies = policies + + +class ApplicationDefinitionArtifact(_serialization.Model): + """Application definition artifact. + + All required parameters must be populated in order to send to server. + + :ivar name: The managed application definition artifact name. Required. Known values are: + "NotSpecified", "ApplicationResourceTemplate", "CreateUiDefinition", and + "MainTemplateParameters". + :vartype name: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifactName + :ivar uri: The managed application definition artifact blob uri. Required. + :vartype uri: str + :ivar type: The managed application definition artifact type. Required. Known values are: + "NotSpecified", "Template", and "Custom". + :vartype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType + """ + + _validation = { + "name": {"required": True}, + "uri": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "uri": {"key": "uri", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Union[str, "_models.ApplicationDefinitionArtifactName"], + uri: str, + type: Union[str, "_models.ApplicationArtifactType"], + **kwargs: Any + ) -> None: + """ + :keyword name: The managed application definition artifact name. Required. Known values are: + "NotSpecified", "ApplicationResourceTemplate", "CreateUiDefinition", and + "MainTemplateParameters". + :paramtype name: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifactName + :keyword uri: The managed application definition artifact blob uri. Required. + :paramtype uri: str + :keyword type: The managed application definition artifact type. Required. Known values are: + "NotSpecified", "Template", and "Custom". + :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType + """ + super().__init__(**kwargs) + self.name = name + self.uri = uri + self.type = type + + +class ApplicationDefinitionListResult(_serialization.Model): + """List of managed application definitions. + + :ivar value: The array of managed application definitions. + :vartype value: list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ApplicationDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.ApplicationDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The array of managed application definitions. + :paramtype value: list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ApplicationDeploymentPolicy(_serialization.Model): + """Managed application deployment policy. + + All required parameters must be populated in order to send to server. + + :ivar deployment_mode: The managed application deployment mode. Required. Known values are: + "NotSpecified", "Incremental", and "Complete". + :vartype deployment_mode: str or ~azure.mgmt.resource.managedapplications.models.DeploymentMode + """ + + _validation = { + "deployment_mode": {"required": True}, + } + + _attribute_map = { + "deployment_mode": {"key": "deploymentMode", "type": "str"}, + } + + def __init__(self, *, deployment_mode: Union[str, "_models.DeploymentMode"], **kwargs: Any) -> None: + """ + :keyword deployment_mode: The managed application deployment mode. Required. Known values are: + "NotSpecified", "Incremental", and "Complete". + :paramtype deployment_mode: str or + ~azure.mgmt.resource.managedapplications.models.DeploymentMode + """ + super().__init__(**kwargs) + self.deployment_mode = deployment_mode + + +class ApplicationJitAccessPolicy(_serialization.Model): + """Managed application Jit access policy. + + All required parameters must be populated in order to send to server. + + :ivar jit_access_enabled: Whether the JIT access is enabled. Required. + :vartype jit_access_enabled: bool + :ivar jit_approval_mode: JIT approval mode. Known values are: "NotSpecified", "AutoApprove", + and "ManualApprove". + :vartype jit_approval_mode: str or + ~azure.mgmt.resource.managedapplications.models.JitApprovalMode + :ivar jit_approvers: The JIT approvers. + :vartype jit_approvers: + list[~azure.mgmt.resource.managedapplications.models.JitApproverDefinition] + :ivar maximum_jit_access_duration: The maximum duration JIT access is granted. This is an + ISO8601 time period value. + :vartype maximum_jit_access_duration: str + """ + + _validation = { + "jit_access_enabled": {"required": True}, + } + + _attribute_map = { + "jit_access_enabled": {"key": "jitAccessEnabled", "type": "bool"}, + "jit_approval_mode": {"key": "jitApprovalMode", "type": "str"}, + "jit_approvers": {"key": "jitApprovers", "type": "[JitApproverDefinition]"}, + "maximum_jit_access_duration": {"key": "maximumJitAccessDuration", "type": "str"}, + } + + def __init__( + self, + *, + jit_access_enabled: bool, + jit_approval_mode: Optional[Union[str, "_models.JitApprovalMode"]] = None, + jit_approvers: Optional[list["_models.JitApproverDefinition"]] = None, + maximum_jit_access_duration: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword jit_access_enabled: Whether the JIT access is enabled. Required. + :paramtype jit_access_enabled: bool + :keyword jit_approval_mode: JIT approval mode. Known values are: "NotSpecified", "AutoApprove", + and "ManualApprove". + :paramtype jit_approval_mode: str or + ~azure.mgmt.resource.managedapplications.models.JitApprovalMode + :keyword jit_approvers: The JIT approvers. + :paramtype jit_approvers: + list[~azure.mgmt.resource.managedapplications.models.JitApproverDefinition] + :keyword maximum_jit_access_duration: The maximum duration JIT access is granted. This is an + ISO8601 time period value. + :paramtype maximum_jit_access_duration: str + """ + super().__init__(**kwargs) + self.jit_access_enabled = jit_access_enabled + self.jit_approval_mode = jit_approval_mode + self.jit_approvers = jit_approvers + self.maximum_jit_access_duration = maximum_jit_access_duration + + +class ApplicationListResult(_serialization.Model): + """List of managed applications. + + :ivar value: The array of managed applications. + :vartype value: list[~azure.mgmt.resource.managedapplications.models.Application] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Application]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[list["_models.Application"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The array of managed applications. + :paramtype value: list[~azure.mgmt.resource.managedapplications.models.Application] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ApplicationManagementPolicy(_serialization.Model): + """Managed application management policy. + + :ivar mode: The managed application management mode. Known values are: "NotSpecified", + "Unmanaged", and "Managed". + :vartype mode: str or ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode + """ + + _attribute_map = { + "mode": {"key": "mode", "type": "str"}, + } + + def __init__( + self, *, mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None, **kwargs: Any + ) -> None: + """ + :keyword mode: The managed application management mode. Known values are: "NotSpecified", + "Unmanaged", and "Managed". + :paramtype mode: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode + """ + super().__init__(**kwargs) + self.mode = mode + + +class ApplicationNotificationEndpoint(_serialization.Model): + """Managed application notification endpoint. + + All required parameters must be populated in order to send to server. + + :ivar uri: The managed application notification endpoint uri. Required. + :vartype uri: str + """ + + _validation = { + "uri": {"required": True}, + } + + _attribute_map = { + "uri": {"key": "uri", "type": "str"}, + } + + def __init__(self, *, uri: str, **kwargs: Any) -> None: + """ + :keyword uri: The managed application notification endpoint uri. Required. + :paramtype uri: str + """ + super().__init__(**kwargs) + self.uri = uri + + +class ApplicationNotificationPolicy(_serialization.Model): + """Managed application notification policy. + + All required parameters must be populated in order to send to server. + + :ivar notification_endpoints: The managed application notification endpoint. Required. + :vartype notification_endpoints: + list[~azure.mgmt.resource.managedapplications.models.ApplicationNotificationEndpoint] + """ + + _validation = { + "notification_endpoints": {"required": True}, + } + + _attribute_map = { + "notification_endpoints": {"key": "notificationEndpoints", "type": "[ApplicationNotificationEndpoint]"}, + } + + def __init__( + self, *, notification_endpoints: list["_models.ApplicationNotificationEndpoint"], **kwargs: Any + ) -> None: + """ + :keyword notification_endpoints: The managed application notification endpoint. Required. + :paramtype notification_endpoints: + list[~azure.mgmt.resource.managedapplications.models.ApplicationNotificationEndpoint] + """ + super().__init__(**kwargs) + self.notification_endpoints = notification_endpoints + + +class ApplicationPackageContact(_serialization.Model): + """The application package contact information. + + All required parameters must be populated in order to send to server. + + :ivar contact_name: The contact name. + :vartype contact_name: str + :ivar email: The contact email. Required. + :vartype email: str + :ivar phone: The contact phone number. Required. + :vartype phone: str + """ + + _validation = { + "email": {"required": True}, + "phone": {"required": True}, + } + + _attribute_map = { + "contact_name": {"key": "contactName", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "phone": {"key": "phone", "type": "str"}, + } + + def __init__(self, *, email: str, phone: str, contact_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword contact_name: The contact name. + :paramtype contact_name: str + :keyword email: The contact email. Required. + :paramtype email: str + :keyword phone: The contact phone number. Required. + :paramtype phone: str + """ + super().__init__(**kwargs) + self.contact_name = contact_name + self.email = email + self.phone = phone + + +class ApplicationPackageLockingPolicyDefinition(_serialization.Model): # pylint: disable=name-too-long + """Managed application locking policy. + + :ivar allowed_actions: The deny assignment excluded actions. + :vartype allowed_actions: list[str] + :ivar allowed_data_actions: The deny assignment excluded data actions. + :vartype allowed_data_actions: list[str] + """ + + _attribute_map = { + "allowed_actions": {"key": "allowedActions", "type": "[str]"}, + "allowed_data_actions": {"key": "allowedDataActions", "type": "[str]"}, + } + + def __init__( + self, + *, + allowed_actions: Optional[list[str]] = None, + allowed_data_actions: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword allowed_actions: The deny assignment excluded actions. + :paramtype allowed_actions: list[str] + :keyword allowed_data_actions: The deny assignment excluded data actions. + :paramtype allowed_data_actions: list[str] + """ + super().__init__(**kwargs) + self.allowed_actions = allowed_actions + self.allowed_data_actions = allowed_data_actions + + +class ApplicationPackageSupportUrls(_serialization.Model): + """The appliance package support URLs. + + :ivar public_azure: The public azure support URL. + :vartype public_azure: str + :ivar government_cloud: The government cloud support URL. + :vartype government_cloud: str + """ + + _attribute_map = { + "public_azure": {"key": "publicAzure", "type": "str"}, + "government_cloud": {"key": "governmentCloud", "type": "str"}, + } + + def __init__( + self, *, public_azure: Optional[str] = None, government_cloud: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword public_azure: The public azure support URL. + :paramtype public_azure: str + :keyword government_cloud: The government cloud support URL. + :paramtype government_cloud: str + """ + super().__init__(**kwargs) + self.public_azure = public_azure + self.government_cloud = government_cloud + + +class ApplicationPatchable(GenericResource): + """Information about managed application. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku + :ivar plan: The plan information. + :vartype plan: ~azure.mgmt.resource.managedapplications.models.PlanPatchable + :ivar kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. + :vartype kind: str + :ivar identity: The identity of the resource. + :vartype identity: ~azure.mgmt.resource.managedapplications.models.Identity + :ivar managed_resource_group_id: The managed resource group Id. + :vartype managed_resource_group_id: str + :ivar application_definition_id: The fully qualified path of managed application definition Id. + :vartype application_definition_id: str + :ivar parameters: Name and value pairs that define the managed application parameters. It can + be a JObject or a well formed JSON string. + :vartype parameters: JSON + :ivar outputs: Name and value pairs that define the managed application outputs. + :vartype outputs: JSON + :ivar provisioning_state: The managed application provisioning state. Known values are: + "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", + "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.models.ProvisioningState + :ivar billing_details: The managed application billing details. + :vartype billing_details: + ~azure.mgmt.resource.managedapplications.models.ApplicationBillingDetailsDefinition + :ivar jit_access_policy: The managed application Jit access policy. + :vartype jit_access_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy + :ivar publisher_tenant_id: The publisher tenant Id. + :vartype publisher_tenant_id: str + :ivar authorizations: The read-only authorizations property that is retrieved from the + application package. + :vartype authorizations: + list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] + :ivar management_mode: The managed application management mode. Known values are: + "NotSpecified", "Unmanaged", and "Managed". + :vartype management_mode: str or + ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode + :ivar customer_support: The read-only customer support property that is retrieved from the + application package. + :vartype customer_support: + ~azure.mgmt.resource.managedapplications.models.ApplicationPackageContact + :ivar support_urls: The read-only support URLs property that is retrieved from the application + package. + :vartype support_urls: + ~azure.mgmt.resource.managedapplications.models.ApplicationPackageSupportUrls + :ivar artifacts: The collection of managed application artifacts. + :vartype artifacts: list[~azure.mgmt.resource.managedapplications.models.ApplicationArtifact] + :ivar created_by: The client entity that created the JIT request. + :vartype created_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails + :ivar updated_by: The client entity that last updated the JIT request. + :vartype updated_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"pattern": r"^[-\w\._,\(\)]+$"}, + "outputs": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "billing_details": {"readonly": True}, + "publisher_tenant_id": {"readonly": True}, + "authorizations": {"readonly": True}, + "management_mode": {"readonly": True}, + "customer_support": {"readonly": True}, + "support_urls": {"readonly": True}, + "artifacts": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "plan": {"key": "plan", "type": "PlanPatchable"}, + "kind": {"key": "kind", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "managed_resource_group_id": {"key": "properties.managedResourceGroupId", "type": "str"}, + "application_definition_id": {"key": "properties.applicationDefinitionId", "type": "str"}, + "parameters": {"key": "properties.parameters", "type": "object"}, + "outputs": {"key": "properties.outputs", "type": "object"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "billing_details": {"key": "properties.billingDetails", "type": "ApplicationBillingDetailsDefinition"}, + "jit_access_policy": {"key": "properties.jitAccessPolicy", "type": "ApplicationJitAccessPolicy"}, + "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, + "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, + "management_mode": {"key": "properties.managementMode", "type": "str"}, + "customer_support": {"key": "properties.customerSupport", "type": "ApplicationPackageContact"}, + "support_urls": {"key": "properties.supportUrls", "type": "ApplicationPackageSupportUrls"}, + "artifacts": {"key": "properties.artifacts", "type": "[ApplicationArtifact]"}, + "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, + "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + plan: Optional["_models.PlanPatchable"] = None, + kind: Optional[str] = None, + identity: Optional["_models.Identity"] = None, + managed_resource_group_id: Optional[str] = None, + application_definition_id: Optional[str] = None, + parameters: Optional[JSON] = None, + jit_access_policy: Optional["_models.ApplicationJitAccessPolicy"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku + :keyword plan: The plan information. + :paramtype plan: ~azure.mgmt.resource.managedapplications.models.PlanPatchable + :keyword kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. + :paramtype kind: str + :keyword identity: The identity of the resource. + :paramtype identity: ~azure.mgmt.resource.managedapplications.models.Identity + :keyword managed_resource_group_id: The managed resource group Id. + :paramtype managed_resource_group_id: str + :keyword application_definition_id: The fully qualified path of managed application definition + Id. + :paramtype application_definition_id: str + :keyword parameters: Name and value pairs that define the managed application parameters. It + can be a JObject or a well formed JSON string. + :paramtype parameters: JSON + :keyword jit_access_policy: The managed application Jit access policy. + :paramtype jit_access_policy: + ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy + """ + super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) + self.plan = plan + self.kind = kind + self.identity = identity + self.managed_resource_group_id = managed_resource_group_id + self.application_definition_id = application_definition_id + self.parameters = parameters + self.outputs: Optional[JSON] = None + self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None + self.billing_details: Optional["_models.ApplicationBillingDetailsDefinition"] = None + self.jit_access_policy = jit_access_policy + self.publisher_tenant_id: Optional[str] = None + self.authorizations: Optional[list["_models.ApplicationAuthorization"]] = None + self.management_mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None + self.customer_support: Optional["_models.ApplicationPackageContact"] = None + self.support_urls: Optional["_models.ApplicationPackageSupportUrls"] = None + self.artifacts: Optional[list["_models.ApplicationArtifact"]] = None + self.created_by: Optional["_models.ApplicationClientDetails"] = None + self.updated_by: Optional["_models.ApplicationClientDetails"] = None + + +class ApplicationPolicy(_serialization.Model): + """Managed application policy. + + :ivar name: The policy name. + :vartype name: str + :ivar policy_definition_id: The policy definition Id. + :vartype policy_definition_id: str + :ivar parameters: The policy parameters. + :vartype parameters: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "parameters": {"key": "parameters", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + parameters: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The policy name. + :paramtype name: str + :keyword policy_definition_id: The policy definition Id. + :paramtype policy_definition_id: str + :keyword parameters: The policy parameters. + :paramtype parameters: str + """ + super().__init__(**kwargs) + self.name = name + self.policy_definition_id = policy_definition_id + self.parameters = parameters + + +class ApplicationPropertiesPatchable(_serialization.Model): + """The managed application properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar managed_resource_group_id: The managed resource group Id. + :vartype managed_resource_group_id: str + :ivar application_definition_id: The fully qualified path of managed application definition Id. + :vartype application_definition_id: str + :ivar parameters: Name and value pairs that define the managed application parameters. It can + be a JObject or a well formed JSON string. + :vartype parameters: JSON + :ivar outputs: Name and value pairs that define the managed application outputs. + :vartype outputs: JSON + :ivar provisioning_state: The managed application provisioning state. Known values are: + "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", + "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.models.ProvisioningState + """ + + _validation = { + "outputs": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "managed_resource_group_id": {"key": "managedResourceGroupId", "type": "str"}, + "application_definition_id": {"key": "applicationDefinitionId", "type": "str"}, + "parameters": {"key": "parameters", "type": "object"}, + "outputs": {"key": "outputs", "type": "object"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + } + + def __init__( + self, + *, + managed_resource_group_id: Optional[str] = None, + application_definition_id: Optional[str] = None, + parameters: Optional[JSON] = None, + **kwargs: Any + ) -> None: + """ + :keyword managed_resource_group_id: The managed resource group Id. + :paramtype managed_resource_group_id: str + :keyword application_definition_id: The fully qualified path of managed application definition + Id. + :paramtype application_definition_id: str + :keyword parameters: Name and value pairs that define the managed application parameters. It + can be a JObject or a well formed JSON string. + :paramtype parameters: JSON + """ + super().__init__(**kwargs) + self.managed_resource_group_id = managed_resource_group_id + self.application_definition_id = application_definition_id + self.parameters = parameters + self.outputs: Optional[JSON] = None + self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.managedapplications.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.resource.managedapplications.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorDetail"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.resource.managedapplications.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.resource.managedapplications.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class Identity(_serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of resource identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of resource. + :vartype tenant_id: str + :ivar type: The identity type. Known values are: "SystemAssigned", "UserAssigned", + "SystemAssigned, UserAssigned", and "None". + :vartype type: str or ~azure.mgmt.resource.managedapplications.models.ResourceIdentityType + :ivar user_assigned_identities: The list of user identities associated with the resource. The + user identity dictionary key references will be resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.resource.managedapplications.models.UserAssignedResourceIdentity] + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedResourceIdentity}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, + user_assigned_identities: Optional[dict[str, "_models.UserAssignedResourceIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The identity type. Known values are: "SystemAssigned", "UserAssigned", + "SystemAssigned, UserAssigned", and "None". + :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.ResourceIdentityType + :keyword user_assigned_identities: The list of user identities associated with the resource. + The user identity dictionary key references will be resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.resource.managedapplications.models.UserAssignedResourceIdentity] + """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.tenant_id: Optional[str] = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class JitApproverDefinition(_serialization.Model): + """JIT approver definition. + + All required parameters must be populated in order to send to server. + + :ivar id: The approver service principal Id. Required. + :vartype id: str + :ivar type: The approver type. Known values are: "user" and "group". + :vartype type: str or ~azure.mgmt.resource.managedapplications.models.JitApproverType + :ivar display_name: The approver display name. + :vartype display_name: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + type: Optional[Union[str, "_models.JitApproverType"]] = None, + display_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The approver service principal Id. Required. + :paramtype id: str + :keyword type: The approver type. Known values are: "user" and "group". + :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.JitApproverType + :keyword display_name: The approver display name. + :paramtype display_name: str + """ + super().__init__(**kwargs) + self.id = id + self.type = type + self.display_name = display_name + + +class JitAuthorizationPolicies(_serialization.Model): + """The JIT authorization policies. + + All required parameters must be populated in order to send to server. + + :ivar principal_id: The the principal id that will be granted JIT access. Required. + :vartype principal_id: str + :ivar role_definition_id: The role definition id that will be granted to the Principal. + Required. + :vartype role_definition_id: str + """ + + _validation = { + "principal_id": {"required": True}, + "role_definition_id": {"required": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + } + + def __init__(self, *, principal_id: str, role_definition_id: str, **kwargs: Any) -> None: + """ + :keyword principal_id: The the principal id that will be granted JIT access. Required. + :paramtype principal_id: str + :keyword role_definition_id: The role definition id that will be granted to the Principal. + Required. + :paramtype role_definition_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + + +class JitRequestDefinition(Resource): + """Information about JIT request definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar application_resource_id: The parent application id. + :vartype application_resource_id: str + :ivar publisher_tenant_id: The publisher tenant id. + :vartype publisher_tenant_id: str + :ivar jit_authorization_policies: The JIT authorization policies. + :vartype jit_authorization_policies: + list[~azure.mgmt.resource.managedapplications.models.JitAuthorizationPolicies] + :ivar jit_scheduling_policy: The JIT request properties. + :vartype jit_scheduling_policy: + ~azure.mgmt.resource.managedapplications.models.JitSchedulingPolicy + :ivar provisioning_state: The JIT request provisioning state. Known values are: "NotSpecified", + "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", "Canceled", + "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.models.ProvisioningState + :ivar jit_request_state: The JIT request state. Known values are: "NotSpecified", "Pending", + "Approved", "Denied", "Failed", "Canceled", "Expired", and "Timeout". + :vartype jit_request_state: str or + ~azure.mgmt.resource.managedapplications.models.JitRequestState + :ivar created_by: The client entity that created the JIT request. + :vartype created_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails + :ivar updated_by: The client entity that last updated the JIT request. + :vartype updated_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "publisher_tenant_id": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "jit_request_state": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "application_resource_id": {"key": "properties.applicationResourceId", "type": "str"}, + "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, + "jit_authorization_policies": { + "key": "properties.jitAuthorizationPolicies", + "type": "[JitAuthorizationPolicies]", + }, + "jit_scheduling_policy": {"key": "properties.jitSchedulingPolicy", "type": "JitSchedulingPolicy"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "jit_request_state": {"key": "properties.jitRequestState", "type": "str"}, + "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, + "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + application_resource_id: Optional[str] = None, + jit_authorization_policies: Optional[list["_models.JitAuthorizationPolicies"]] = None, + jit_scheduling_policy: Optional["_models.JitSchedulingPolicy"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword application_resource_id: The parent application id. + :paramtype application_resource_id: str + :keyword jit_authorization_policies: The JIT authorization policies. + :paramtype jit_authorization_policies: + list[~azure.mgmt.resource.managedapplications.models.JitAuthorizationPolicies] + :keyword jit_scheduling_policy: The JIT request properties. + :paramtype jit_scheduling_policy: + ~azure.mgmt.resource.managedapplications.models.JitSchedulingPolicy + """ + super().__init__(location=location, tags=tags, **kwargs) + self.application_resource_id = application_resource_id + self.publisher_tenant_id: Optional[str] = None + self.jit_authorization_policies = jit_authorization_policies + self.jit_scheduling_policy = jit_scheduling_policy + self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None + self.jit_request_state: Optional[Union[str, "_models.JitRequestState"]] = None + self.created_by: Optional["_models.ApplicationClientDetails"] = None + self.updated_by: Optional["_models.ApplicationClientDetails"] = None + + +class JitRequestDefinitionListResult(_serialization.Model): + """List of JIT requests. + + :ivar value: The array of Jit request definition. + :vartype value: list[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[JitRequestDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.JitRequestDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The array of Jit request definition. + :paramtype value: list[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class JitRequestPatchable(_serialization.Model): + """Information about JIT request. + + :ivar tags: Jit request tags. + :vartype tags: dict[str, str] + """ + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, tags: Optional[dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Jit request tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.tags = tags + + +class JitSchedulingPolicy(_serialization.Model): + """The JIT scheduling policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar type: The type of JIT schedule. Required. Known values are: "NotSpecified", "Once", and + "Recurring". + :vartype type: str or ~azure.mgmt.resource.managedapplications.models.JitSchedulingType + :ivar duration: The required duration of the JIT request. Required. + :vartype duration: ~datetime.timedelta + :ivar start_time: The start time of the request. Required. + :vartype start_time: ~datetime.datetime + """ + + _validation = { + "type": {"required": True, "readonly": True}, + "duration": {"required": True}, + "start_time": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "duration": {"key": "duration", "type": "duration"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + } + + def __init__(self, *, duration: datetime.timedelta, start_time: datetime.datetime, **kwargs: Any) -> None: + """ + :keyword duration: The required duration of the JIT request. Required. + :paramtype duration: ~datetime.timedelta + :keyword start_time: The start time of the request. Required. + :paramtype start_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.type: Optional[Union[str, "_models.JitSchedulingType"]] = None + self.duration = duration + self.start_time = start_time + + +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.resource.managedapplications.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.resource.managedapplications.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.resource.managedapplications.models.ActionType + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.resource.managedapplications.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name: Optional[str] = None + self.is_data_action: Optional[bool] = None + self.display = display + self.origin: Optional[Union[str, "_models.Origin"]] = None + self.action_type: Optional[Union[str, "_models.ActionType"]] = None + + +class OperationAutoGenerated(_serialization.Model): + """Microsoft.Solutions operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.managedapplications.models.OperationDisplayAutoGenerated + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplayAutoGenerated"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["_models.OperationDisplayAutoGenerated"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: + ~azure.mgmt.resource.managedapplications.models.OperationDisplayAutoGenerated + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". + :vartype resource: str + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". + :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.provider: Optional[str] = None + self.resource: Optional[str] = None + self.operation: Optional[str] = None + self.description: Optional[str] = None + + +class OperationDisplayAutoGenerated(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Solutions. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Application, JitRequest, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Solutions. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Application, JitRequest, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link + to get the next set of results. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of operations supported by the resource provider. + :vartype value: list[~azure.mgmt.resource.managedapplications.models.Operation] + :ivar next_link: URL to get the next set of operation list results (if there are any). + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value: Optional[list["_models.Operation"]] = None + self.next_link: Optional[str] = None + + +class Plan(_serialization.Model): + """Plan for the managed application. + + All required parameters must be populated in order to send to server. + + :ivar name: The plan name. Required. + :vartype name: str + :ivar publisher: The publisher ID. Required. + :vartype publisher: str + :ivar product: The product code. Required. + :vartype product: str + :ivar promotion_code: The promotion code. + :vartype promotion_code: str + :ivar version: The plan's version. Required. + :vartype version: str + """ + + _validation = { + "name": {"required": True}, + "publisher": {"required": True}, + "product": {"required": True}, + "version": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "product": {"key": "product", "type": "str"}, + "promotion_code": {"key": "promotionCode", "type": "str"}, + "version": {"key": "version", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + publisher: str, + product: str, + version: str, + promotion_code: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The plan name. Required. + :paramtype name: str + :keyword publisher: The publisher ID. Required. + :paramtype publisher: str + :keyword product: The product code. Required. + :paramtype product: str + :keyword promotion_code: The promotion code. + :paramtype promotion_code: str + :keyword version: The plan's version. Required. + :paramtype version: str + """ + super().__init__(**kwargs) + self.name = name + self.publisher = publisher + self.product = product + self.promotion_code = promotion_code + self.version = version + + +class PlanPatchable(_serialization.Model): + """Plan for the managed application. + + :ivar name: The plan name. + :vartype name: str + :ivar publisher: The publisher ID. + :vartype publisher: str + :ivar product: The product code. + :vartype product: str + :ivar promotion_code: The promotion code. + :vartype promotion_code: str + :ivar version: The plan's version. + :vartype version: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "product": {"key": "product", "type": "str"}, + "promotion_code": {"key": "promotionCode", "type": "str"}, + "version": {"key": "version", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + publisher: Optional[str] = None, + product: Optional[str] = None, + promotion_code: Optional[str] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The plan name. + :paramtype name: str + :keyword publisher: The publisher ID. + :paramtype publisher: str + :keyword product: The product code. + :paramtype product: str + :keyword promotion_code: The promotion code. + :paramtype promotion_code: str + :keyword version: The plan's version. + :paramtype version: str + """ + super().__init__(**kwargs) + self.name = name + self.publisher = publisher + self.product = product + self.promotion_code = promotion_code + self.version = version + + +class Sku(_serialization.Model): + """SKU for the resource. + + All required parameters must be populated in order to send to server. + + :ivar name: The SKU name. Required. + :vartype name: str + :ivar tier: The SKU tier. + :vartype tier: str + :ivar size: The SKU size. + :vartype size: str + :ivar family: The SKU family. + :vartype family: str + :ivar model: The SKU model. + :vartype model: str + :ivar capacity: The SKU capacity. + :vartype capacity: int + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "size": {"key": "size", "type": "str"}, + "family": {"key": "family", "type": "str"}, + "model": {"key": "model", "type": "str"}, + "capacity": {"key": "capacity", "type": "int"}, + } + + def __init__( + self, + *, + name: str, + tier: Optional[str] = None, + size: Optional[str] = None, + family: Optional[str] = None, + model: Optional[str] = None, + capacity: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The SKU name. Required. + :paramtype name: str + :keyword tier: The SKU tier. + :paramtype tier: str + :keyword size: The SKU size. + :paramtype size: str + :keyword family: The SKU family. + :paramtype family: str + :keyword model: The SKU model. + :paramtype model: str + :keyword capacity: The SKU capacity. + :paramtype capacity: int + """ + super().__init__(**kwargs) + self.name = name + self.tier = tier + self.size = size + self.family = family + self.model = model + self.capacity = capacity + + +class UserAssignedResourceIdentity(_serialization.Model): + """Represents the user assigned identity that is contained within the UserAssignedIdentities + dictionary on ResourceIdentity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant id of user assigned identity. + :vartype tenant_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.tenant_id: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_patch.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/__init__.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/__init__.py new file mode 100644 index 000000000000..cdaa4d1b9b46 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/__init__.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _ApplicationClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import ApplicationsOperations # type: ignore +from ._operations import ApplicationDefinitionsOperations # type: ignore +from ._operations import JitRequestsOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationsOperations", + "ApplicationDefinitionsOperations", + "JitRequestsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_operations.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_operations.py new file mode 100644 index 000000000000..b8c49dd259a7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_operations.py @@ -0,0 +1,3622 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._configuration import ApplicationClientConfiguration +from .._utils.serialization import Deserializer, Serializer +from .._utils.utils import ClientMixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_application_list_operations_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Solutions/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_get_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_delete_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_create_or_update_request( # pylint: disable=name-too-long + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_update_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_list_by_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_list_by_subscription_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/applications") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_get_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_delete_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_create_or_update_by_id_request( # pylint: disable=name-too-long + application_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_update_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_refresh_permissions_request( # pylint: disable=name-too-long + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_get_request( # pylint: disable=name-too-long + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_delete_request( # pylint: disable=name-too-long + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_create_or_update_request( # pylint: disable=name-too-long + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_list_by_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_get_by_id_request( # pylint: disable=name-too-long + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_delete_by_id_request( # pylint: disable=name-too-long + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_create_or_update_by_id_request( # pylint: disable=name-too-long + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_get_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_create_or_update_request( # pylint: disable=name-too-long + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_update_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_delete_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_list_by_subscription_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/jitRequests") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_list_by_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class _ApplicationClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], ApplicationClientConfiguration] +): + + @distributed_trace + def list_operations(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Solutions REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_application_list_operations_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ApplicationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.ApplicationClient`'s + :attr:`applications` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, application_name: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + _request = build_applications_get_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial(self, resource_group_name: str, application_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_applications_delete_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, application_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + application_name: str, + parameters: Union[_models.Application, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + _request = build_applications_create_or_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: Union[_models.Application, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + application_name=application_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.Application].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.Application]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[_models.ApplicationPatchable] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[Union[_models.ApplicationPatchable, IO[bytes]]] = None, + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + ApplicationPatchable type or a IO[bytes] type. Default value is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable or + IO[bytes] + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if parameters else None + cls: ClsType[Optional[_models.Application]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if parameters else None + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "ApplicationPatchable") + else: + _json = None + + _request = build_applications_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> ItemPaged["_models.Application"]: + """Gets all the applications within a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_applications_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> ItemPaged["_models.Application"]: + """Gets all the applications within a subscription. + + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_applications_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_by_id(self, application_id: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + _request = build_applications_get_by_id_request( + application_id=application_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_by_id_initial(self, application_id: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_applications_delete_by_id_request( + application_id=application_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_by_id(self, application_id: str, **kwargs: Any) -> LROPoller[None]: + """Deletes the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_by_id_initial( + application_id=application_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _create_or_update_by_id_initial( + self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + _request = build_applications_create_or_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update_by_id( + self, + application_id: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update_by_id( + self, application_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_by_id( + self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_by_id_initial( + application_id=application_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.Application].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.Application]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + def update_by_id( + self, + application_id: str, + parameters: Optional[_models.Application] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_by_id( + self, + application_id: str, + parameters: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_by_id( + self, application_id: str, parameters: Optional[Union[_models.Application, IO[bytes]]] = None, **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + Application type or a IO[bytes] type. Default value is None. + :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if parameters else None + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if parameters else None + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "Application") + else: + _json = None + + _request = build_applications_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _refresh_permissions_initial( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_applications_refresh_permissions_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_refresh_permissions( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Refresh Permissions for application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._refresh_permissions_initial( + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + +class ApplicationDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.ApplicationClient`'s + :attr:`application_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + _request = build_application_definitions_get_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_application_definitions_delete_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition to delete. + Required. + :type application_definition_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + _request = build_application_definitions_create_or_update_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or + IO[bytes] + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ApplicationDefinition].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ApplicationDefinition]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> ItemPaged["_models.ApplicationDefinition"]: + """Lists the managed application definitions in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_application_definitions_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + _request = build_application_definitions_get_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_by_id_initial( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_application_definitions_delete_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_by_id_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _create_or_update_by_id_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + _request = build_application_definitions_create_or_update_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or + IO[bytes] + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_by_id_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ApplicationDefinition].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ApplicationDefinition]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class JitRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.ApplicationClient`'s + :attr:`jit_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> _models.JitRequestDefinition: + """Gets the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + _request = build_jit_requests_get_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestDefinition") + + _request = build_jit_requests_create_or_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either JitRequestDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either JitRequestDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition or + IO[bytes] + :return: An instance of LROPoller that returns either JitRequestDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.JitRequestDefinition].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.JitRequestDefinition]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestPatchable, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestPatchable, IO[bytes]], + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestPatchable type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable or + IO[bytes] + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestPatchable") + + _request = build_jit_requests_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, jit_request_name: str, **kwargs: Any + ) -> None: + """Deletes the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_jit_requests_delete_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the subscription. + + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + _request = build_jit_requests_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + _request = build_jit_requests_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_patch.py b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/py.typed b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/azure/mgmt/resource/managedapplications/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-managedapplications/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application.py new file mode 100644 index 000000000000..6d58250cecdc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application.py @@ -0,0 +1,51 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python create_or_update_application.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.applications.begin_create_or_update( + resource_group_name="rg", + application_name="myManagedApplication", + parameters={ + "kind": "ServiceCatalog", + "location": "East US 2", + "properties": { + "applicationDefinitionId": "/subscriptions/subid/resourceGroups/rg/providers/Microsoft.Solutions/applicationDefinitions/myAppDef", + "managedResourceGroupId": "/subscriptions/subid/resourceGroups/myManagedRG", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/createOrUpdateApplication.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application_definition.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application_definition.py new file mode 100644 index 000000000000..7c931b9028f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/create_or_update_application_definition.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python create_or_update_application_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_definitions.begin_create_or_update( + resource_group_name="rg", + application_definition_name="myManagedApplicationDef", + parameters={ + "location": "East US 2", + "properties": { + "authorizations": [{"principalId": "validprincipalguid", "roleDefinitionId": "validroleguid"}], + "description": "myManagedApplicationDef description", + "displayName": "myManagedApplicationDef", + "lockLevel": "None", + "packageFileUri": "https://path/to/packagezipfile", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/createOrUpdateApplicationDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/delete_application_definition.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/delete_application_definition.py new file mode 100644 index 000000000000..269f2eddb4fb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/delete_application_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python delete_application_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + client.application_definitions.begin_delete_by_id( + resource_group_name="rg", + application_definition_name="myManagedApplicationDef", + ).result() + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/deleteApplicationDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application.py new file mode 100644 index 000000000000..d0129419d647 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python get_application.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.applications.get( + resource_group_name="rg", + application_name="myManagedApplication", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/getApplication.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application_definition.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application_definition.py new file mode 100644 index 000000000000..655281c058c7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/get_application_definition.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python get_application_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_definitions.get( + resource_group_name="rg", + application_definition_name="myManagedApplicationDef", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/getApplicationDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_application_definitions_by_resource_group.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_application_definitions_by_resource_group.py new file mode 100644 index 000000000000..1b1d35260bb8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_application_definitions_by_resource_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python list_application_definitions_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_definitions.list_by_resource_group( + resource_group_name="rg", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/listApplicationDefinitionsByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_applications_by_resource_group.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_applications_by_resource_group.py new file mode 100644 index 000000000000..abeeb74e764b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_applications_by_resource_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python list_applications_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.applications.list_by_resource_group( + resource_group_name="rg", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/listApplicationsByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_solutions_operations.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_solutions_operations.py new file mode 100644 index 000000000000..93d9878acf28 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/list_solutions_operations.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python list_solutions_operations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.list_operations() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/listSolutionsOperations.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/update_application.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/update_application.py new file mode 100644 index 000000000000..fc1aba3132ed --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_samples/update_application.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.managedapplications import ApplicationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-managedapplications +# USAGE + python update_application.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ApplicationClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.applications.update( + resource_group_name="rg", + application_name="myManagedApplication", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/managedapplications/stable/2019-07-01/examples/updateApplication.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/conftest.py new file mode 100644 index 000000000000..8947fbf6e90c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + application_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + application_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + application_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + application_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application.py new file mode 100644 index 000000000000..0377b67b0be3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplication(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_operations(self, resource_group): + response = self.client.list_operations( + api_version="2019-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations.py new file mode 100644 index 000000000000..d5a6643fae79 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations.py @@ -0,0 +1,148 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationApplicationDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_get(self, resource_group): + response = self.client.application_definitions.get( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_begin_delete(self, resource_group): + response = self.client.application_definitions.begin_delete( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_begin_create_or_update(self, resource_group): + response = self.client.application_definitions.begin_create_or_update( + resource_group_name=resource_group.name, + application_definition_name="str", + parameters={ + "lockLevel": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "createUiDefinition": {}, + "deploymentPolicy": {"deploymentMode": "str"}, + "description": "str", + "displayName": "str", + "id": "str", + "isEnabled": bool, + "location": "str", + "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, + "mainTemplate": {}, + "managedBy": "str", + "managementPolicy": {"mode": "str"}, + "name": "str", + "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, + "packageFileUri": "str", + "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], + "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_list_by_resource_group(self, resource_group): + response = self.client.application_definitions.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2019-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_get_by_id(self, resource_group): + response = self.client.application_definitions.get_by_id( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_begin_delete_by_id(self, resource_group): + response = self.client.application_definitions.begin_delete_by_id( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_begin_create_or_update_by_id(self, resource_group): + response = self.client.application_definitions.begin_create_or_update_by_id( + resource_group_name=resource_group.name, + application_definition_name="str", + parameters={ + "lockLevel": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "createUiDefinition": {}, + "deploymentPolicy": {"deploymentMode": "str"}, + "description": "str", + "displayName": "str", + "id": "str", + "isEnabled": bool, + "location": "str", + "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, + "mainTemplate": {}, + "managedBy": "str", + "managementPolicy": {"mode": "str"}, + "name": "str", + "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, + "packageFileUri": "str", + "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], + "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations_async.py new file mode 100644 index 000000000000..780a831d1008 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_application_definitions_operations_async.py @@ -0,0 +1,171 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationApplicationDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_get(self, resource_group): + response = await self.client.application_definitions.get( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_begin_delete(self, resource_group): + response = await ( + await self.client.application_definitions.begin_delete( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_begin_create_or_update(self, resource_group): + response = await ( + await self.client.application_definitions.begin_create_or_update( + resource_group_name=resource_group.name, + application_definition_name="str", + parameters={ + "lockLevel": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "createUiDefinition": {}, + "deploymentPolicy": {"deploymentMode": "str"}, + "description": "str", + "displayName": "str", + "id": "str", + "isEnabled": bool, + "location": "str", + "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, + "mainTemplate": {}, + "managedBy": "str", + "managementPolicy": {"mode": "str"}, + "name": "str", + "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, + "packageFileUri": "str", + "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], + "sku": { + "name": "str", + "capacity": 0, + "family": "str", + "model": "str", + "size": "str", + "tier": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_list_by_resource_group(self, resource_group): + response = self.client.application_definitions.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2019-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_get_by_id(self, resource_group): + response = await self.client.application_definitions.get_by_id( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_begin_delete_by_id(self, resource_group): + response = await ( + await self.client.application_definitions.begin_delete_by_id( + resource_group_name=resource_group.name, + application_definition_name="str", + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_begin_create_or_update_by_id(self, resource_group): + response = await ( + await self.client.application_definitions.begin_create_or_update_by_id( + resource_group_name=resource_group.name, + application_definition_name="str", + parameters={ + "lockLevel": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "createUiDefinition": {}, + "deploymentPolicy": {"deploymentMode": "str"}, + "description": "str", + "displayName": "str", + "id": "str", + "isEnabled": bool, + "location": "str", + "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, + "mainTemplate": {}, + "managedBy": "str", + "managementPolicy": {"mode": "str"}, + "name": "str", + "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, + "packageFileUri": "str", + "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], + "sku": { + "name": "str", + "capacity": 0, + "family": "str", + "model": "str", + "size": "str", + "tier": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations.py new file mode 100644 index 000000000000..59b1d04354c2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations.py @@ -0,0 +1,218 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationApplicationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_get(self, resource_group): + response = self.client.applications.get( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_begin_delete(self, resource_group): + response = self.client.applications.begin_delete( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_begin_create_or_update(self, resource_group): + response = self.client.applications.begin_create_or_update( + resource_group_name=resource_group.name, + application_name="str", + parameters={ + "kind": "str", + "applicationDefinitionId": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "billingDetails": {"resourceUsageId": "str"}, + "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, + }, + "jitAccessPolicy": { + "jitAccessEnabled": bool, + "jitApprovalMode": "str", + "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], + "maximumJitAccessDuration": "str", + }, + "location": "str", + "managedBy": "str", + "managedResourceGroupId": "str", + "managementMode": "str", + "name": "str", + "outputs": {}, + "parameters": {}, + "plan": {"name": "str", "product": "str", "publisher": "str", "version": "str", "promotionCode": "str"}, + "provisioningState": "str", + "publisherTenantId": "str", + "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, + "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, + "tags": {"str": "str"}, + "type": "str", + "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + }, + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_update(self, resource_group): + response = self.client.applications.update( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_list_by_resource_group(self, resource_group): + response = self.client.applications.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2019-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_list_by_subscription(self, resource_group): + response = self.client.applications.list_by_subscription( + api_version="2019-07-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_get_by_id(self, resource_group): + response = self.client.applications.get_by_id( + application_id="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_begin_delete_by_id(self, resource_group): + response = self.client.applications.begin_delete_by_id( + application_id="str", + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_begin_create_or_update_by_id(self, resource_group): + response = self.client.applications.begin_create_or_update_by_id( + application_id="str", + parameters={ + "kind": "str", + "applicationDefinitionId": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "billingDetails": {"resourceUsageId": "str"}, + "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, + }, + "jitAccessPolicy": { + "jitAccessEnabled": bool, + "jitApprovalMode": "str", + "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], + "maximumJitAccessDuration": "str", + }, + "location": "str", + "managedBy": "str", + "managedResourceGroupId": "str", + "managementMode": "str", + "name": "str", + "outputs": {}, + "parameters": {}, + "plan": {"name": "str", "product": "str", "publisher": "str", "version": "str", "promotionCode": "str"}, + "provisioningState": "str", + "publisherTenantId": "str", + "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, + "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, + "tags": {"str": "str"}, + "type": "str", + "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + }, + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_update_by_id(self, resource_group): + response = self.client.applications.update_by_id( + application_id="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_begin_refresh_permissions(self, resource_group): + response = self.client.applications.begin_refresh_permissions( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations_async.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations_async.py new file mode 100644 index 000000000000..41cfb021e04d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_applications_operations_async.py @@ -0,0 +1,255 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationApplicationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_get(self, resource_group): + response = await self.client.applications.get( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_begin_delete(self, resource_group): + response = await ( + await self.client.applications.begin_delete( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_begin_create_or_update(self, resource_group): + response = await ( + await self.client.applications.begin_create_or_update( + resource_group_name=resource_group.name, + application_name="str", + parameters={ + "kind": "str", + "applicationDefinitionId": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "billingDetails": {"resourceUsageId": "str"}, + "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, + }, + "jitAccessPolicy": { + "jitAccessEnabled": bool, + "jitApprovalMode": "str", + "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], + "maximumJitAccessDuration": "str", + }, + "location": "str", + "managedBy": "str", + "managedResourceGroupId": "str", + "managementMode": "str", + "name": "str", + "outputs": {}, + "parameters": {}, + "plan": { + "name": "str", + "product": "str", + "publisher": "str", + "version": "str", + "promotionCode": "str", + }, + "provisioningState": "str", + "publisherTenantId": "str", + "sku": { + "name": "str", + "capacity": 0, + "family": "str", + "model": "str", + "size": "str", + "tier": "str", + }, + "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, + "tags": {"str": "str"}, + "type": "str", + "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + }, + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_update(self, resource_group): + response = await self.client.applications.update( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_list_by_resource_group(self, resource_group): + response = self.client.applications.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2019-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_list_by_subscription(self, resource_group): + response = self.client.applications.list_by_subscription( + api_version="2019-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_get_by_id(self, resource_group): + response = await self.client.applications.get_by_id( + application_id="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_begin_delete_by_id(self, resource_group): + response = await ( + await self.client.applications.begin_delete_by_id( + application_id="str", + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_begin_create_or_update_by_id(self, resource_group): + response = await ( + await self.client.applications.begin_create_or_update_by_id( + application_id="str", + parameters={ + "kind": "str", + "applicationDefinitionId": "str", + "artifacts": [{"name": "str", "type": "str", "uri": "str"}], + "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], + "billingDetails": {"resourceUsageId": "str"}, + "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, + }, + "jitAccessPolicy": { + "jitAccessEnabled": bool, + "jitApprovalMode": "str", + "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], + "maximumJitAccessDuration": "str", + }, + "location": "str", + "managedBy": "str", + "managedResourceGroupId": "str", + "managementMode": "str", + "name": "str", + "outputs": {}, + "parameters": {}, + "plan": { + "name": "str", + "product": "str", + "publisher": "str", + "version": "str", + "promotionCode": "str", + }, + "provisioningState": "str", + "publisherTenantId": "str", + "sku": { + "name": "str", + "capacity": 0, + "family": "str", + "model": "str", + "size": "str", + "tier": "str", + }, + "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, + "tags": {"str": "str"}, + "type": "str", + "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + }, + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_update_by_id(self, resource_group): + response = await self.client.applications.update_by_id( + application_id="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_begin_refresh_permissions(self, resource_group): + response = await ( + await self.client.applications.begin_refresh_permissions( + resource_group_name=resource_group.name, + application_name="str", + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_async.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_async.py new file mode 100644 index 000000000000..df72803a5f39 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_operations(self, resource_group): + response = self.client.list_operations( + api_version="2019-07-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations.py new file mode 100644 index 000000000000..f0cd26e49228 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations.py @@ -0,0 +1,108 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationJitRequestsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_get(self, resource_group): + response = self.client.jit_requests.get( + resource_group_name=resource_group.name, + jit_request_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_begin_create_or_update(self, resource_group): + response = self.client.jit_requests.begin_create_or_update( + resource_group_name=resource_group.name, + jit_request_name="str", + parameters={ + "applicationResourceId": "str", + "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + "id": "str", + "jitAuthorizationPolicies": [{"principalId": "str", "roleDefinitionId": "str"}], + "jitRequestState": "str", + "jitSchedulingPolicy": { + "duration": "1 day, 0:00:00", + "startTime": "2020-02-20 00:00:00", + "type": "str", + }, + "location": "str", + "name": "str", + "provisioningState": "str", + "publisherTenantId": "str", + "tags": {"str": "str"}, + "type": "str", + "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + }, + api_version="2019-07-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_update(self, resource_group): + response = self.client.jit_requests.update( + resource_group_name=resource_group.name, + jit_request_name="str", + parameters={"tags": {"str": "str"}}, + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_delete(self, resource_group): + response = self.client.jit_requests.delete( + resource_group_name=resource_group.name, + jit_request_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_list_by_subscription(self, resource_group): + response = self.client.jit_requests.list_by_subscription( + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_list_by_resource_group(self, resource_group): + response = self.client.jit_requests.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations_async.py b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations_async.py new file mode 100644 index 000000000000..dbcafcf74cbe --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/generated_tests/test_application_jit_requests_operations_async.py @@ -0,0 +1,111 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestApplicationJitRequestsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_get(self, resource_group): + response = await self.client.jit_requests.get( + resource_group_name=resource_group.name, + jit_request_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_begin_create_or_update(self, resource_group): + response = await ( + await self.client.jit_requests.begin_create_or_update( + resource_group_name=resource_group.name, + jit_request_name="str", + parameters={ + "applicationResourceId": "str", + "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + "id": "str", + "jitAuthorizationPolicies": [{"principalId": "str", "roleDefinitionId": "str"}], + "jitRequestState": "str", + "jitSchedulingPolicy": { + "duration": "1 day, 0:00:00", + "startTime": "2020-02-20 00:00:00", + "type": "str", + }, + "location": "str", + "name": "str", + "provisioningState": "str", + "publisherTenantId": "str", + "tags": {"str": "str"}, + "type": "str", + "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, + }, + api_version="2019-07-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_update(self, resource_group): + response = await self.client.jit_requests.update( + resource_group_name=resource_group.name, + jit_request_name="str", + parameters={"tags": {"str": "str"}}, + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_delete(self, resource_group): + response = await self.client.jit_requests.delete( + resource_group_name=resource_group.name, + jit_request_name="str", + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_list_by_subscription(self, resource_group): + response = await self.client.jit_requests.list_by_subscription( + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_list_by_resource_group(self, resource_group): + response = await self.client.jit_requests.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2019-07-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/pyproject.toml b/sdk/resources/azure-mgmt-resource-managedapplications/pyproject.toml new file mode 100644 index 000000000000..2887a938a23c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-managedapplications" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Managedapplications Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.managedapplications._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-managedapplications" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Managedapplications Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "ApplicationClient" diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/conftest.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/conftest.py new file mode 100644 index 000000000000..8947fbf6e90c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + application_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + application_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + application_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + application_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=application_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_async_test.py new file mode 100644 index 000000000000..6fda645bf58c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_async_test.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationApplicationDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_application_definitions_list_by_resource_group(self, resource_group): + response = self.client.application_definitions.list_by_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert result == [] diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_test.py new file mode 100644 index 000000000000..5c9676e70ee1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_application_definitions_operations_test.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationApplicationDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_application_definitions_list_by_resource_group(self, resource_group): + response = self.client.application_definitions.list_by_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert result == [] diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_async_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_async_test.py new file mode 100644 index 000000000000..1290344c0063 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationApplicationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_list_by_resource_group(self, resource_group): + response = self.client.applications.list_by_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert result == [] + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_applications_list_by_subscription(self, resource_group): + response = self.client.applications.list_by_subscription() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_test.py new file mode 100644 index 000000000000..dcdfcaa99bd7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_applications_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationApplicationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_list_by_resource_group(self, resource_group): + response = self.client.applications.list_by_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert result == [] + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_applications_list_by_subscription(self, resource_group): + response = self.client.applications.list_by_subscription() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_async_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_async_test.py new file mode 100644 index 000000000000..6f7184f85128 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_operations(self, resource_group): + response = self.client.list_operations() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_async_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_async_test.py new file mode 100644 index 000000000000..9601d903b3d3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications.aio import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationJitRequestsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_list_by_subscription(self, resource_group): + response = await self.client.jit_requests.list_by_subscription() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_jit_requests_list_by_resource_group(self, resource_group): + response = await self.client.jit_requests.list_by_resource_group( + resource_group_name=resource_group.name, + ) + + assert response diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_test.py new file mode 100644 index 000000000000..982b28f7f56b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_jit_requests_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplicationJitRequestsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_list_by_subscription(self, resource_group): + response = self.client.jit_requests.list_by_subscription() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_jit_requests_list_by_resource_group(self, resource_group): + response = self.client.jit_requests.list_by_resource_group( + resource_group_name=resource_group.name, + ) + + assert response diff --git a/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_test.py b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_test.py new file mode 100644 index 000000000000..fbafcb7e2c04 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-managedapplications/tests/test_application_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.managedapplications import ApplicationClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestApplication(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ApplicationClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_operations(self, resource_group): + response = self.client.list_operations() + result = [r for r in response] + assert result From 002c89dc18bd342c7bc5f28e9ffe2edbbc2b8de9 Mon Sep 17 00:00:00 2001 From: Yuchao Yan Date: Thu, 5 Feb 2026 16:33:21 +0800 Subject: [PATCH 58/84] Skip release pipeline comment when link is empty (#45032) --- scripts/auto_release/main.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/auto_release/main.py b/scripts/auto_release/main.py index 845d2e32b210..86b8eda0fd99 100644 --- a/scripts/auto_release/main.py +++ b/scripts/auto_release/main.py @@ -329,9 +329,11 @@ def create_pr_proc(self): pr_title = "[AutoRelease] {}(can only be merged by SDK owner)".format(self.new_branch) pr_head = "{}:{}".format(os.getenv("USR_NAME"), self.new_branch) pr_base = "main" - pr_body = "{} \n{} \n After PR merged, trigger [release pipeline]({}) to release".format( - self.issue_link, self.test_result, self.release_pipeline_link - ) + pr_body = "PR for release issue {}".format(self.issue_link) + if self.release_pipeline_link: + pr_body += " \n After PR merged, trigger [release pipeline]({}) to release".format( + self.release_pipeline_link + ) if self.has_multi_packages: pr_body += f"\nBuildTargetingString\n {self.whole_package_name}\nSkip.CreateApiReview" pr_body += "\n\n (Just to record: this PR was created by this [pipeline]({}))".format( From 7bbbacaf3c472b2c8188e3983b56c1d76e27b307 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:54:10 -0800 Subject: [PATCH 59/84] [AutoRelease] t2-resource-changes-2026-02-05-00873(can only be merged by SDK owner) (#45018) * code and test * update * Update dev_requirements.txt --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 Co-authored-by: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> --- .../azure-mgmt-resource-changes/CHANGELOG.md | 7 + .../azure-mgmt-resource-changes/LICENSE | 21 + .../azure-mgmt-resource-changes/MANIFEST.in | 8 + .../azure-mgmt-resource-changes/README.md | 61 + .../_metadata.json | 11 + .../apiview-properties.json | 21 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../azure/mgmt/resource/changes/__init__.py | 32 + .../mgmt/resource/changes/_changes_client.py | 128 ++ .../mgmt/resource/changes/_configuration.py | 76 + .../azure/mgmt/resource/changes/_patch.py | 21 + .../mgmt/resource/changes/_utils/__init__.py | 6 + .../resource/changes/_utils/serialization.py | 2041 +++++++++++++++++ .../azure/mgmt/resource/changes/_version.py | 9 + .../mgmt/resource/changes/aio/__init__.py | 29 + .../resource/changes/aio/_changes_client.py | 132 ++ .../resource/changes/aio/_configuration.py | 76 + .../azure/mgmt/resource/changes/aio/_patch.py | 21 + .../changes/aio/operations/__init__.py | 25 + .../changes/aio/operations/_operations.py | 238 ++ .../resource/changes/aio/operations/_patch.py | 21 + .../mgmt/resource/changes/models/__init__.py | 52 + .../changes/models/_changes_client_enums.py | 41 + .../resource/changes/models/_models_py3.py | 352 +++ .../mgmt/resource/changes/models/_patch.py | 21 + .../resource/changes/operations/__init__.py | 25 + .../changes/operations/_operations.py | 324 +++ .../resource/changes/operations/_patch.py | 21 + .../azure/mgmt/resource/changes/py.typed | 1 + .../dev_requirements.txt | 6 + .../generated_samples/get_change.py | 46 + .../generated_samples/list_changes.py | 46 + .../generated_tests/conftest.py | 35 + .../test_changes_changes_operations.py | 48 + .../test_changes_changes_operations_async.py | 49 + .../pyproject.toml | 87 + .../tests/conftest.py | 35 + ...t_changes_changes_operations_async_test.py | 53 + .../test_changes_changes_operations_test.py | 54 + 41 files changed, 4283 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-changes/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-changes/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-changes/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-changes/README.md create mode 100644 sdk/resources/azure-mgmt-resource-changes/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-changes/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_changes_client.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_changes_client.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_changes_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-changes/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-changes/generated_samples/get_change.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/generated_samples/list_changes.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-changes/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-changes/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-changes/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-changes/LICENSE b/sdk/resources/azure-mgmt-resource-changes/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-changes/MANIFEST.in b/sdk/resources/azure-mgmt-resource-changes/MANIFEST.in new file mode 100644 index 000000000000..576fc0369823 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/changes/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-changes/README.md b/sdk/resources/azure-mgmt-resource-changes/README.md new file mode 100644 index 000000000000..2c7acc09cee5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Changes Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-changes +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.changes import ChangesClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ChangesClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Changes Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-changes/_metadata.json b/sdk/resources/azure-mgmt-resource-changes/_metadata.json new file mode 100644 index 000000000000..e17f9c4eb4b6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Resources/changes/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-changes-2022-05 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Resources/changes/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-changes/apiview-properties.json b/sdk/resources/azure-mgmt-resource-changes/apiview-properties.json new file mode 100644 index 000000000000..0928d57c12ec --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/apiview-properties.json @@ -0,0 +1,21 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.changes.models.ChangeAttributes": null, + "azure.mgmt.resource.changes.models.ChangeBase": null, + "azure.mgmt.resource.changes.models.ChangeProperties": null, + "azure.mgmt.resource.changes.models.ChangeResourceListResult": null, + "azure.mgmt.resource.changes.models.Resource": null, + "azure.mgmt.resource.changes.models.ChangeResourceResult": null, + "azure.mgmt.resource.changes.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.changes.models.ErrorDetail": null, + "azure.mgmt.resource.changes.models.ErrorResponse": null, + "azure.mgmt.resource.changes.models.ChangeType": null, + "azure.mgmt.resource.changes.models.PropertyChangeType": null, + "azure.mgmt.resource.changes.models.ChangeCategory": null, + "azure.mgmt.resource.changes.operations.ChangesOperations.list": null, + "azure.mgmt.resource.changes.aio.operations.ChangesOperations.list": null, + "azure.mgmt.resource.changes.operations.ChangesOperations.get": null, + "azure.mgmt.resource.changes.aio.operations.ChangesOperations.get": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/__init__.py new file mode 100644 index 000000000000..885ce76f7c57 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._changes_client import ChangesClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_changes_client.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_changes_client.py new file mode 100644 index 000000000000..ffea993b03a6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_changes_client.py @@ -0,0 +1,128 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import ChangesClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ChangesOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ChangesClient: + """Changes Client. + + :ivar changes: ChangesOperations operations + :vartype changes: azure.mgmt.resource.changes.operations.ChangesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ChangesClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.changes = ChangesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_configuration.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_configuration.py new file mode 100644 index 000000000000..2a1b064553d3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_configuration.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ChangesClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ChangesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2022-05-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-changes/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_patch.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_version.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/__init__.py new file mode 100644 index 000000000000..acead607168e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._changes_client import ChangesClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_changes_client.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_changes_client.py new file mode 100644 index 000000000000..662a42571450 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_changes_client.py @@ -0,0 +1,132 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ChangesClientConfiguration +from .operations import ChangesOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ChangesClient: + """Changes Client. + + :ivar changes: ChangesOperations operations + :vartype changes: azure.mgmt.resource.changes.aio.operations.ChangesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ChangesClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.changes = ChangesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_configuration.py new file mode 100644 index 000000000000..d2d6fbd59cce --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_configuration.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ChangesClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ChangesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2022-05-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-changes/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_patch.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/__init__.py new file mode 100644 index 000000000000..8fe881f6b809 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ChangesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_operations.py new file mode 100644 index 000000000000..6dafb9831593 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_operations.py @@ -0,0 +1,238 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import build_changes_get_request, build_changes_list_request +from .._configuration import ChangesClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class ChangesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.changes.aio.ChangesClient`'s + :attr:`changes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ChangesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + top: int = 100, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.ChangeResourceResult"]: + """Obtains a list of change resources from the past 14 days for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param top: (Optional) Set the maximum number of results per response. Default value is 100. + :type top: int + :param skip_token: (Optional) The page-continuation token. Default value is None. + :type skip_token: str + :return: An iterator like instance of either ChangeResourceResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.changes.models.ChangeResourceResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChangeResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_changes_list_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ChangeResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + change_resource_id: str, + **kwargs: Any + ) -> _models.ChangeResourceResult: + """Obtains the specified change resource for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param change_resource_id: The ID of the change resource. Required. + :type change_resource_id: str + :return: ChangeResourceResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.changes.models.ChangeResourceResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChangeResourceResult] = kwargs.pop("cls", None) + + _request = build_changes_get_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + change_resource_id=change_resource_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ChangeResourceResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/__init__.py new file mode 100644 index 000000000000..402dae6f0312 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/__init__.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ChangeAttributes, + ChangeBase, + ChangeProperties, + ChangeResourceListResult, + ChangeResourceResult, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + Resource, +) + +from ._changes_client_enums import ( # type: ignore + ChangeCategory, + ChangeType, + PropertyChangeType, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangeAttributes", + "ChangeBase", + "ChangeProperties", + "ChangeResourceListResult", + "ChangeResourceResult", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Resource", + "ChangeCategory", + "ChangeType", + "PropertyChangeType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_changes_client_enums.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_changes_client_enums.py new file mode 100644 index 000000000000..996871a4dc8d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_changes_client_enums.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ChangeCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The entity that made the change.""" + + USER = "User" + """User initiated change""" + SYSTEM = "System" + """System initiated change""" + + +class ChangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of change that was captured in the resource.""" + + UPDATE = "Update" + """An existing resource underwent a change""" + DELETE = "Delete" + """An existing resource was deleted""" + CREATE = "Create" + """A newly created resource""" + + +class PropertyChangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of change that occurred.""" + + UPDATE = "Update" + """An existing property underwent a change""" + INSERT = "Insert" + """A property was newly created""" + REMOVE = "Remove" + """An existing property was deleted""" diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_models_py3.py new file mode 100644 index 000000000000..544c6786afef --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_models_py3.py @@ -0,0 +1,352 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class ChangeAttributes(_serialization.Model): + """Details about the change resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar correlation_id: The ARM correlation ID of the change resource. + :vartype correlation_id: str + :ivar timestamp: The time the change(s) on the target resource ocurred. + :vartype timestamp: str + :ivar changes_count: The number of changes this resource captures. + :vartype changes_count: int + :ivar previous_resource_snapshot_id: The GUID of the previous snapshot. + :vartype previous_resource_snapshot_id: str + :ivar new_resource_snapshot_id: The GUID of the new snapshot. + :vartype new_resource_snapshot_id: str + """ + + _validation = { + "correlation_id": {"readonly": True}, + "timestamp": {"readonly": True}, + "changes_count": {"readonly": True}, + "previous_resource_snapshot_id": {"readonly": True}, + "new_resource_snapshot_id": {"readonly": True}, + } + + _attribute_map = { + "correlation_id": {"key": "correlationId", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "str"}, + "changes_count": {"key": "changesCount", "type": "int"}, + "previous_resource_snapshot_id": {"key": "previousResourceSnapshotId", "type": "str"}, + "new_resource_snapshot_id": {"key": "newResourceSnapshotId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.correlation_id: Optional[str] = None + self.timestamp: Optional[str] = None + self.changes_count: Optional[int] = None + self.previous_resource_snapshot_id: Optional[str] = None + self.new_resource_snapshot_id: Optional[str] = None + + +class ChangeBase(_serialization.Model): + """An individual change on the target resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar property_change_type: The type of change that occurred. Known values are: "Update", + "Insert", and "Remove". + :vartype property_change_type: str or ~azure.mgmt.resource.changes.models.PropertyChangeType + :ivar change_category: The entity that made the change. Known values are: "User" and "System". + :vartype change_category: str or ~azure.mgmt.resource.changes.models.ChangeCategory + :ivar previous_value: The target resource property value before the change. + :vartype previous_value: str + :ivar new_value: The target resource property value after the change. + :vartype new_value: str + """ + + _validation = { + "property_change_type": {"readonly": True}, + "change_category": {"readonly": True}, + "previous_value": {"readonly": True}, + "new_value": {"readonly": True}, + } + + _attribute_map = { + "property_change_type": {"key": "propertyChangeType", "type": "str"}, + "change_category": {"key": "changeCategory", "type": "str"}, + "previous_value": {"key": "previousValue", "type": "str"}, + "new_value": {"key": "newValue", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.property_change_type: Optional[Union[str, "_models.PropertyChangeType"]] = None + self.change_category: Optional[Union[str, "_models.ChangeCategory"]] = None + self.previous_value: Optional[str] = None + self.new_value: Optional[str] = None + + +class ChangeProperties(_serialization.Model): + """The properties of a change. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar target_resource_id: The fully qualified ID of the target resource that was changed. + :vartype target_resource_id: str + :ivar target_resource_type: The namespace and type of the resource. + :vartype target_resource_type: str + :ivar change_type: The type of change that was captured in the resource. Known values are: + "Update", "Delete", and "Create". + :vartype change_type: str or ~azure.mgmt.resource.changes.models.ChangeType + :ivar change_attributes: Details about the change resource. + :vartype change_attributes: ~azure.mgmt.resource.changes.models.ChangeAttributes + :ivar changes: A dictionary with changed property name as a key and the change details as the + value. + :vartype changes: dict[str, ~azure.mgmt.resource.changes.models.ChangeBase] + """ + + _validation = { + "target_resource_id": {"readonly": True}, + "target_resource_type": {"readonly": True}, + "change_type": {"readonly": True}, + } + + _attribute_map = { + "target_resource_id": {"key": "targetResourceId", "type": "str"}, + "target_resource_type": {"key": "targetResourceType", "type": "str"}, + "change_type": {"key": "changeType", "type": "str"}, + "change_attributes": {"key": "changeAttributes", "type": "ChangeAttributes"}, + "changes": {"key": "changes", "type": "{ChangeBase}"}, + } + + def __init__( + self, + *, + change_attributes: Optional["_models.ChangeAttributes"] = None, + changes: Optional[dict[str, "_models.ChangeBase"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword change_attributes: Details about the change resource. + :paramtype change_attributes: ~azure.mgmt.resource.changes.models.ChangeAttributes + :keyword changes: A dictionary with changed property name as a key and the change details as + the value. + :paramtype changes: dict[str, ~azure.mgmt.resource.changes.models.ChangeBase] + """ + super().__init__(**kwargs) + self.target_resource_id: Optional[str] = None + self.target_resource_type: Optional[str] = None + self.change_type: Optional[Union[str, "_models.ChangeType"]] = None + self.change_attributes = change_attributes + self.changes = changes + + +class ChangeResourceListResult(_serialization.Model): + """The list of resources. + + :ivar next_link: The link used to get the next page of Change Resources. + :vartype next_link: str + :ivar value: The list of resources. + :vartype value: list[~azure.mgmt.resource.changes.models.ChangeResourceResult] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[ChangeResourceResult]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[list["_models.ChangeResourceResult"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of Change Resources. + :paramtype next_link: str + :keyword value: The list of resources. + :paramtype value: list[~azure.mgmt.resource.changes.models.ChangeResourceResult] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + + +class ChangeResourceResult(Resource): + """Change Resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The properties of a change. + :vartype properties: ~azure.mgmt.resource.changes.models.ChangeProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "ChangeProperties"}, + } + + def __init__(self, *, properties: Optional["_models.ChangeProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The properties of a change. + :paramtype properties: ~azure.mgmt.resource.changes.models.ChangeProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.changes.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.changes.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorDetail"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.resource.changes.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.resource.changes.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_patch.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/__init__.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/__init__.py new file mode 100644 index 000000000000..8fe881f6b809 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ChangesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_operations.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_operations.py new file mode 100644 index 000000000000..e430f1cef8ab --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_operations.py @@ -0,0 +1,324 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import ChangesClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_changes_list_request( + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + top: int = 100, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=100, minimum=1) + if skip_token is not None: + _params["$skipToken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_changes_get_request( + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + change_resource_id: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes/{changeResourceId}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "changeResourceId": _SERIALIZER.url("change_resource_id", change_resource_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ChangesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.changes.ChangesClient`'s + :attr:`changes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ChangesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + top: int = 100, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.ChangeResourceResult"]: + """Obtains a list of change resources from the past 14 days for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param top: (Optional) Set the maximum number of results per response. Default value is 100. + :type top: int + :param skip_token: (Optional) The page-continuation token. Default value is None. + :type skip_token: str + :return: An iterator like instance of either ChangeResourceResult or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.changes.models.ChangeResourceResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChangeResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_changes_list_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ChangeResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + change_resource_id: str, + **kwargs: Any + ) -> _models.ChangeResourceResult: + """Obtains the specified change resource for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param change_resource_id: The ID of the change resource. Required. + :type change_resource_id: str + :return: ChangeResourceResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.changes.models.ChangeResourceResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChangeResourceResult] = kwargs.pop("cls", None) + + _request = build_changes_get_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + change_resource_id=change_resource_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ChangeResourceResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_patch.py b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/py.typed b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/azure/mgmt/resource/changes/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-changes/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-changes/dev_requirements.txt new file mode 100644 index 000000000000..eef1165788ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/dev_requirements.txt @@ -0,0 +1,6 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +../../logic/azure-mgmt-logic +aiohttp diff --git a/sdk/resources/azure-mgmt-resource-changes/generated_samples/get_change.py b/sdk/resources/azure-mgmt-resource-changes/generated_samples/get_change.py new file mode 100644 index 000000000000..fca8688b1273 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/generated_samples/get_change.py @@ -0,0 +1,46 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.changes import ChangesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-changes +# USAGE + python get_change.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ChangesClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId1", + ) + + response = client.changes.get( + resource_group_name="resourceGroup1", + resource_provider_namespace="resourceProvider1", + resource_type="resourceType1", + resource_name="resourceName1", + change_resource_id="1d58d72f-0719-4a48-9228-b7ea682885bf", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/changes/stable/2022-05-01/examples/GetChange.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-changes/generated_samples/list_changes.py b/sdk/resources/azure-mgmt-resource-changes/generated_samples/list_changes.py new file mode 100644 index 000000000000..f4ea43a8a706 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/generated_samples/list_changes.py @@ -0,0 +1,46 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.changes import ChangesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-changes +# USAGE + python list_changes.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ChangesClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId1", + ) + + response = client.changes.list( + resource_group_name="resourceGroup1", + resource_provider_namespace="resourceProvider1", + resource_type="resourceType1", + resource_name="resourceName1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/changes/stable/2022-05-01/examples/ListChanges.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-changes/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-changes/generated_tests/conftest.py new file mode 100644 index 000000000000..23079c6d18ed --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + changes_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + changes_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + changes_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + changes_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations.py b/sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations.py new file mode 100644 index 000000000000..8b735a43fbf2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.changes import ChangesClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestChangesChangesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ChangesClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_changes_list(self, resource_group): + response = self.client.changes.list( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + resource_type="str", + resource_name="str", + api_version="2022-05-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_changes_get(self, resource_group): + response = self.client.changes.get( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + resource_type="str", + resource_name="str", + change_resource_id="str", + api_version="2022-05-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations_async.py b/sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations_async.py new file mode 100644 index 000000000000..3ed263a8c02b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/generated_tests/test_changes_changes_operations_async.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.changes.aio import ChangesClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestChangesChangesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ChangesClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_changes_list(self, resource_group): + response = self.client.changes.list( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + resource_type="str", + resource_name="str", + api_version="2022-05-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_changes_get(self, resource_group): + response = await self.client.changes.get( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + resource_type="str", + resource_name="str", + change_resource_id="str", + api_version="2022-05-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-changes/pyproject.toml b/sdk/resources/azure-mgmt-resource-changes/pyproject.toml new file mode 100644 index 000000000000..676e9ebe98a4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-changes" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Changes Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.changes._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-changes" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Changes Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "ChangesClient" diff --git a/sdk/resources/azure-mgmt-resource-changes/tests/conftest.py b/sdk/resources/azure-mgmt-resource-changes/tests/conftest.py new file mode 100644 index 000000000000..23079c6d18ed --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + changes_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + changes_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + changes_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + changes_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=changes_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_async_test.py b/sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_async_test.py new file mode 100644 index 000000000000..6cc7aec4d357 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_async_test.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +import azure.mgmt.logic as az_logic +from azure.mgmt.resource.changes.aio import ChangesClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestChangesChangesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ChangesClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_changes_list_for_workflow(self, resource_group): + # use sync logic management client from async test + logic_client = self.create_mgmt_client(az_logic.LogicManagementClient) + + workflow_name = self.get_resource_name("workflow") + workflow = az_logic.models.Workflow( + location=AZURE_LOCATION, + definition={ + "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "triggers": {}, + "actions": {}, + "outputs": {}, + }, + ) + + logic_client.workflows.create_or_update(resource_group.name, workflow_name, workflow) + + try: + response = self.client.changes.list( + resource_group_name=resource_group.name, + resource_provider_namespace="Microsoft.Logic", + resource_type="workflows", + resource_name=workflow_name, + ) + _ = [r async for r in response] + finally: + logic_client.workflows.delete(resource_group.name, workflow_name) diff --git a/sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_test.py b/sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_test.py new file mode 100644 index 000000000000..53b665a613ca --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-changes/tests/test_changes_changes_operations_test.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +import azure.mgmt.logic as az_logic +from azure.mgmt.resource.changes import ChangesClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestChangesChangesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ChangesClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_changes_list_for_workflow(self, resource_group): + logic_client = self.create_mgmt_client(az_logic.LogicManagementClient) + + # create a workflow as the target resource + workflow_name = self.get_resource_name("workflow") + workflow = az_logic.models.Workflow( + location=AZURE_LOCATION, + definition={ + "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "triggers": {}, + "actions": {}, + "outputs": {}, + }, + ) + + logic_client.workflows.create_or_update(resource_group.name, workflow_name, workflow) + + try: + response = self.client.changes.list( + resource_group_name=resource_group.name, + resource_provider_namespace="Microsoft.Logic", + resource_type="workflows", + resource_name=workflow_name, + ) + # Just ensure the call succeeds and returns an iterable + _ = [r for r in response] + finally: + # Best-effort cleanup of the workflow + logic_client.workflows.delete(resource_group.name, workflow_name) From 015e7bf48cc5c823d86d67fb3c551cd7982abd95 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 00:54:24 -0800 Subject: [PATCH 60/84] [AutoRelease] t2-resource-locks-2026-02-05-86806(can only be merged by SDK owner) (#45021) * code and test * update --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 Co-authored-by: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> --- .../azure-mgmt-resource-locks/CHANGELOG.md | 7 + .../azure-mgmt-resource-locks/LICENSE | 21 + .../azure-mgmt-resource-locks/MANIFEST.in | 8 + .../azure-mgmt-resource-locks/README.md | 61 + .../azure-mgmt-resource-locks/_metadata.json | 11 + .../apiview-properties.json | 46 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/resource/__init__.py | 1 + .../azure/mgmt/resource/locks/__init__.py | 32 + .../mgmt/resource/locks/_configuration.py | 75 + .../resource/locks/_management_lock_client.py | 135 ++ .../azure/mgmt/resource/locks/_patch.py | 21 + .../mgmt/resource/locks/_utils/__init__.py | 6 + .../resource/locks/_utils/serialization.py | 2041 ++++++++++++++++ .../azure/mgmt/resource/locks/_version.py | 9 + .../azure/mgmt/resource/locks/aio/__init__.py | 29 + .../mgmt/resource/locks/aio/_configuration.py | 75 + .../locks/aio/_management_lock_client.py | 139 ++ .../azure/mgmt/resource/locks/aio/_patch.py | 21 + .../resource/locks/aio/operations/__init__.py | 27 + .../locks/aio/operations/_operations.py | 1590 +++++++++++++ .../resource/locks/aio/operations/_patch.py | 21 + .../mgmt/resource/locks/models/__init__.py | 42 + .../models/_management_lock_client_enums.py | 21 + .../mgmt/resource/locks/models/_models_py3.py | 231 ++ .../mgmt/resource/locks/models/_patch.py | 21 + .../resource/locks/operations/__init__.py | 27 + .../resource/locks/operations/_operations.py | 2117 +++++++++++++++++ .../mgmt/resource/locks/operations/_patch.py | 21 + .../azure/mgmt/resource/locks/py.typed | 1 + .../dev_requirements.txt | 5 + .../list_provider_operations.py | 41 + ...reate_or_update_at_resource_group_level.py | 44 + ...ocks_create_or_update_at_resource_level.py | 48 + ...agement_locks_create_or_update_at_scope.py | 44 + ..._create_or_update_at_subscription_level.py | 43 + ...nt_locks_delete_at_resource_group_level.py | 42 + ...nagement_locks_delete_at_resource_level.py | 46 + .../management_locks_delete_at_scope.py | 42 + ...ment_locks_delete_at_subscription_level.py | 41 + ...ement_locks_get_at_resource_group_level.py | 43 + .../management_locks_get_at_resource_level.py | 47 + .../management_locks_get_at_scope.py | 43 + ...agement_locks_get_at_subscription_level.py | 42 + ...ment_locks_list_at_resource_group_level.py | 43 + ...management_locks_list_at_resource_level.py | 47 + .../management_locks_list_at_scope.py | 43 + ...gement_locks_list_at_subscription_level.py | 41 + .../generated_tests/conftest.py | 35 + ...ock_authorization_operations_operations.py | 29 + ...thorization_operations_operations_async.py | 30 + ...gement_lock_management_locks_operations.py | 251 ++ ..._lock_management_locks_operations_async.py | 252 ++ .../azure-mgmt-resource-locks/pyproject.toml | 87 + .../tests/conftest.py | 35 + ...zation_operations_operations_async_test.py | 27 + ...uthorization_operations_operations_test.py | 26 + ..._management_locks_operations_async_test.py | 36 + ...t_lock_management_locks_operations_test.py | 35 + 60 files changed, 8447 insertions(+) create mode 100644 sdk/resources/azure-mgmt-resource-locks/CHANGELOG.md create mode 100644 sdk/resources/azure-mgmt-resource-locks/LICENSE create mode 100644 sdk/resources/azure-mgmt-resource-locks/MANIFEST.in create mode 100644 sdk/resources/azure-mgmt-resource-locks/README.md create mode 100644 sdk/resources/azure-mgmt-resource-locks/_metadata.json create mode 100644 sdk/resources/azure-mgmt-resource-locks/apiview-properties.json create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_management_lock_client.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/serialization.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_version.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_configuration.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_management_lock_client.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_management_lock_client_enums.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_models_py3.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/__init__.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_patch.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/py.typed create mode 100644 sdk/resources/azure-mgmt-resource-locks/dev_requirements.txt create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/list_provider_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_group_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_scope.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_subscription_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_group_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_scope.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_subscription_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_group_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_scope.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_subscription_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_group_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_scope.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_subscription_level.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations_async.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/pyproject.toml create mode 100644 sdk/resources/azure-mgmt-resource-locks/tests/conftest.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_test.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_async_test.py create mode 100644 sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource-locks/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-locks/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-locks/LICENSE b/sdk/resources/azure-mgmt-resource-locks/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-locks/MANIFEST.in b/sdk/resources/azure-mgmt-resource-locks/MANIFEST.in new file mode 100644 index 000000000000..79243268825d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/locks/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-locks/README.md b/sdk/resources/azure-mgmt-resource-locks/README.md new file mode 100644 index 000000000000..d2ea1901b501 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Locks Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-locks +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.locks import ManagementLockClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ManagementLockClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Locks Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-locks/_metadata.json b/sdk/resources/azure-mgmt-resource-locks/_metadata.json new file mode 100644 index 000000000000..5a36fd767a16 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "94cec42b293ffaaf67b51ac86235819e6c4886b3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Authorization/locks/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-locks-2016-09 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Authorization/locks/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-locks/apiview-properties.json b/sdk/resources/azure-mgmt-resource-locks/apiview-properties.json new file mode 100644 index 000000000000..e683238febba --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/apiview-properties.json @@ -0,0 +1,46 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.locks.models.ManagementLockListResult": null, + "azure.mgmt.resource.locks.models.ManagementLockObject": null, + "azure.mgmt.resource.locks.models.ManagementLockOwner": null, + "azure.mgmt.resource.locks.models.Operation": null, + "azure.mgmt.resource.locks.models.OperationDisplay": null, + "azure.mgmt.resource.locks.models.OperationListResult": null, + "azure.mgmt.resource.locks.models.LockLevel": null, + "azure.mgmt.resource.locks.operations.AuthorizationOperationsOperations.list": null, + "azure.mgmt.resource.locks.aio.operations.AuthorizationOperationsOperations.list": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.create_or_update_at_resource_group_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.create_or_update_at_resource_group_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.delete_at_resource_group_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.delete_at_resource_group_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.get_at_resource_group_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.get_at_resource_group_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.create_or_update_by_scope": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.create_or_update_by_scope": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.delete_by_scope": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.delete_by_scope": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.get_by_scope": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.get_by_scope": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.create_or_update_at_resource_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.create_or_update_at_resource_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.delete_at_resource_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.delete_at_resource_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.get_at_resource_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.get_at_resource_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.create_or_update_at_subscription_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.create_or_update_at_subscription_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.delete_at_subscription_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.delete_at_subscription_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.get_at_subscription_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.get_at_subscription_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.list_at_resource_group_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.list_at_resource_group_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.list_at_resource_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.list_at_resource_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.list_at_subscription_level": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.list_at_subscription_level": null, + "azure.mgmt.resource.locks.operations.ManagementLocksOperations.list_by_scope": null, + "azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations.list_by_scope": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/__init__.py new file mode 100644 index 000000000000..1e35dbc6c246 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._management_lock_client import ManagementLockClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_configuration.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_configuration.py new file mode 100644 index 000000000000..51c7c413613c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ManagementLockClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-locks/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_management_lock_client.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_management_lock_client.py new file mode 100644 index 000000000000..a4c0d493c0e1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_management_lock_client.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import ManagementLockClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import AuthorizationOperationsOperations, ManagementLocksOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ManagementLockClient: + """ManagementLock Client. + + :ivar authorization_operations: AuthorizationOperationsOperations operations + :vartype authorization_operations: + azure.mgmt.resource.locks.operations.AuthorizationOperationsOperations + :ivar management_locks: ManagementLocksOperations operations + :vartype management_locks: azure.mgmt.resource.locks.operations.ManagementLocksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ManagementLockClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.authorization_operations = AuthorizationOperationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.management_locks = ManagementLocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_patch.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_version.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/__init__.py new file mode 100644 index 000000000000..fc55901ba15e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._management_lock_client import ManagementLockClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_configuration.py new file mode 100644 index 000000000000..755079b6bbf4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLockClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-locks/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_management_lock_client.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_management_lock_client.py new file mode 100644 index 000000000000..2cc16a16886c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_management_lock_client.py @@ -0,0 +1,139 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ManagementLockClientConfiguration +from .operations import AuthorizationOperationsOperations, ManagementLocksOperations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLockClient: + """ManagementLock Client. + + :ivar authorization_operations: AuthorizationOperationsOperations operations + :vartype authorization_operations: + azure.mgmt.resource.locks.aio.operations.AuthorizationOperationsOperations + :ivar management_locks: ManagementLocksOperations operations + :vartype management_locks: azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ManagementLockClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.authorization_operations = AuthorizationOperationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.management_locks = ManagementLocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_patch.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/__init__.py new file mode 100644 index 000000000000..624473253c54 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import AuthorizationOperationsOperations # type: ignore +from ._operations import ManagementLocksOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AuthorizationOperationsOperations", + "ManagementLocksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_operations.py new file mode 100644 index 000000000000..557e7ccb2c8c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_operations.py @@ -0,0 +1,1590 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_authorization_operations_list_request, + build_management_locks_create_or_update_at_resource_group_level_request, + build_management_locks_create_or_update_at_resource_level_request, + build_management_locks_create_or_update_at_subscription_level_request, + build_management_locks_create_or_update_by_scope_request, + build_management_locks_delete_at_resource_group_level_request, + build_management_locks_delete_at_resource_level_request, + build_management_locks_delete_at_subscription_level_request, + build_management_locks_delete_by_scope_request, + build_management_locks_get_at_resource_group_level_request, + build_management_locks_get_at_resource_level_request, + build_management_locks_get_at_subscription_level_request, + build_management_locks_get_by_scope_request, + build_management_locks_list_at_resource_group_level_request, + build_management_locks_list_at_resource_level_request, + build_management_locks_list_at_subscription_level_request, + build_management_locks_list_by_scope_request, +) +from .._configuration import ManagementLockClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class AuthorizationOperationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.aio.ManagementLockClient`'s + :attr:`authorization_operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Authorization REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_authorization_operations_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ManagementLocksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.aio.ManagementLockClient`'s + :attr:`management_locks` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO[bytes]], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_resource_group_level(self, resource_group_name: str, lock_name: str, **kwargs: Any) -> None: + """Deletes a management lock at the resource group level. + + To delete management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the lock. Required. + :type resource_group_name: str + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_resource_group_level( + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> _models.ManagementLockObject: + """Gets a management lock at the resource group level. + + :param resource_group_name: The name of the locked resource group. Required. + :type resource_group_name: str + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_by_scope( + self, + scope: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_scope( + self, + scope: str, + lock_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_scope( + self, scope: str, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Is either a + ManagementLockObject type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> None: + """Delete a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Get a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO[bytes]], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Is either a + ManagementLockObject type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> None: + """Deletes the management lock of a resource or any level below the resource. + + To delete management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource with the + lock to delete. Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource with the + lock to delete. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource with the lock to delete. Required. + :type resource_type: str + :param resource_name: The name of the resource with the lock to delete. Required. + :type resource_name: str + :param lock_name: The name of the lock to delete. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> _models.ManagementLockObject: + """Get the management lock of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: An extra path parameter needed in some services, like SQL + Databases. Required. + :type parent_resource_path: str + :param resource_type: The type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_at_subscription_level( + self, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_subscription_level( + self, lock_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_subscription_level( + self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_subscription_level(self, lock_name: str, **kwargs: Any) -> None: + """Deletes the management lock at the subscription level. + + To delete management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_subscription_level(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Gets a management lock at the subscription level. + + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_at_resource_group_level( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a resource group. + + :param resource_group_name: The name of the resource group containing the locks to get. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_at_resource_group_level_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a resource or any level below resource. + + :param resource_group_name: The name of the resource group containing the locked resource. The + name is case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the locked resource. Required. + :type resource_type: str + :param resource_name: The name of the locked resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_at_subscription_level( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_at_subscription_level_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_by_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/__init__.py new file mode 100644 index 000000000000..635bdfd36740 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/__init__.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ManagementLockListResult, + ManagementLockObject, + ManagementLockOwner, + Operation, + OperationDisplay, + OperationListResult, +) + +from ._management_lock_client_enums import ( # type: ignore + LockLevel, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockListResult", + "ManagementLockObject", + "ManagementLockOwner", + "Operation", + "OperationDisplay", + "OperationListResult", + "LockLevel", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_management_lock_client_enums.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_management_lock_client_enums.py new file mode 100644 index 000000000000..672293de07fe --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_management_lock_client_enums.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class LockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete + means authorized users are able to read and modify the resources, but not delete. ReadOnly + means authorized users can only read from a resource, but they can't modify or delete it. + """ + + NOT_SPECIFIED = "NotSpecified" + CAN_NOT_DELETE = "CanNotDelete" + READ_ONLY = "ReadOnly" diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_models_py3.py new file mode 100644 index 000000000000..c930fded0649 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_models_py3.py @@ -0,0 +1,231 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models + + +class ManagementLockListResult(_serialization.Model): + """The list of locks. + + :ivar value: The list of locks. + :vartype value: list[~azure.mgmt.resource.locks.models.ManagementLockObject] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ManagementLockObject]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.ManagementLockObject"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The list of locks. + :paramtype value: list[~azure.mgmt.resource.locks.models.ManagementLockObject] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ManagementLockObject(_serialization.Model): + """The lock information. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The resource ID of the lock. + :vartype id: str + :ivar type: The resource type of the lock - Microsoft.Authorization/locks. + :vartype type: str + :ivar name: The name of the lock. + :vartype name: str + :ivar level: The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. + CanNotDelete means authorized users are able to read and modify the resources, but not delete. + ReadOnly means authorized users can only read from a resource, but they can't modify or delete + it. Required. Known values are: "NotSpecified", "CanNotDelete", and "ReadOnly". + :vartype level: str or ~azure.mgmt.resource.locks.models.LockLevel + :ivar notes: Notes about the lock. Maximum of 512 characters. + :vartype notes: str + :ivar owners: The owners of the lock. + :vartype owners: list[~azure.mgmt.resource.locks.models.ManagementLockOwner] + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "level": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "level": {"key": "properties.level", "type": "str"}, + "notes": {"key": "properties.notes", "type": "str"}, + "owners": {"key": "properties.owners", "type": "[ManagementLockOwner]"}, + } + + def __init__( + self, + *, + level: Union[str, "_models.LockLevel"], + notes: Optional[str] = None, + owners: Optional[list["_models.ManagementLockOwner"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword level: The level of the lock. Possible values are: NotSpecified, CanNotDelete, + ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but + not delete. ReadOnly means authorized users can only read from a resource, but they can't + modify or delete it. Required. Known values are: "NotSpecified", "CanNotDelete", and + "ReadOnly". + :paramtype level: str or ~azure.mgmt.resource.locks.models.LockLevel + :keyword notes: Notes about the lock. Maximum of 512 characters. + :paramtype notes: str + :keyword owners: The owners of the lock. + :paramtype owners: list[~azure.mgmt.resource.locks.models.ManagementLockOwner] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.type: Optional[str] = None + self.name: Optional[str] = None + self.level = level + self.notes = notes + self.owners = owners + + +class ManagementLockOwner(_serialization.Model): + """Lock owner properties. + + :ivar application_id: The application ID of the lock owner. + :vartype application_id: str + """ + + _attribute_map = { + "application_id": {"key": "applicationId", "type": "str"}, + } + + def __init__(self, *, application_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword application_id: The application ID of the lock owner. + :paramtype application_id: str + """ + super().__init__(**kwargs) + self.application_id = application_id + + +class Operation(_serialization.Model): + """Microsoft.Authorization operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.locks.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.locks.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Authorization. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Authorization. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Authorization operations. It contains a list of + operations and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Authorization operations. + :vartype value: list[~azure.mgmt.resource.locks.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Authorization operations. + :paramtype value: list[~azure.mgmt.resource.locks.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_patch.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/__init__.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/__init__.py new file mode 100644 index 000000000000..624473253c54 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import AuthorizationOperationsOperations # type: ignore +from ._operations import ManagementLocksOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AuthorizationOperationsOperations", + "ManagementLocksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_operations.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_operations.py new file mode 100644 index 000000000000..c8aa945ea695 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_operations.py @@ -0,0 +1,2117 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import ManagementLockClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_authorization_operations_list_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_resource_group_level_request( # pylint: disable=name-too-long + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_resource_group_level_request( # pylint: disable=name-too-long + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_resource_group_level_request( # pylint: disable=name-too-long + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_by_scope_request( # pylint: disable=name-too-long + scope: str, lock_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_by_scope_request( # pylint: disable=name-too-long + scope: str, lock_name: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_by_scope_request( # pylint: disable=name-too-long + scope: str, lock_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_resource_level_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_resource_level_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_resource_level_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_subscription_level_request( # pylint: disable=name-too-long + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_subscription_level_request( # pylint: disable=name-too-long + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_subscription_level_request( # pylint: disable=name-too-long + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_resource_group_level_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_resource_level_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks", + ) + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_subscription_level_request( # pylint: disable=name-too-long + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_by_scope_request( # pylint: disable=name-too-long + scope: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AuthorizationOperationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.ManagementLockClient`'s + :attr:`authorization_operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """Lists all of the available Microsoft.Authorization REST API operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_authorization_operations_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ManagementLocksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.ManagementLockClient`'s + :attr:`management_locks` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO[bytes]], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_resource_group_level( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> None: + """Deletes a management lock at the resource group level. + + To delete management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the lock. Required. + :type resource_group_name: str + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_resource_group_level( + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> _models.ManagementLockObject: + """Gets a management lock at the resource group level. + + :param resource_group_name: The name of the locked resource group. Required. + :type resource_group_name: str + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_by_scope( + self, + scope: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_scope( + self, + scope: str, + lock_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_scope( + self, scope: str, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Is either a + ManagementLockObject type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, lock_name: str, **kwargs: Any + ) -> None: + """Delete a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Get a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO[bytes]], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Is either a + ManagementLockObject type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_resource_level( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> None: + """Deletes the management lock of a resource or any level below the resource. + + To delete management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource with the + lock to delete. Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource with the + lock to delete. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource with the lock to delete. Required. + :type resource_type: str + :param resource_name: The name of the resource with the lock to delete. Required. + :type resource_name: str + :param lock_name: The name of the lock to delete. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> _models.ManagementLockObject: + """Get the management lock of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: An extra path parameter needed in some services, like SQL + Databases. Required. + :type parent_resource_path: str + :param resource_type: The type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_at_subscription_level( + self, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_subscription_level( + self, lock_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_subscription_level( + self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \\, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + _request = build_management_locks_create_or_update_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_subscription_level( # pylint: disable=inconsistent-return-statements + self, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock at the subscription level. + + To delete management locks, you must have access to Microsoft.Authorization/\\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_locks_delete_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_subscription_level(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Gets a management lock at the subscription level. + + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + _request = build_management_locks_get_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_at_resource_group_level( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a resource group. + + :param resource_group_name: The name of the resource group containing the locks to get. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_at_resource_group_level_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a resource or any level below resource. + + :param resource_group_name: The name of the resource group containing the locked resource. The + name is case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the locked resource. Required. + :type resource_type: str + :param resource_name: The name of the locked resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_at_subscription_level( + self, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_at_subscription_level_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.ManagementLockObject"]: + """Gets all the management locks for a scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_locks_list_by_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_patch.py b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/py.typed b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/azure/mgmt/resource/locks/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-locks/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-locks/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/list_provider_operations.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/list_provider_operations.py new file mode 100644 index 000000000000..577e50eac6ca --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/list_provider_operations.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python list_provider_operations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.authorization_operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ListProviderOperations.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_group_level.py new file mode 100644 index 000000000000..be33f304f2a7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_group_level.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_create_or_update_at_resource_group_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.create_or_update_at_resource_group_level( + resource_group_name="resourcegroupname", + lock_name="testlock", + parameters={"properties": {"level": "ReadOnly"}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtResourceGroupLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_level.py new file mode 100644 index 000000000000..0167daaeb620 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_resource_level.py @@ -0,0 +1,48 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_create_or_update_at_resource_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.create_or_update_at_resource_level( + resource_group_name="resourcegroupname", + resource_provider_namespace="Microsoft.Storage", + parent_resource_path="parentResourcePath", + resource_type="storageAccounts", + resource_name="teststorageaccount", + lock_name="testlock", + parameters={"properties": {"level": "ReadOnly"}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtResourceLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_scope.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_scope.py new file mode 100644 index 000000000000..afb6bdfe2f55 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_scope.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_create_or_update_at_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.management_locks.create_or_update_by_scope( + scope="subscriptions/subscriptionId", + lock_name="testlock", + parameters={"properties": {"level": "ReadOnly"}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtScope.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_subscription_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_subscription_level.py new file mode 100644 index 000000000000..c0a2966ba59a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_create_or_update_at_subscription_level.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_create_or_update_at_subscription_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.create_or_update_at_subscription_level( + lock_name="testlock", + parameters={"properties": {"level": "ReadOnly"}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtSubscriptionLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_group_level.py new file mode 100644 index 000000000000..150da9dba5b3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_group_level.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_delete_at_resource_group_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + client.management_locks.delete_at_resource_group_level( + resource_group_name="resourcegroupname", + lock_name="testlock", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_DeleteAtResourceGroupLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_level.py new file mode 100644 index 000000000000..f5c6db49912c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_resource_level.py @@ -0,0 +1,46 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_delete_at_resource_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + client.management_locks.delete_at_resource_level( + resource_group_name="resourcegroupname", + resource_provider_namespace="Microsoft.Storage", + parent_resource_path="parentResourcePath", + resource_type="storageAccounts", + resource_name="teststorageaccount", + lock_name="testlock", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_DeleteAtResourceLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_scope.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_scope.py new file mode 100644 index 000000000000..f424248732c1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_scope.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_delete_at_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.management_locks.delete_by_scope( + scope="subscriptions/subscriptionId", + lock_name="testlock", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_DeleteAtScope.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_subscription_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_subscription_level.py new file mode 100644 index 000000000000..0683f990af72 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_delete_at_subscription_level.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_delete_at_subscription_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + client.management_locks.delete_at_subscription_level( + lock_name="testlock", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_DeleteAtSubscriptionLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_group_level.py new file mode 100644 index 000000000000..118b46283af5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_group_level.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_get_at_resource_group_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.get_at_resource_group_level( + resource_group_name="resourcegroupname", + lock_name="testlock", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_GetAtResourceGroupLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_level.py new file mode 100644 index 000000000000..8f6e8bb1d053 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_resource_level.py @@ -0,0 +1,47 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_get_at_resource_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.get_at_resource_level( + resource_group_name="resourcegroupname", + resource_provider_namespace="Microsoft.Storage", + parent_resource_path="parentResourcePath", + resource_type="storageAccounts", + resource_name="teststorageaccount", + lock_name="testlock", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_GetAtResourceLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_scope.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_scope.py new file mode 100644 index 000000000000..372affa2f5ba --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_scope.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_get_at_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.management_locks.get_by_scope( + scope="subscriptions/subscriptionId", + lock_name="testlock", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_GetAtScope.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_subscription_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_subscription_level.py new file mode 100644 index 000000000000..7e59d6644144 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_get_at_subscription_level.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_get_at_subscription_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.get_at_subscription_level( + lock_name="testlock", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_GetAtSubscriptionLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_group_level.py new file mode 100644 index 000000000000..4b8e3e0f4f1e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_group_level.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_list_at_resource_group_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.list_at_resource_group_level( + resource_group_name="resourcegroupname", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_ListAtResourceGroupLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_level.py new file mode 100644 index 000000000000..dd3c2f05c2cd --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_resource_level.py @@ -0,0 +1,47 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_list_at_resource_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.list_at_resource_level( + resource_group_name="resourcegroupname", + resource_provider_namespace="Microsoft.Storage", + parent_resource_path="parentResourcePath", + resource_type="storageAccounts", + resource_name="teststorageaccount", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_ListAtResourceLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_scope.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_scope.py new file mode 100644 index 000000000000..a9d873869d07 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_scope.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_list_at_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.management_locks.list_by_scope( + scope="subscriptions/subscriptionId", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_ListAtScope.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_subscription_level.py b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_subscription_level.py new file mode 100644 index 000000000000..e3f29d7d84b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_samples/management_locks_list_at_subscription_level.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.locks import ManagementLockClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-locks +# USAGE + python management_locks_list_at_subscription_level.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ManagementLockClient( + credential=DefaultAzureCredential(), + subscription_id="subscriptionId", + ) + + response = client.management_locks.list_at_subscription_level() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/locks/stable/2016-09-01/examples/ManagementLocks_ListAtSubscriptionLevel.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-locks/generated_tests/conftest.py new file mode 100644 index 000000000000..6fac9703ac50 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementlock_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + managementlock_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementlock_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementlock_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations.py b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations.py new file mode 100644 index 000000000000..887ea3a8f653 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLockAuthorizationOperationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_authorization_operations_list(self, resource_group): + response = self.client.authorization_operations.list( + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations_async.py b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations_async.py new file mode 100644 index 000000000000..1e0b09f2ed97 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_authorization_operations_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks.aio import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLockAuthorizationOperationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_authorization_operations_list(self, resource_group): + response = self.client.authorization_operations.list( + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations.py b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations.py new file mode 100644 index 000000000000..b636617fc4f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations.py @@ -0,0 +1,251 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLockManagementLocksOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_create_or_update_at_resource_group_level(self, resource_group): + response = self.client.management_locks.create_or_update_at_resource_group_level( + resource_group_name=resource_group.name, + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_delete_at_resource_group_level(self, resource_group): + response = self.client.management_locks.delete_at_resource_group_level( + resource_group_name=resource_group.name, + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_get_at_resource_group_level(self, resource_group): + response = self.client.management_locks.get_at_resource_group_level( + resource_group_name=resource_group.name, + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_create_or_update_by_scope(self, resource_group): + response = self.client.management_locks.create_or_update_by_scope( + scope="str", + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_delete_by_scope(self, resource_group): + response = self.client.management_locks.delete_by_scope( + scope="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_get_by_scope(self, resource_group): + response = self.client.management_locks.get_by_scope( + scope="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_create_or_update_at_resource_level(self, resource_group): + response = self.client.management_locks.create_or_update_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_delete_at_resource_level(self, resource_group): + response = self.client.management_locks.delete_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_get_at_resource_level(self, resource_group): + response = self.client.management_locks.get_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_create_or_update_at_subscription_level(self, resource_group): + response = self.client.management_locks.create_or_update_at_subscription_level( + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_delete_at_subscription_level(self, resource_group): + response = self.client.management_locks.delete_at_subscription_level( + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_get_at_subscription_level(self, resource_group): + response = self.client.management_locks.get_at_subscription_level( + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_list_at_resource_group_level(self, resource_group): + response = self.client.management_locks.list_at_resource_group_level( + resource_group_name=resource_group.name, + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_list_at_resource_level(self, resource_group): + response = self.client.management_locks.list_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_list_at_subscription_level(self, resource_group): + response = self.client.management_locks.list_at_subscription_level( + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_list_by_scope(self, resource_group): + response = self.client.management_locks.list_by_scope( + scope="str", + api_version="2016-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations_async.py b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations_async.py new file mode 100644 index 000000000000..986fda779d7e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/generated_tests/test_management_lock_management_locks_operations_async.py @@ -0,0 +1,252 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks.aio import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementLockManagementLocksOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_create_or_update_at_resource_group_level(self, resource_group): + response = await self.client.management_locks.create_or_update_at_resource_group_level( + resource_group_name=resource_group.name, + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_delete_at_resource_group_level(self, resource_group): + response = await self.client.management_locks.delete_at_resource_group_level( + resource_group_name=resource_group.name, + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_get_at_resource_group_level(self, resource_group): + response = await self.client.management_locks.get_at_resource_group_level( + resource_group_name=resource_group.name, + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_create_or_update_by_scope(self, resource_group): + response = await self.client.management_locks.create_or_update_by_scope( + scope="str", + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_delete_by_scope(self, resource_group): + response = await self.client.management_locks.delete_by_scope( + scope="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_get_by_scope(self, resource_group): + response = await self.client.management_locks.get_by_scope( + scope="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_create_or_update_at_resource_level(self, resource_group): + response = await self.client.management_locks.create_or_update_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_delete_at_resource_level(self, resource_group): + response = await self.client.management_locks.delete_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_get_at_resource_level(self, resource_group): + response = await self.client.management_locks.get_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_create_or_update_at_subscription_level(self, resource_group): + response = await self.client.management_locks.create_or_update_at_subscription_level( + lock_name="str", + parameters={ + "level": "str", + "id": "str", + "name": "str", + "notes": "str", + "owners": [{"applicationId": "str"}], + "type": "str", + }, + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_delete_at_subscription_level(self, resource_group): + response = await self.client.management_locks.delete_at_subscription_level( + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_get_at_subscription_level(self, resource_group): + response = await self.client.management_locks.get_at_subscription_level( + lock_name="str", + api_version="2016-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_list_at_resource_group_level(self, resource_group): + response = self.client.management_locks.list_at_resource_group_level( + resource_group_name=resource_group.name, + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_list_at_resource_level(self, resource_group): + response = self.client.management_locks.list_at_resource_level( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_list_at_subscription_level(self, resource_group): + response = self.client.management_locks.list_at_subscription_level( + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_list_by_scope(self, resource_group): + response = self.client.management_locks.list_by_scope( + scope="str", + api_version="2016-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-locks/pyproject.toml b/sdk/resources/azure-mgmt-resource-locks/pyproject.toml new file mode 100644 index 000000000000..46af792610a1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-locks" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Locks Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.locks._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-locks" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Locks Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "ManagementLockClient" diff --git a/sdk/resources/azure-mgmt-resource-locks/tests/conftest.py b/sdk/resources/azure-mgmt-resource-locks/tests/conftest.py new file mode 100644 index 000000000000..6fac9703ac50 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementlock_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + managementlock_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementlock_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementlock_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementlock_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_async_test.py b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_async_test.py new file mode 100644 index 000000000000..2de1cd1092c5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks.aio import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLockAuthorizationOperationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_authorization_operations_list(self, resource_group): + response = self.client.authorization_operations.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_test.py b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_test.py new file mode 100644 index 000000000000..b6df93ae5de1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_authorization_operations_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLockAuthorizationOperationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_authorization_operations_list(self, resource_group): + response = self.client.authorization_operations.list() + result = [r for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_async_test.py b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_async_test.py new file mode 100644 index 000000000000..5990ca6a0e8c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks.aio import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLockManagementLocksOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_list_at_resource_group_level(self, resource_group): + response = self.client.management_locks.list_at_resource_group_level( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert result == [] + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_locks_list_at_subscription_level(self, resource_group): + response = self.client.management_locks.list_at_subscription_level() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_test.py b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_test.py new file mode 100644 index 000000000000..651601c54f09 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-locks/tests/test_management_lock_management_locks_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.locks import ManagementLockClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementLockManagementLocksOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementLockClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_list_at_resource_group_level(self, resource_group): + response = self.client.management_locks.list_at_resource_group_level( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert result == [] + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_locks_list_at_subscription_level(self, resource_group): + response = self.client.management_locks.list_at_subscription_level() + result = [r for r in response] + assert response From 84e1b4328eb3a47b997f0f984982928ab31fc123 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 01:11:53 -0800 Subject: [PATCH 61/84] [AutoRelease] t2-agricultureplatform-2026-02-05-40775(can only be merged by SDK owner) (#45031) * code and test * Update sdk/agricultureplatform/azure-mgmt-agricultureplatform/CHANGELOG.md --------- Co-authored-by: azure-sdk Co-authored-by: Yuchao Yan Co-authored-by: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> --- .../CHANGELOG.md | 7 + .../azure-mgmt-agricultureplatform/LICENSE | 21 + .../MANIFEST.in | 7 + .../azure-mgmt-agricultureplatform/README.md | 61 + .../_metadata.json | 7 + .../apiview-properties.json | 53 + .../azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../mgmt/agricultureplatform/__init__.py | 32 + .../azure/mgmt/agricultureplatform/_client.py | 137 ++ .../agricultureplatform/_configuration.py | 80 + .../azure/mgmt/agricultureplatform/_patch.py | 21 + .../agricultureplatform/_utils/__init__.py | 6 + .../agricultureplatform/_utils/model_base.py | 1337 +++++++++++ .../_utils/serialization.py | 2041 +++++++++++++++++ .../mgmt/agricultureplatform/_version.py | 9 + .../mgmt/agricultureplatform/aio/__init__.py | 29 + .../mgmt/agricultureplatform/aio/_client.py | 141 ++ .../agricultureplatform/aio/_configuration.py | 80 + .../mgmt/agricultureplatform/aio/_patch.py | 21 + .../aio/operations/__init__.py | 27 + .../aio/operations/_operations.py | 1102 +++++++++ .../aio/operations/_patch.py | 21 + .../agricultureplatform/models/__init__.py | 92 + .../mgmt/agricultureplatform/models/_enums.py | 103 + .../agricultureplatform/models/_models.py | 1037 +++++++++ .../mgmt/agricultureplatform/models/_patch.py | 21 + .../operations/__init__.py | 27 + .../operations/_operations.py | 1303 +++++++++++ .../agricultureplatform/operations/_patch.py | 21 + .../azure/mgmt/agricultureplatform/py.typed | 1 + .../dev_requirements.txt | 5 + ...ervice_create_or_update_maximum_set_gen.py | 67 + .../agri_service_delete_maximum_set_gen.py | 41 + .../agri_service_get_maximum_set_gen.py | 42 + ...ist_available_solutions_maximum_set_gen.py | 42 + ..._list_by_resource_group_maximum_set_gen.py | 42 + ...ce_list_by_subscription_maximum_set_gen.py | 40 + .../agri_service_update_maximum_set_gen.py | 59 + .../operations_list_maximum_set_gen.py | 40 + .../generated_tests/conftest.py | 43 + ...e_platform_mgmt_agri_service_operations.py | 198 ++ ...form_mgmt_agri_service_operations_async.py | 205 ++ ...st_agriculture_platform_mgmt_operations.py | 27 + ...iculture_platform_mgmt_operations_async.py | 28 + .../pyproject.toml | 86 + .../tsp-location.yaml | 4 + sdk/agricultureplatform/ci.yml | 34 + 48 files changed, 8850 insertions(+) create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/CHANGELOG.md create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/LICENSE create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/MANIFEST.in create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/README.md create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/_metadata.json create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/apiview-properties.json create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_client.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_configuration.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_patch.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/model_base.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/serialization.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_version.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_client.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_configuration.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_patch.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_operations.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_patch.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_enums.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_models.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_patch.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/__init__.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_operations.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_patch.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/py.typed create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/dev_requirements.txt create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_create_or_update_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_delete_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_get_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_available_solutions_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_resource_group_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_subscription_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_update_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/operations_list_maximum_set_gen.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/conftest.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations_async.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations_async.py create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/pyproject.toml create mode 100644 sdk/agricultureplatform/azure-mgmt-agricultureplatform/tsp-location.yaml create mode 100644 sdk/agricultureplatform/ci.yml diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/CHANGELOG.md b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/CHANGELOG.md new file mode 100644 index 000000000000..0654b5548459 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-05) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/LICENSE b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/MANIFEST.in b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/MANIFEST.in new file mode 100644 index 000000000000..6feec3d9ad9c --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/MANIFEST.in @@ -0,0 +1,7 @@ +include *.md +include LICENSE +include azure/mgmt/agricultureplatform/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/README.md b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/README.md new file mode 100644 index 000000000000..c6d6f5aa4e27 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Agricultureplatform Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-agricultureplatform +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = AgriculturePlatformMgmtClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Agricultureplatform Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/_metadata.json b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/_metadata.json new file mode 100644 index 000000000000..f2edf9ac7066 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/_metadata.json @@ -0,0 +1,7 @@ +{ + "apiVersion": "2024-06-01-preview", + "commit": "6a9ac1728fd1b59dcf80b8f7e27b1d5f8ccdfb8e", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/agricultureplatform/AgriculturePlatform.Management", + "emitterVersion": "0.60.0" +} \ No newline at end of file diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/apiview-properties.json b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/apiview-properties.json new file mode 100644 index 000000000000..ae10f6a1a8df --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/apiview-properties.json @@ -0,0 +1,53 @@ +{ + "CrossLanguagePackageId": "Microsoft.AgriculturePlatform", + "CrossLanguageDefinitionId": { + "azure.mgmt.agricultureplatform.models.AgriServiceConfig": "Microsoft.AgriculturePlatform.AgriServiceConfig", + "azure.mgmt.agricultureplatform.models.Resource": "Azure.ResourceManager.CommonTypes.Resource", + "azure.mgmt.agricultureplatform.models.TrackedResource": "Azure.ResourceManager.CommonTypes.TrackedResource", + "azure.mgmt.agricultureplatform.models.AgriServiceResource": "Microsoft.AgriculturePlatform.AgriServiceResource", + "azure.mgmt.agricultureplatform.models.AgriServiceResourceProperties": "Microsoft.AgriculturePlatform.AgriServiceResourceProperties", + "azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdate": "Azure.ResourceManager.Foundations.ResourceUpdateModel", + "azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdateProperties": "Azure.ResourceManager.Foundations.ResourceUpdateModelProperties", + "azure.mgmt.agricultureplatform.models.AvailableAgriSolutionListResult": "Microsoft.AgriculturePlatform.AvailableAgriSolutionListResult", + "azure.mgmt.agricultureplatform.models.DataConnectorCredentialMap": "Microsoft.AgriculturePlatform.DataConnectorCredentialMap", + "azure.mgmt.agricultureplatform.models.DataConnectorCredentials": "Microsoft.AgriculturePlatform.DataConnectorCredentials", + "azure.mgmt.agricultureplatform.models.DataManagerForAgricultureSolution": "Microsoft.AgriculturePlatform.DataManagerForAgricultureSolution", + "azure.mgmt.agricultureplatform.models.ErrorAdditionalInfo": "Azure.ResourceManager.CommonTypes.ErrorAdditionalInfo", + "azure.mgmt.agricultureplatform.models.ErrorDetail": "Azure.ResourceManager.CommonTypes.ErrorDetail", + "azure.mgmt.agricultureplatform.models.ErrorResponse": "Azure.ResourceManager.CommonTypes.ErrorResponse", + "azure.mgmt.agricultureplatform.models.InstalledSolutionMap": "Microsoft.AgriculturePlatform.InstalledSolutionMap", + "azure.mgmt.agricultureplatform.models.ManagedOnBehalfOfConfiguration": "Microsoft.AgriculturePlatform.ManagedOnBehalfOfConfiguration", + "azure.mgmt.agricultureplatform.models.ManagedServiceIdentity": "Azure.ResourceManager.CommonTypes.ManagedServiceIdentity", + "azure.mgmt.agricultureplatform.models.MarketPlaceOfferDetails": "Microsoft.AgriculturePlatform.MarketPlaceOfferDetails", + "azure.mgmt.agricultureplatform.models.MoboBrokerResource": "Microsoft.AgriculturePlatform.MoboBrokerResource", + "azure.mgmt.agricultureplatform.models.Operation": "Azure.ResourceManager.CommonTypes.Operation", + "azure.mgmt.agricultureplatform.models.OperationDisplay": "Azure.ResourceManager.CommonTypes.OperationDisplay", + "azure.mgmt.agricultureplatform.models.Sku": "Azure.ResourceManager.CommonTypes.Sku", + "azure.mgmt.agricultureplatform.models.Solution": "Microsoft.AgriculturePlatform.Solution", + "azure.mgmt.agricultureplatform.models.SystemData": "Azure.ResourceManager.CommonTypes.SystemData", + "azure.mgmt.agricultureplatform.models.UserAssignedIdentity": "Azure.ResourceManager.CommonTypes.UserAssignedIdentity", + "azure.mgmt.agricultureplatform.models.Origin": "Azure.ResourceManager.CommonTypes.Origin", + "azure.mgmt.agricultureplatform.models.ActionType": "Azure.ResourceManager.CommonTypes.ActionType", + "azure.mgmt.agricultureplatform.models.CreatedByType": "Azure.ResourceManager.CommonTypes.createdByType", + "azure.mgmt.agricultureplatform.models.ProvisioningState": "Microsoft.AgriculturePlatform.ProvisioningState", + "azure.mgmt.agricultureplatform.models.AuthCredentialsKind": "Microsoft.AgriculturePlatform.AuthCredentialsKind", + "azure.mgmt.agricultureplatform.models.ManagedServiceIdentityType": "Azure.ResourceManager.CommonTypes.ManagedServiceIdentityType", + "azure.mgmt.agricultureplatform.models.SkuTier": "Azure.ResourceManager.CommonTypes.SkuTier", + "azure.mgmt.agricultureplatform.operations.Operations.list": "Azure.ResourceManager.Operations.list", + "azure.mgmt.agricultureplatform.aio.operations.Operations.list": "Azure.ResourceManager.Operations.list", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.get": "Microsoft.AgriculturePlatform.AgriService.get", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.get": "Microsoft.AgriculturePlatform.AgriService.get", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.begin_create_or_update": "Microsoft.AgriculturePlatform.AgriService.createOrUpdate", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.begin_create_or_update": "Microsoft.AgriculturePlatform.AgriService.createOrUpdate", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.begin_update": "Microsoft.AgriculturePlatform.AgriService.update", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.begin_update": "Microsoft.AgriculturePlatform.AgriService.update", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.begin_delete": "Microsoft.AgriculturePlatform.AgriService.delete", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.begin_delete": "Microsoft.AgriculturePlatform.AgriService.delete", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.list_by_resource_group": "Microsoft.AgriculturePlatform.AgriService.listByResourceGroup", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.list_by_resource_group": "Microsoft.AgriculturePlatform.AgriService.listByResourceGroup", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.list_by_subscription": "Microsoft.AgriculturePlatform.AgriService.listBySubscription", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.list_by_subscription": "Microsoft.AgriculturePlatform.AgriService.listBySubscription", + "azure.mgmt.agricultureplatform.operations.AgriServiceOperations.list_available_solutions": "Microsoft.AgriculturePlatform.AgriService.listAvailableSolutions", + "azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations.list_available_solutions": "Microsoft.AgriculturePlatform.AgriService.listAvailableSolutions" + } +} \ No newline at end of file diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/__init__.py new file mode 100644 index 000000000000..db0350cb8645 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import AgriculturePlatformMgmtClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AgriculturePlatformMgmtClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_client.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_client.py new file mode 100644 index 000000000000..486945bc760d --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_client.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from ._configuration import AgriculturePlatformMgmtClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import AgriServiceOperations, Operations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class AgriculturePlatformMgmtClient: + """AgriculturePlatformMgmtClient. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.agricultureplatform.operations.Operations + :ivar agri_service: AgriServiceOperations operations + :vartype agri_service: azure.mgmt.agricultureplatform.operations.AgriServiceOperations + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service host. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Default value is + "2024-06-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = AgriculturePlatformMgmtClientConfiguration( + credential=credential, + subscription_id=subscription_id, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, _endpoint), policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.agri_service = AgriServiceOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_configuration.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_configuration.py new file mode 100644 index 000000000000..8dda416169ce --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_configuration.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class AgriculturePlatformMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for AgriculturePlatformMgmtClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Default value is + "2024-06-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2024-06-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.base_url = base_url + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-agricultureplatform/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_patch.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/model_base.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/model_base.py new file mode 100644 index 000000000000..c402af2afc63 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/model_base.py @@ -0,0 +1,1337 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/serialization.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/serialization.py new file mode 100644 index 000000000000..81ec1de5922b --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_version.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_version.py new file mode 100644 index 000000000000..be71c81bd282 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/__init__.py new file mode 100644 index 000000000000..741004e6b887 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import AgriculturePlatformMgmtClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AgriculturePlatformMgmtClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_client.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_client.py new file mode 100644 index 000000000000..ddef3df5696b --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_client.py @@ -0,0 +1,141 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .._utils.serialization import Deserializer, Serializer +from ._configuration import AgriculturePlatformMgmtClientConfiguration +from .operations import AgriServiceOperations, Operations + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class AgriculturePlatformMgmtClient: + """AgriculturePlatformMgmtClient. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.agricultureplatform.aio.operations.Operations + :ivar agri_service: AgriServiceOperations operations + :vartype agri_service: azure.mgmt.agricultureplatform.aio.operations.AgriServiceOperations + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service host. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Default value is + "2024-06-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = AgriculturePlatformMgmtClientConfiguration( + credential=credential, + subscription_id=subscription_id, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, _endpoint), policies=_policies, **kwargs + ) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.agri_service = AgriServiceOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_configuration.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_configuration.py new file mode 100644 index 000000000000..87870f105173 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_configuration.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class AgriculturePlatformMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for AgriculturePlatformMgmtClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Default value is + "2024-06-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2024-06-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.base_url = base_url + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-agricultureplatform/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_patch.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/__init__.py new file mode 100644 index 000000000000..5bc65312327a --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import AgriServiceOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "AgriServiceOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_operations.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_operations.py new file mode 100644 index 000000000000..61ed1ed0b029 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_operations.py @@ -0,0 +1,1102 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_agri_service_create_or_update_request, + build_agri_service_delete_request, + build_agri_service_get_request, + build_agri_service_list_available_solutions_request, + build_agri_service_list_by_resource_group_request, + build_agri_service_list_by_subscription_request, + build_agri_service_update_request, + build_operations_list_request, +) +from .._configuration import AgriculturePlatformMgmtClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.agricultureplatform.aio.AgriculturePlatformMgmtClient`'s + :attr:`operations` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AgriculturePlatformMgmtClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of Operation + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.agricultureplatform.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Operation], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class AgriServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.agricultureplatform.aio.AgriculturePlatformMgmtClient`'s + :attr:`agri_service` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AgriculturePlatformMgmtClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> _models.AgriServiceResource: + """Get a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :return: AgriServiceResource. The AgriServiceResource is compatible with MutableMapping + :rtype: ~azure.mgmt.agricultureplatform.models.AgriServiceResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AgriServiceResource] = kwargs.pop("cls", None) + + _request = build_agri_service_get_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AgriServiceResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: Union[_models.AgriServiceResource, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agri_service_create_or_update_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: _models.AgriServiceResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.agricultureplatform.models.AgriServiceResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: Union[_models.AgriServiceResource, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Is one of the following types: + AgriServiceResource, JSON, IO[bytes] Required. + :type resource: ~azure.mgmt.agricultureplatform.models.AgriServiceResource or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AgriServiceResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + resource=resource, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.AgriServiceResource, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.AgriServiceResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.AgriServiceResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: Union[_models.AgriServiceResourceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _content = json.dumps(properties, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agri_service_update_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: _models.AgriServiceResourceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: Union[_models.AgriServiceResourceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Is one of the following types: + AgriServiceResourceUpdate, JSON, IO[bytes] Required. + :type properties: ~azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdate or JSON or + IO[bytes] + :return: An instance of AsyncLROPoller that returns AgriServiceResource. The + AgriServiceResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AgriServiceResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + properties=properties, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.AgriServiceResource, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.AgriServiceResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.AgriServiceResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_agri_service_delete_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Delete a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.AgriServiceResource"]: + """List AgriServiceResource resources by resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of AgriServiceResource + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.AgriServiceResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_agri_service_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.AgriServiceResource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.AgriServiceResource"]: + """List AgriServiceResource resources by subscription ID. + + :return: An iterator like instance of AgriServiceResource + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.AgriServiceResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_agri_service_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.AgriServiceResource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def list_available_solutions( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> _models.AvailableAgriSolutionListResult: + """Returns the list of available agri solutions. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :return: AvailableAgriSolutionListResult. The AvailableAgriSolutionListResult is compatible + with MutableMapping + :rtype: ~azure.mgmt.agricultureplatform.models.AvailableAgriSolutionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AvailableAgriSolutionListResult] = kwargs.pop("cls", None) + + _request = build_agri_service_list_available_solutions_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AvailableAgriSolutionListResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_patch.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/__init__.py new file mode 100644 index 000000000000..1081ef3d2c14 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/__init__.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AgriServiceConfig, + AgriServiceResource, + AgriServiceResourceProperties, + AgriServiceResourceUpdate, + AgriServiceResourceUpdateProperties, + AvailableAgriSolutionListResult, + DataConnectorCredentialMap, + DataConnectorCredentials, + DataManagerForAgricultureSolution, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + InstalledSolutionMap, + ManagedOnBehalfOfConfiguration, + ManagedServiceIdentity, + MarketPlaceOfferDetails, + MoboBrokerResource, + Operation, + OperationDisplay, + Resource, + Sku, + Solution, + SystemData, + TrackedResource, + UserAssignedIdentity, +) + +from ._enums import ( # type: ignore + ActionType, + AuthCredentialsKind, + CreatedByType, + ManagedServiceIdentityType, + Origin, + ProvisioningState, + SkuTier, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AgriServiceConfig", + "AgriServiceResource", + "AgriServiceResourceProperties", + "AgriServiceResourceUpdate", + "AgriServiceResourceUpdateProperties", + "AvailableAgriSolutionListResult", + "DataConnectorCredentialMap", + "DataConnectorCredentials", + "DataManagerForAgricultureSolution", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "InstalledSolutionMap", + "ManagedOnBehalfOfConfiguration", + "ManagedServiceIdentity", + "MarketPlaceOfferDetails", + "MoboBrokerResource", + "Operation", + "OperationDisplay", + "Resource", + "Sku", + "Solution", + "SystemData", + "TrackedResource", + "UserAssignedIdentity", + "ActionType", + "AuthCredentialsKind", + "CreatedByType", + "ManagedServiceIdentityType", + "Origin", + "ProvisioningState", + "SkuTier", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_enums.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_enums.py new file mode 100644 index 000000000000..06b8c280a1a7 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_enums.py @@ -0,0 +1,103 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal + only APIs. + """ + + INTERNAL = "Internal" + """Actions are for internal-only APIs.""" + + +class AuthCredentialsKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Types of different kind of Data connector auth credentials supported.""" + + O_AUTH_CLIENT_CREDENTIALS = "OAuthClientCredentials" + """OAuth Client Credential type.""" + API_KEY_AUTH_CREDENTIALS = "ApiKeyAuthCredentials" + """API Key Auth Credential type.""" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of entity that created the resource.""" + + USER = "User" + """The entity was created by a user.""" + APPLICATION = "Application" + """The entity was created by an application.""" + MANAGED_IDENTITY = "ManagedIdentity" + """The entity was created by a managed identity.""" + KEY = "Key" + """The entity was created by a key.""" + + +class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of managed service identity (where both SystemAssigned and UserAssigned types are + allowed). + """ + + NONE = "None" + """No managed identity.""" + SYSTEM_ASSIGNED = "SystemAssigned" + """System assigned managed identity.""" + USER_ASSIGNED = "UserAssigned" + """User assigned managed identity.""" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" + """System and user assigned managed identity.""" + + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". + """ + + USER = "user" + """Indicates the operation is initiated by a user.""" + SYSTEM = "system" + """Indicates the operation is initiated by a system.""" + USER_SYSTEM = "user,system" + """Indicates the operation is initiated by a user or system.""" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the current operation.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" + PROVISIONING = "Provisioning" + """The resource is being provisioned.""" + UPDATING = "Updating" + """The resource is updating.""" + DELETING = "Deleting" + """The resource is being deleted.""" + ACCEPTED = "Accepted" + """The resource create request has been accepted.""" + + +class SkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This field is required to be implemented by the Resource Provider if the service has more than + one tier, but is not required on a PUT. + """ + + FREE = "Free" + """The Free service tier.""" + BASIC = "Basic" + """The Basic service tier.""" + STANDARD = "Standard" + """The Standard service tier.""" + PREMIUM = "Premium" + """The Premium service tier.""" diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_models.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_models.py new file mode 100644 index 000000000000..4067cb103022 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_models.py @@ -0,0 +1,1037 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class AgriServiceConfig(_Model): + """Config of the AgriService resource instance. + + :ivar instance_uri: Instance URI of the AgriService instance. + :vartype instance_uri: str + :ivar version: Version of AgriService instance. + :vartype version: str + :ivar app_service_resource_id: App service resource Id. + :vartype app_service_resource_id: str + :ivar cosmos_db_resource_id: Cosmos Db resource Id. + :vartype cosmos_db_resource_id: str + :ivar storage_account_resource_id: Storage account resource Id. + :vartype storage_account_resource_id: str + :ivar key_vault_resource_id: Key vault resource Id. + :vartype key_vault_resource_id: str + :ivar redis_cache_resource_id: Redis cache resource Id. + :vartype redis_cache_resource_id: str + """ + + instance_uri: Optional[str] = rest_field(name="instanceUri", visibility=["read"]) + """Instance URI of the AgriService instance.""" + version: Optional[str] = rest_field(visibility=["read"]) + """Version of AgriService instance.""" + app_service_resource_id: Optional[str] = rest_field(name="appServiceResourceId", visibility=["read"]) + """App service resource Id.""" + cosmos_db_resource_id: Optional[str] = rest_field(name="cosmosDbResourceId", visibility=["read"]) + """Cosmos Db resource Id.""" + storage_account_resource_id: Optional[str] = rest_field(name="storageAccountResourceId", visibility=["read"]) + """Storage account resource Id.""" + key_vault_resource_id: Optional[str] = rest_field(name="keyVaultResourceId", visibility=["read"]) + """Key vault resource Id.""" + redis_cache_resource_id: Optional[str] = rest_field(name="redisCacheResourceId", visibility=["read"]) + """Redis cache resource Id.""" + + +class Resource(_Model): + """Resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.agricultureplatform.models.SystemData + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the resource.""" + type: Optional[str] = rest_field(visibility=["read"]) + """The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or + \"Microsoft.Storage/storageAccounts\".""" + system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) + """Azure Resource Manager metadata containing createdBy and modifiedBy information.""" + + +class TrackedResource(Resource): + """Tracked Resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.agricultureplatform.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + """ + + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource tags.""" + location: str = rest_field(visibility=["read", "create"]) + """The geo-location where the resource lives. Required.""" + + @overload + def __init__( + self, + *, + location: str, + tags: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AgriServiceResource(TrackedResource): + """Schema of the AgriService resource from Microsoft.AgriculturePlatform resource provider. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.agricultureplatform.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.agricultureplatform.models.AgriServiceResourceProperties + :ivar identity: The managed service identities assigned to this resource. + :vartype identity: ~azure.mgmt.agricultureplatform.models.ManagedServiceIdentity + :ivar sku: The SKU (Stock Keeping Unit) assigned to this resource. + :vartype sku: ~azure.mgmt.agricultureplatform.models.Sku + """ + + properties: Optional["_models.AgriServiceResourceProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The resource-specific properties for this resource.""" + identity: Optional["_models.ManagedServiceIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The managed service identities assigned to this resource.""" + sku: Optional["_models.Sku"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU (Stock Keeping Unit) assigned to this resource.""" + + @overload + def __init__( + self, + *, + location: str, + tags: Optional[dict[str, str]] = None, + properties: Optional["_models.AgriServiceResourceProperties"] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + sku: Optional["_models.Sku"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AgriServiceResourceProperties(_Model): + """Details of the Agriculture AgriDataManager. + + :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", + "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". + :vartype provisioning_state: str or ~azure.mgmt.agricultureplatform.models.ProvisioningState + :ivar config: Config of the AgriService instance. + :vartype config: ~azure.mgmt.agricultureplatform.models.AgriServiceConfig + :ivar managed_on_behalf_of_configuration: Managed On Behalf Of Configuration. + :vartype managed_on_behalf_of_configuration: + ~azure.mgmt.agricultureplatform.models.ManagedOnBehalfOfConfiguration + :ivar data_connector_credentials: Data connector credentials of AgriService instance. + :vartype data_connector_credentials: + list[~azure.mgmt.agricultureplatform.models.DataConnectorCredentialMap] + :ivar installed_solutions: AgriService installed solutions. + :vartype installed_solutions: list[~azure.mgmt.agricultureplatform.models.InstalledSolutionMap] + """ + + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """The status of the last operation. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", + \"Provisioning\", \"Updating\", \"Deleting\", and \"Accepted\".""" + config: Optional["_models.AgriServiceConfig"] = rest_field(visibility=["read", "create", "update"]) + """Config of the AgriService instance.""" + managed_on_behalf_of_configuration: Optional["_models.ManagedOnBehalfOfConfiguration"] = rest_field( + name="managedOnBehalfOfConfiguration", visibility=["read"] + ) + """Managed On Behalf Of Configuration.""" + data_connector_credentials: Optional[list["_models.DataConnectorCredentialMap"]] = rest_field( + name="dataConnectorCredentials", visibility=["read", "create", "update"] + ) + """Data connector credentials of AgriService instance.""" + installed_solutions: Optional[list["_models.InstalledSolutionMap"]] = rest_field( + name="installedSolutions", visibility=["read", "create", "update"] + ) + """AgriService installed solutions.""" + + @overload + def __init__( + self, + *, + config: Optional["_models.AgriServiceConfig"] = None, + data_connector_credentials: Optional[list["_models.DataConnectorCredentialMap"]] = None, + installed_solutions: Optional[list["_models.InstalledSolutionMap"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AgriServiceResourceUpdate(_Model): + """The type used for update operations of the AgriServiceResource. + + :ivar identity: The managed service identities assigned to this resource. + :vartype identity: ~azure.mgmt.agricultureplatform.models.ManagedServiceIdentity + :ivar sku: The SKU (Stock Keeping Unit) assigned to this resource. + :vartype sku: ~azure.mgmt.agricultureplatform.models.Sku + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdateProperties + """ + + identity: Optional["_models.ManagedServiceIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The managed service identities assigned to this resource.""" + sku: Optional["_models.Sku"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU (Stock Keeping Unit) assigned to this resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource tags.""" + properties: Optional["_models.AgriServiceResourceUpdateProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The resource-specific properties for this resource.""" + + @overload + def __init__( + self, + *, + identity: Optional["_models.ManagedServiceIdentity"] = None, + sku: Optional["_models.Sku"] = None, + tags: Optional[dict[str, str]] = None, + properties: Optional["_models.AgriServiceResourceUpdateProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AgriServiceResourceUpdateProperties(_Model): + """The updatable properties of the AgriServiceResource. + + :ivar config: Config of the AgriService instance. + :vartype config: ~azure.mgmt.agricultureplatform.models.AgriServiceConfig + :ivar data_connector_credentials: Data connector credentials of AgriService instance. + :vartype data_connector_credentials: + list[~azure.mgmt.agricultureplatform.models.DataConnectorCredentialMap] + :ivar installed_solutions: AgriService installed solutions. + :vartype installed_solutions: list[~azure.mgmt.agricultureplatform.models.InstalledSolutionMap] + """ + + config: Optional["_models.AgriServiceConfig"] = rest_field(visibility=["read", "create", "update"]) + """Config of the AgriService instance.""" + data_connector_credentials: Optional[list["_models.DataConnectorCredentialMap"]] = rest_field( + name="dataConnectorCredentials", visibility=["read", "create", "update"] + ) + """Data connector credentials of AgriService instance.""" + installed_solutions: Optional[list["_models.InstalledSolutionMap"]] = rest_field( + name="installedSolutions", visibility=["read", "create", "update"] + ) + """AgriService installed solutions.""" + + @overload + def __init__( + self, + *, + config: Optional["_models.AgriServiceConfig"] = None, + data_connector_credentials: Optional[list["_models.DataConnectorCredentialMap"]] = None, + installed_solutions: Optional[list["_models.InstalledSolutionMap"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AvailableAgriSolutionListResult(_Model): + """The list of available agri solutions. + + :ivar solutions: Agri solutions list. Required. + :vartype solutions: + list[~azure.mgmt.agricultureplatform.models.DataManagerForAgricultureSolution] + """ + + solutions: list["_models.DataManagerForAgricultureSolution"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Agri solutions list. Required.""" + + @overload + def __init__( + self, + *, + solutions: list["_models.DataManagerForAgricultureSolution"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataConnectorCredentialMap(_Model): + """Mapping of data connector credentials. + + :ivar key: The key representing the credential. Required. + :vartype key: str + :ivar value: The data connector credential value. Required. + :vartype value: ~azure.mgmt.agricultureplatform.models.DataConnectorCredentials + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key representing the credential. Required.""" + value: "_models.DataConnectorCredentials" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The data connector credential value. Required.""" + + @overload + def __init__( + self, + *, + key: str, + value: "_models.DataConnectorCredentials", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataConnectorCredentials(_Model): + """The properties related to an AgriService data connector. + + :ivar kind: Type of credential. Known values are: "OAuthClientCredentials" and + "ApiKeyAuthCredentials". + :vartype kind: str or ~azure.mgmt.agricultureplatform.models.AuthCredentialsKind + :ivar client_id: Client Id associated with the provider, if type of credentials is + OAuthClientCredentials. + :vartype client_id: str + :ivar key_vault_uri: Uri of the key vault. + :vartype key_vault_uri: str + :ivar key_name: Name of the key vault key. + :vartype key_name: str + :ivar key_version: Version of the key vault key. + :vartype key_version: str + """ + + kind: Optional[Union[str, "_models.AuthCredentialsKind"]] = rest_field(visibility=["read", "create", "update"]) + """Type of credential. Known values are: \"OAuthClientCredentials\" and \"ApiKeyAuthCredentials\".""" + client_id: Optional[str] = rest_field(name="clientId", visibility=["read", "create", "update"]) + """Client Id associated with the provider, if type of credentials is OAuthClientCredentials.""" + key_vault_uri: Optional[str] = rest_field(name="keyVaultUri", visibility=["read", "create", "update"]) + """Uri of the key vault.""" + key_name: Optional[str] = rest_field(name="keyName", visibility=["read", "create", "update"]) + """Name of the key vault key.""" + key_version: Optional[str] = rest_field(name="keyVersion", visibility=["read", "create", "update"]) + """Version of the key vault key.""" + + @overload + def __init__( + self, + *, + kind: Optional[Union[str, "_models.AuthCredentialsKind"]] = None, + client_id: Optional[str] = None, + key_vault_uri: Optional[str] = None, + key_name: Optional[str] = None, + key_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataManagerForAgricultureSolution(_Model): + """Data Manager for Agriculture solution. + + :ivar partner_id: Partner Id. Required. + :vartype partner_id: str + :ivar solution_id: Solution Id. Required. + :vartype solution_id: str + :ivar partner_tenant_id: Partner tenant Id. Required. + :vartype partner_tenant_id: str + :ivar data_access_scopes: Data access scopes. Required. + :vartype data_access_scopes: list[str] + :ivar market_place_offer_details: Marketplace offer details. Required. + :vartype market_place_offer_details: + ~azure.mgmt.agricultureplatform.models.MarketPlaceOfferDetails + :ivar saas_application_id: Saas application Id. Required. + :vartype saas_application_id: str + :ivar access_azure_data_manager_for_agriculture_application_id: Entra application Id used to + access azure data manager for agriculture instance. Required. + :vartype access_azure_data_manager_for_agriculture_application_id: str + :ivar access_azure_data_manager_for_agriculture_application_name: Entra application name used + to access azure data manager for agriculture instance. Required. + :vartype access_azure_data_manager_for_agriculture_application_name: str + :ivar is_validate_input: Whether solution inference will validate input. Required. + :vartype is_validate_input: bool + """ + + partner_id: str = rest_field(name="partnerId", visibility=["read", "create", "update", "delete", "query"]) + """Partner Id. Required.""" + solution_id: str = rest_field(name="solutionId", visibility=["read", "create", "update", "delete", "query"]) + """Solution Id. Required.""" + partner_tenant_id: str = rest_field( + name="partnerTenantId", visibility=["read", "create", "update", "delete", "query"] + ) + """Partner tenant Id. Required.""" + data_access_scopes: list[str] = rest_field( + name="dataAccessScopes", visibility=["read", "create", "update", "delete", "query"] + ) + """Data access scopes. Required.""" + market_place_offer_details: "_models.MarketPlaceOfferDetails" = rest_field( + name="marketPlaceOfferDetails", visibility=["read", "create", "update", "delete", "query"] + ) + """Marketplace offer details. Required.""" + saas_application_id: str = rest_field( + name="saasApplicationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Saas application Id. Required.""" + access_azure_data_manager_for_agriculture_application_id: str = rest_field( + name="accessAzureDataManagerForAgricultureApplicationId", + visibility=["read", "create", "update", "delete", "query"], + ) + """Entra application Id used to access azure data manager for agriculture instance. Required.""" + access_azure_data_manager_for_agriculture_application_name: str = rest_field( + name="accessAzureDataManagerForAgricultureApplicationName", + visibility=["read", "create", "update", "delete", "query"], + ) + """Entra application name used to access azure data manager for agriculture instance. Required.""" + is_validate_input: bool = rest_field( + name="isValidateInput", visibility=["read", "create", "update", "delete", "query"] + ) + """Whether solution inference will validate input. Required.""" + + @overload + def __init__( + self, + *, + partner_id: str, + solution_id: str, + partner_tenant_id: str, + data_access_scopes: list[str], + market_place_offer_details: "_models.MarketPlaceOfferDetails", + saas_application_id: str, + access_azure_data_manager_for_agriculture_application_id: str, + access_azure_data_manager_for_agriculture_application_name: str, + is_validate_input: bool, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + type: Optional[str] = rest_field(visibility=["read"]) + """The additional info type.""" + info: Optional[Any] = rest_field(visibility=["read"]) + """The additional info.""" + + +class ErrorDetail(_Model): + """The error detail. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.agricultureplatform.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.agricultureplatform.models.ErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The error target.""" + details: Optional[list["_models.ErrorDetail"]] = rest_field(visibility=["read"]) + """The error details.""" + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read"] + ) + """The error additional info.""" + + +class ErrorResponse(_Model): + """Error response. + + :ivar error: The error object. + :vartype error: ~azure.mgmt.agricultureplatform.models.ErrorDetail + """ + + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error object.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InstalledSolutionMap(_Model): + """Mapping of installed solutions. + + :ivar key: The key representing the installed solution. Required. + :vartype key: str + :ivar value: The installed solution value. Required. + :vartype value: ~azure.mgmt.agricultureplatform.models.Solution + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key representing the installed solution. Required.""" + value: "_models.Solution" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The installed solution value. Required.""" + + @overload + def __init__( + self, + *, + key: str, + value: "_models.Solution", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ManagedOnBehalfOfConfiguration(_Model): + """Configuration of the managed on behalf of resource. + + :ivar mobo_broker_resources: Associated MoboBrokerResources. Required. + :vartype mobo_broker_resources: list[~azure.mgmt.agricultureplatform.models.MoboBrokerResource] + """ + + mobo_broker_resources: list["_models.MoboBrokerResource"] = rest_field( + name="moboBrokerResources", visibility=["read"] + ) + """Associated MoboBrokerResources. Required.""" + + +class ManagedServiceIdentity(_Model): + """Managed service identity (system assigned and/or user assigned identities). + + :ivar principal_id: The service principal ID of the system assigned identity. This property + will only be provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the system assigned identity. This property will only be + provided for a system assigned identity. + :vartype tenant_id: str + :ivar type: The type of managed identity assigned to this resource. Required. Known values are: + "None", "SystemAssigned", "UserAssigned", and "SystemAssigned,UserAssigned". + :vartype type: str or ~azure.mgmt.agricultureplatform.models.ManagedServiceIdentityType + :ivar user_assigned_identities: The identities assigned to this resource by the user. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.agricultureplatform.models.UserAssignedIdentity] + """ + + principal_id: Optional[str] = rest_field(name="principalId", visibility=["read"]) + """The service principal ID of the system assigned identity. This property will only be provided + for a system assigned identity.""" + tenant_id: Optional[str] = rest_field(name="tenantId", visibility=["read"]) + """The tenant ID of the system assigned identity. This property will only be provided for a system + assigned identity.""" + type: Union[str, "_models.ManagedServiceIdentityType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of managed identity assigned to this resource. Required. Known values are: \"None\", + \"SystemAssigned\", \"UserAssigned\", and \"SystemAssigned,UserAssigned\".""" + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentity"]] = rest_field( + name="userAssignedIdentities", visibility=["read", "create", "update", "delete", "query"] + ) + """The identities assigned to this resource by the user.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.ManagedServiceIdentityType"], + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentity"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MarketPlaceOfferDetails(_Model): + """Marketplace offer details of Agri solution. + + :ivar saas_offer_id: Saas offer Id. Required. + :vartype saas_offer_id: str + :ivar publisher_id: Publisher Id. Required. + :vartype publisher_id: str + """ + + saas_offer_id: str = rest_field(name="saasOfferId", visibility=["read", "create", "update", "delete", "query"]) + """Saas offer Id. Required.""" + publisher_id: str = rest_field(name="publisherId", visibility=["read", "create", "update", "delete", "query"]) + """Publisher Id. Required.""" + + @overload + def __init__( + self, + *, + saas_offer_id: str, + publisher_id: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MoboBrokerResource(_Model): + """MoboBroker resource. + + :ivar id: The fully qualified resource ID of the MoboBroker resource. Example: + ``/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}``. + Required. + :vartype id: str + """ + + id: str = rest_field(visibility=["read"]) + """The fully qualified resource ID of the MoboBroker resource. Example: + ``/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}``. + Required.""" + + +class Operation(_Model): + """REST API Operation. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for Azure Resource Manager/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.agricultureplatform.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.agricultureplatform.models.Origin + :ivar action_type: Extensible enum. Indicates the action type. "Internal" refers to actions + that are for internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.agricultureplatform.models.ActionType + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + \"Microsoft.Compute/virtualMachines/write\", + \"Microsoft.Compute/virtualMachines/capture/action\".""" + is_data_action: Optional[bool] = rest_field(name="isDataAction", visibility=["read"]) + """Whether the operation applies to data-plane. This is \"true\" for data-plane operations and + \"false\" for Azure Resource Manager/control-plane operations.""" + display: Optional["_models.OperationDisplay"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Localized display information for this particular operation.""" + origin: Optional[Union[str, "_models.Origin"]] = rest_field(visibility=["read"]) + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is \"user,system\". Known values are: \"user\", \"system\", and + \"user,system\".""" + action_type: Optional[Union[str, "_models.ActionType"]] = rest_field(name="actionType", visibility=["read"]) + """Extensible enum. Indicates the action type. \"Internal\" refers to actions that are for + internal only APIs. \"Internal\"""" + + @overload + def __init__( + self, + *, + display: Optional["_models.OperationDisplay"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OperationDisplay(_Model): + """Localized display information for an operation. + + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". + :vartype resource: str + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". + :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str + """ + + provider: Optional[str] = rest_field(visibility=["read"]) + """The localized friendly form of the resource provider name, e.g. \"Microsoft Monitoring + Insights\" or \"Microsoft Compute\".""" + resource: Optional[str] = rest_field(visibility=["read"]) + """The localized friendly name of the resource type related to this operation. E.g. \"Virtual + Machines\" or \"Job Schedule Collections\".""" + operation: Optional[str] = rest_field(visibility=["read"]) + """The concise, localized friendly name for the operation; suitable for dropdowns. E.g. \"Create + or Update Virtual Machine\", \"Restart Virtual Machine\".""" + description: Optional[str] = rest_field(visibility=["read"]) + """The short, localized friendly description of the operation; suitable for tool tips and detailed + views.""" + + +class Sku(_Model): + """The resource model definition representing SKU. + + :ivar name: The name of the SKU. Ex - P3. It is typically a letter+number code. Required. + :vartype name: str + :ivar tier: This field is required to be implemented by the Resource Provider if the service + has more than one tier, but is not required on a PUT. Known values are: "Free", "Basic", + "Standard", and "Premium". + :vartype tier: str or ~azure.mgmt.agricultureplatform.models.SkuTier + :ivar size: The SKU size. When the name field is the combination of tier and some other value, + this would be the standalone code. + :vartype size: str + :ivar family: If the service has different generations of hardware, for the same SKU, then that + can be captured here. + :vartype family: str + :ivar capacity: If the SKU supports scale out/in then the capacity integer should be included. + If scale out/in is not possible for the resource this may be omitted. + :vartype capacity: int + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the SKU. Ex - P3. It is typically a letter+number code. Required.""" + tier: Optional[Union[str, "_models.SkuTier"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """This field is required to be implemented by the Resource Provider if the service has more than + one tier, but is not required on a PUT. Known values are: \"Free\", \"Basic\", \"Standard\", + and \"Premium\".""" + size: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU size. When the name field is the combination of tier and some other value, this would + be the standalone code.""" + family: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """If the service has different generations of hardware, for the same SKU, then that can be + captured here.""" + capacity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """If the SKU supports scale out/in then the capacity integer should be included. If scale out/in + is not possible for the resource this may be omitted.""" + + @overload + def __init__( + self, + *, + name: str, + tier: Optional[Union[str, "_models.SkuTier"]] = None, + size: Optional[str] = None, + family: Optional[str] = None, + capacity: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Solution(_Model): + """Installed data manager for Agriculture solution detail. + + :ivar application_name: Application name of the solution. + :vartype application_name: str + :ivar partner_id: Partner Id. + :vartype partner_id: str + :ivar market_place_publisher_id: Marketplace publisher Id. + :vartype market_place_publisher_id: str + :ivar saas_subscription_id: Saas subscription Id. + :vartype saas_subscription_id: str + :ivar saas_subscription_name: Saas subscription name. + :vartype saas_subscription_name: str + :ivar plan_id: Plan Id. + :vartype plan_id: str + """ + + application_name: Optional[str] = rest_field(name="applicationName", visibility=["read", "create", "update"]) + """Application name of the solution.""" + partner_id: Optional[str] = rest_field(name="partnerId", visibility=["read", "create", "update"]) + """Partner Id.""" + market_place_publisher_id: Optional[str] = rest_field( + name="marketPlacePublisherId", visibility=["read", "create", "update"] + ) + """Marketplace publisher Id.""" + saas_subscription_id: Optional[str] = rest_field(name="saasSubscriptionId", visibility=["read", "create", "update"]) + """Saas subscription Id.""" + saas_subscription_name: Optional[str] = rest_field( + name="saasSubscriptionName", visibility=["read", "create", "update"] + ) + """Saas subscription name.""" + plan_id: Optional[str] = rest_field(name="planId", visibility=["read", "create", "update"]) + """Plan Id.""" + + @overload + def __init__( + self, + *, + application_name: Optional[str] = None, + partner_id: Optional[str] = None, + market_place_publisher_id: Optional[str] = None, + saas_subscription_id: Optional[str] = None, + saas_subscription_name: Optional[str] = None, + plan_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SystemData(_Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.agricultureplatform.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.agricultureplatform.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) + """The identity that created the resource.""" + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that created the resource. Known values are: \"User\", \"Application\", + \"ManagedIdentity\", and \"Key\".""" + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource creation (UTC).""" + last_modified_by: Optional[str] = rest_field( + name="lastModifiedBy", visibility=["read", "create", "update", "delete", "query"] + ) + """The identity that last modified the resource.""" + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="lastModifiedByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that last modified the resource. Known values are: \"User\", + \"Application\", \"ManagedIdentity\", and \"Key\".""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource last modification (UTC).""" + + @overload + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UserAssignedIdentity(_Model): + """User assigned identity properties. + + :ivar principal_id: The principal ID of the assigned identity. + :vartype principal_id: str + :ivar client_id: The client ID of the assigned identity. + :vartype client_id: str + """ + + principal_id: Optional[str] = rest_field(name="principalId", visibility=["read"]) + """The principal ID of the assigned identity.""" + client_id: Optional[str] = rest_field(name="clientId", visibility=["read"]) + """The client ID of the assigned identity.""" diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_patch.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/__init__.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/__init__.py new file mode 100644 index 000000000000..5bc65312327a --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import AgriServiceOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "AgriServiceOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_operations.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_operations.py new file mode 100644 index 000000000000..c5edb1a15e86 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_operations.py @@ -0,0 +1,1303 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._configuration import AgriculturePlatformMgmtClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_operations_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.AgriculturePlatform/operations" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agri_service_get_request( + resource_group_name: str, agri_service_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "agriServiceResourceName": _SERIALIZER.url("agri_service_resource_name", agri_service_resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agri_service_create_or_update_request( # pylint: disable=name-too-long + resource_group_name: str, agri_service_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "agriServiceResourceName": _SERIALIZER.url("agri_service_resource_name", agri_service_resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agri_service_update_request( + resource_group_name: str, agri_service_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "agriServiceResourceName": _SERIALIZER.url("agri_service_resource_name", agri_service_resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agri_service_delete_request( + resource_group_name: str, agri_service_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "agriServiceResourceName": _SERIALIZER.url("agri_service_resource_name", agri_service_resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_agri_service_list_by_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agri_service_list_by_subscription_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.AgriculturePlatform/agriServices" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agri_service_list_available_solutions_request( # pylint: disable=name-too-long + resource_group_name: str, agri_service_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-06-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}/listAvailableSolutions" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "agriServiceResourceName": _SERIALIZER.url("agri_service_resource_name", agri_service_resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.agricultureplatform.AgriculturePlatformMgmtClient`'s + :attr:`operations` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AgriculturePlatformMgmtClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of Operation + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.agricultureplatform.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Operation], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class AgriServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.agricultureplatform.AgriculturePlatformMgmtClient`'s + :attr:`agri_service` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AgriculturePlatformMgmtClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> _models.AgriServiceResource: + """Get a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :return: AgriServiceResource. The AgriServiceResource is compatible with MutableMapping + :rtype: ~azure.mgmt.agricultureplatform.models.AgriServiceResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AgriServiceResource] = kwargs.pop("cls", None) + + _request = build_agri_service_get_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AgriServiceResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: Union[_models.AgriServiceResource, JSON, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agri_service_create_or_update_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: _models.AgriServiceResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.agricultureplatform.models.AgriServiceResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + resource: Union[_models.AgriServiceResource, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Create a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param resource: Resource create parameters. Is one of the following types: + AgriServiceResource, JSON, IO[bytes] Required. + :type resource: ~azure.mgmt.agricultureplatform.models.AgriServiceResource or JSON or IO[bytes] + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AgriServiceResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + resource=resource, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.AgriServiceResource, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.AgriServiceResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.AgriServiceResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: Union[_models.AgriServiceResourceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _content = json.dumps(properties, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agri_service_update_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: _models.AgriServiceResourceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + agri_service_resource_name: str, + properties: Union[_models.AgriServiceResourceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.AgriServiceResource]: + """Update a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :param properties: The resource properties to be updated. Is one of the following types: + AgriServiceResourceUpdate, JSON, IO[bytes] Required. + :type properties: ~azure.mgmt.agricultureplatform.models.AgriServiceResourceUpdate or JSON or + IO[bytes] + :return: An instance of LROPoller that returns AgriServiceResource. The AgriServiceResource is + compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AgriServiceResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + properties=properties, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.AgriServiceResource, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.AgriServiceResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.AgriServiceResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_agri_service_delete_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any) -> LROPoller[None]: + """Delete a AgriServiceResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> ItemPaged["_models.AgriServiceResource"]: + """List AgriServiceResource resources by resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of AgriServiceResource + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.AgriServiceResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_agri_service_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.AgriServiceResource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> ItemPaged["_models.AgriServiceResource"]: + """List AgriServiceResource resources by subscription ID. + + :return: An iterator like instance of AgriServiceResource + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.agricultureplatform.models.AgriServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.AgriServiceResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_agri_service_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.AgriServiceResource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_available_solutions( + self, resource_group_name: str, agri_service_resource_name: str, **kwargs: Any + ) -> _models.AvailableAgriSolutionListResult: + """Returns the list of available agri solutions. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param agri_service_resource_name: The name of the AgriService resource. Required. + :type agri_service_resource_name: str + :return: AvailableAgriSolutionListResult. The AvailableAgriSolutionListResult is compatible + with MutableMapping + :rtype: ~azure.mgmt.agricultureplatform.models.AvailableAgriSolutionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AvailableAgriSolutionListResult] = kwargs.pop("cls", None) + + _request = build_agri_service_list_available_solutions_request( + resource_group_name=resource_group_name, + agri_service_resource_name=agri_service_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AvailableAgriSolutionListResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_patch.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/py.typed b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/azure/mgmt/agricultureplatform/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/dev_requirements.txt b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_create_or_update_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_create_or_update_maximum_set_gen.py new file mode 100644 index 000000000000..6823c383e139 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_create_or_update_maximum_set_gen.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_create_or_update_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.agri_service.begin_create_or_update( + resource_group_name="rgopenapi", + agri_service_resource_name="abc123", + resource={ + "identity": {"type": "None", "userAssignedIdentities": {"key4955": {}}}, + "location": "pkneuknooprpqirnugzwbkiie", + "properties": { + "config": {}, + "dataConnectorCredentials": [ + { + "key": "BackendAADApplicationCredentials", + "value": {"clientId": "dce298a8-1eec-481a-a8f9-a3cd5a8257b2"}, + } + ], + "installedSolutions": [ + {"key": "bayerAgPowered.cwum", "value": {"applicationName": "bayerAgPowered.cwum"}} + ], + "managedOnBehalfOfConfiguration": {}, + }, + "sku": { + "capacity": 20, + "family": "xerdhxyjwrypvxphavgrtjphtohf", + "name": "kfl", + "size": "r", + "tier": "Free", + }, + "tags": {"key137": "oxwansfetzzgdwl"}, + }, + ).result() + print(response) + + +# x-ms-original-file: 2024-06-01-preview/AgriService_CreateOrUpdate_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_delete_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_delete_maximum_set_gen.py new file mode 100644 index 000000000000..d523358903d0 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_delete_maximum_set_gen.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_delete_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.agri_service.begin_delete( + resource_group_name="rgopenapi", + agri_service_resource_name="abc123", + ).result() + + +# x-ms-original-file: 2024-06-01-preview/AgriService_Delete_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_get_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_get_maximum_set_gen.py new file mode 100644 index 000000000000..3baf0d524751 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_get_maximum_set_gen.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_get_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.agri_service.get( + resource_group_name="rgopenapi", + agri_service_resource_name="abc123", + ) + print(response) + + +# x-ms-original-file: 2024-06-01-preview/AgriService_Get_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_available_solutions_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_available_solutions_maximum_set_gen.py new file mode 100644 index 000000000000..b8b328d1674c --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_available_solutions_maximum_set_gen.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_list_available_solutions_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.agri_service.list_available_solutions( + resource_group_name="rgopenapi", + agri_service_resource_name="abc123", + ) + print(response) + + +# x-ms-original-file: 2024-06-01-preview/AgriService_ListAvailableSolutions_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_resource_group_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_resource_group_maximum_set_gen.py new file mode 100644 index 000000000000..0eb34069b710 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_resource_group_maximum_set_gen.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_list_by_resource_group_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.agri_service.list_by_resource_group( + resource_group_name="rgopenapi", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2024-06-01-preview/AgriService_ListByResourceGroup_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_subscription_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_subscription_maximum_set_gen.py new file mode 100644 index 000000000000..cfd3cc56b2de --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_list_by_subscription_maximum_set_gen.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_list_by_subscription_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.agri_service.list_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: 2024-06-01-preview/AgriService_ListBySubscription_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_update_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_update_maximum_set_gen.py new file mode 100644 index 000000000000..1785bed6fbb6 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/agri_service_update_maximum_set_gen.py @@ -0,0 +1,59 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python agri_service_update_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.agri_service.begin_update( + resource_group_name="rgopenapi", + agri_service_resource_name="abc123", + properties={ + "identity": {"type": "None", "userAssignedIdentities": {"key4771": {}}}, + "properties": { + "config": {}, + "dataConnectorCredentials": [ + { + "key": "BackendAADApplicationCredentials", + "value": {"clientId": "dce298a8-1eec-481a-a8f9-a3cd5a8257b2"}, + } + ], + "installedSolutions": [ + {"key": "bayerAgPowered.cwum", "value": {"applicationName": "bayerAgPowered.cwum"}} + ], + }, + "sku": {"capacity": 22, "family": "hxojswlgs", "name": "tbdtdfffkar", "size": "iusaqqj", "tier": "Free"}, + "tags": {"key9006": "kuzlwpujbql"}, + }, + ).result() + print(response) + + +# x-ms-original-file: 2024-06-01-preview/AgriService_Update_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/operations_list_maximum_set_gen.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/operations_list_maximum_set_gen.py new file mode 100644 index 000000000000..f310e7c15c4d --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_samples/operations_list_maximum_set_gen.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-agricultureplatform +# USAGE + python operations_list_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AgriculturePlatformMgmtClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: 2024-06-01-preview/Operations_List_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/conftest.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/conftest.py new file mode 100644 index 000000000000..1034aa854cde --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/conftest.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + agricultureplatformmgmt_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + agricultureplatformmgmt_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + agricultureplatformmgmt_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + agricultureplatformmgmt_client_secret = os.environ.get( + "AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=agricultureplatformmgmt_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=agricultureplatformmgmt_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=agricultureplatformmgmt_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=agricultureplatformmgmt_client_secret, value="00000000-0000-0000-0000-000000000000" + ) + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations.py new file mode 100644 index 000000000000..28b080cf2009 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations.py @@ -0,0 +1,198 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAgriculturePlatformMgmtAgriServiceOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AgriculturePlatformMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_get(self, resource_group): + response = self.client.agri_service.get( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_begin_create_or_update(self, resource_group): + response = self.client.agri_service.begin_create_or_update( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + resource={ + "location": "str", + "id": "str", + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "name": "str", + "properties": { + "config": { + "appServiceResourceId": "str", + "cosmosDbResourceId": "str", + "instanceUri": "str", + "keyVaultResourceId": "str", + "redisCacheResourceId": "str", + "storageAccountResourceId": "str", + "version": "str", + }, + "dataConnectorCredentials": [ + { + "key": "str", + "value": { + "clientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + "kind": "str", + }, + } + ], + "installedSolutions": [ + { + "key": "str", + "value": { + "applicationName": "str", + "marketPlacePublisherId": "str", + "partnerId": "str", + "planId": "str", + "saasSubscriptionId": "str", + "saasSubscriptionName": "str", + }, + } + ], + "managedOnBehalfOfConfiguration": {"moboBrokerResources": [{"id": "str"}]}, + "provisioningState": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_begin_update(self, resource_group): + response = self.client.agri_service.begin_update( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + properties={ + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "properties": { + "config": { + "appServiceResourceId": "str", + "cosmosDbResourceId": "str", + "instanceUri": "str", + "keyVaultResourceId": "str", + "redisCacheResourceId": "str", + "storageAccountResourceId": "str", + "version": "str", + }, + "dataConnectorCredentials": [ + { + "key": "str", + "value": { + "clientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + "kind": "str", + }, + } + ], + "installedSolutions": [ + { + "key": "str", + "value": { + "applicationName": "str", + "marketPlacePublisherId": "str", + "partnerId": "str", + "planId": "str", + "saasSubscriptionId": "str", + "saasSubscriptionName": "str", + }, + } + ], + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_begin_delete(self, resource_group): + response = self.client.agri_service.begin_delete( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_list_by_resource_group(self, resource_group): + response = self.client.agri_service.list_by_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_list_by_subscription(self, resource_group): + response = self.client.agri_service.list_by_subscription() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_agri_service_list_available_solutions(self, resource_group): + response = self.client.agri_service.list_available_solutions( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations_async.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations_async.py new file mode 100644 index 000000000000..249d79419141 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_agri_service_operations_async.py @@ -0,0 +1,205 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.agricultureplatform.aio import AgriculturePlatformMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAgriculturePlatformMgmtAgriServiceOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AgriculturePlatformMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_get(self, resource_group): + response = await self.client.agri_service.get( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_begin_create_or_update(self, resource_group): + response = await ( + await self.client.agri_service.begin_create_or_update( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + resource={ + "location": "str", + "id": "str", + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "name": "str", + "properties": { + "config": { + "appServiceResourceId": "str", + "cosmosDbResourceId": "str", + "instanceUri": "str", + "keyVaultResourceId": "str", + "redisCacheResourceId": "str", + "storageAccountResourceId": "str", + "version": "str", + }, + "dataConnectorCredentials": [ + { + "key": "str", + "value": { + "clientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + "kind": "str", + }, + } + ], + "installedSolutions": [ + { + "key": "str", + "value": { + "applicationName": "str", + "marketPlacePublisherId": "str", + "partnerId": "str", + "planId": "str", + "saasSubscriptionId": "str", + "saasSubscriptionName": "str", + }, + } + ], + "managedOnBehalfOfConfiguration": {"moboBrokerResources": [{"id": "str"}]}, + "provisioningState": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_begin_update(self, resource_group): + response = await ( + await self.client.agri_service.begin_update( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + properties={ + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "properties": { + "config": { + "appServiceResourceId": "str", + "cosmosDbResourceId": "str", + "instanceUri": "str", + "keyVaultResourceId": "str", + "redisCacheResourceId": "str", + "storageAccountResourceId": "str", + "version": "str", + }, + "dataConnectorCredentials": [ + { + "key": "str", + "value": { + "clientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + "kind": "str", + }, + } + ], + "installedSolutions": [ + { + "key": "str", + "value": { + "applicationName": "str", + "marketPlacePublisherId": "str", + "partnerId": "str", + "planId": "str", + "saasSubscriptionId": "str", + "saasSubscriptionName": "str", + }, + } + ], + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_begin_delete(self, resource_group): + response = await ( + await self.client.agri_service.begin_delete( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_list_by_resource_group(self, resource_group): + response = self.client.agri_service.list_by_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_list_by_subscription(self, resource_group): + response = self.client.agri_service.list_by_subscription() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_agri_service_list_available_solutions(self, resource_group): + response = await self.client.agri_service.list_available_solutions( + resource_group_name=resource_group.name, + agri_service_resource_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations.py new file mode 100644 index 000000000000..c3385ab56880 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.agricultureplatform import AgriculturePlatformMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAgriculturePlatformMgmtOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AgriculturePlatformMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations_async.py b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations_async.py new file mode 100644 index 000000000000..69d2554f1df4 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/generated_tests/test_agriculture_platform_mgmt_operations_async.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.agricultureplatform.aio import AgriculturePlatformMgmtClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAgriculturePlatformMgmtOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AgriculturePlatformMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/pyproject.toml b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/pyproject.toml new file mode 100644 index 000000000000..854500de7117 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/pyproject.toml @@ -0,0 +1,86 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-agricultureplatform" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Agricultureplatform Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.agricultureplatform._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-agricultureplatform" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "Agricultureplatform Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "AgriculturePlatformMgmtClient" diff --git a/sdk/agricultureplatform/azure-mgmt-agricultureplatform/tsp-location.yaml b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/tsp-location.yaml new file mode 100644 index 000000000000..3eb0ae04cf50 --- /dev/null +++ b/sdk/agricultureplatform/azure-mgmt-agricultureplatform/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/agricultureplatform/AgriculturePlatform.Management +commit: 6a9ac1728fd1b59dcf80b8f7e27b1d5f8ccdfb8e +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/agricultureplatform/ci.yml b/sdk/agricultureplatform/ci.yml new file mode 100644 index 000000000000..cd7ae593e3f1 --- /dev/null +++ b/sdk/agricultureplatform/ci.yml @@ -0,0 +1,34 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/agricultureplatform/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/agricultureplatform/ + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: agricultureplatform + TestProxy: true + Artifacts: + - name: azure-mgmt-agricultureplatform + safeName: azuremgmtagricultureplatform From 1d795e46a29b3fd2d0bfc933f8b68cec8c079ba4 Mon Sep 17 00:00:00 2001 From: M-Hietala <78813398+M-Hietala@users.noreply.github.com> Date: Thu, 5 Feb 2026 09:20:41 -0600 Subject: [PATCH 62/84] update operation name add support for message attributes (#44979) * update operation name and add support for message attributes * adding support of input and output message attributes for responses trace * updating assets.json * change agent creation system instructions from event to attribute * adding support for opt-in trace context propagation * small update to readme * fix review findings * updating test recording * changing provider name to microsoft.foundry * making baggage header inclusion separately configurable for trace propagation --- sdk/ai/azure-ai-projects/CHANGELOG.md | 5 + sdk/ai/azure-ai-projects/README.md | 43 +- sdk/ai/azure-ai-projects/assets.json | 2 +- .../telemetry/_ai_project_instrumentor.py | 370 ++- .../telemetry/_responses_instrumentor.py | 243 +- .../azure/ai/projects/telemetry/_utils.py | 40 +- .../telemetry/test_ai_agents_instrumentor.py | 801 +++--- .../test_ai_agents_instrumentor_async.py | 809 +++--- .../telemetry/test_responses_instrumentor.py | 2233 +++++++++++------ .../test_responses_instrumentor_async.py | 567 +++-- ...sponses_instrumentor_browser_automation.py | 27 +- ...s_instrumentor_browser_automation_async.py | 27 +- ...responses_instrumentor_code_interpreter.py | 27 +- ...ses_instrumentor_code_interpreter_async.py | 27 +- ...test_responses_instrumentor_file_search.py | 27 +- ...esponses_instrumentor_file_search_async.py | 27 +- .../test_responses_instrumentor_mcp.py | 634 +++-- .../test_responses_instrumentor_mcp_async.py | 1169 +++++---- .../test_responses_instrumentor_workflow.py | 27 +- ...t_responses_instrumentor_workflow_async.py | 27 +- 20 files changed, 4500 insertions(+), 2632 deletions(-) diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 0cac8cb15095..9e6b24b66a3f 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -5,6 +5,7 @@ ### Features Added * Tracing: included agent ID in response generation traces when available. +* Tracing: Added support for opt-in trace context propagation. ### Breaking changes @@ -23,6 +24,10 @@ * Rename class `ItemParam` to `InputItem`. * Tracing: workflow actions in conversation item listings are now emitted as "gen_ai.conversation.item" events (with role="workflow") instead of "gen_ai.workflow.action" events in the list_conversation_items span. * Tracing: response generation span names changed from "responses {model_name}" to "chat {model_name}" for model calls and from "responses {agent_name}" to "invoke_agent {agent_name}" for agent calls. +* Tracing: response generation operation names changed from "responses" to "chat" for model calls and from "responses" to "invoke_agent" for agent calls. +* Tracing: response generation uses gen_ai.input.messages and gen_ai.output.messages attributes directly under the span instead of events. +* Tracing: agent creation uses gen_ai.system.instructions attribute directly under the span instead of an event. +* Tracing: "gen_ai.provider.name" attribute value changed to "microsoft.foundry". ## 2.0.0b3 (2026-01-06) diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index f6c858708b72..86e711138dcb 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -1017,11 +1017,52 @@ AIProjectInstrumentor().instrument() See the full sample in file `\agents\telemetry\sample_agent_basic_with_console_tracing.py` in the [Samples][samples] folder. +### Enabling trace context propagation + +Trace context propagation allows client-side spans generated by the Projects SDK to be correlated with server-side spans from Azure OpenAI and other Azure services. When enabled, the SDK automatically injects W3C Trace Context headers (`traceparent` and `tracestate`) into HTTP requests made by OpenAI clients obtained via `get_openai_client()`. + +This feature ensures that all operations within a distributed trace share the same trace ID, providing end-to-end visibility across your application and Azure services in your observability backend (such as Azure Monitor). + +To enable trace context propagation, set the `AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION` environment variable to `true`: + +If no value is provided for the `enable_trace_context_propagation` parameter with the AIProjectInstrumentor.instrument()` call and the environment variable is not set, trace context propagation defaults to `false` (opt-in). + +**Important Security and Privacy Considerations:** + +- **Trace IDs**: When trace context propagation is enabled, trace IDs are sent to Azure OpenAI and other external services. +- **Request Correlation**: Trace IDs allow Azure services to correlate requests from the same session or user across multiple API calls, which may have privacy implications depending on your use case. +- **Opt-in by Design**: This feature is disabled by default to give you explicit control over when trace context is propagated to external services. + +Only enable trace context propagation after carefully reviewing your observability, privacy and security requirements. + +#### Controlling baggage propagation + +When trace context propagation is enabled, you can separately control whether the baggage header is included. By default, only `traceparent` and `tracestate` headers are propagated. To also include the `baggage` header, set the `AZURE_TRACING_GEN_AI_TRACE_CONTEXT_PROPAGATION_INCLUDE_BAGGAGE` environment variable to `true`: + +If no value is provided for the `enable_baggage_propagation` parameter with the `AIProjectInstrumentor.instrument()` call and the environment variable is not set, the value defaults to `false` and baggage is not included. + +**Why is baggage propagation separate?** + +The baggage header can contain arbitrary key-value pairs added anywhere in your application's trace context. Unlike trace IDs (which are randomly generated identifiers), baggage may contain: +- User identifiers or session information +- Authentication tokens or credentials +- Business-specific data or metadata +- Personally identifiable information (PII) + +Baggage is automatically propagated through your entire application's call chain, meaning data added in one part of your application will be included in requests to Azure OpenAI unless explicitly controlled. + +**Important Security Considerations:** + +- **Review Baggage Contents**: Before enabling baggage propagation, audit what data your application (and any third-party libraries) adds to OpenTelemetry baggage. +- **Sensitive Data Risk**: Baggage is sent to Azure OpenAI and may be logged or processed by Microsoft services. Never add sensitive information to baggage when baggage propagation is enabled. +- **Opt-in by Design**: Baggage propagation is disabled by default (even when trace context propagation is enabled) to prevent accidental exposure of sensitive data. +- **Minimal Propagation**: `traceparent` and `tracestate` headers are generally sufficient for distributed tracing. Only enable baggage propagation if your specific observability requirements demand it. + ### Enabling content recording Content recording controls whether message contents and tool call related details, such as parameters and return values, are captured with the traces. This data may include sensitive user information. -To enable content recording, set the `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` environment variable to `true`. If the environment variable is not set, content recording defaults to `false`. +To enable content recording, set the `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` environment variable to `true`. If the environment variable is not set and no value is provided with the `AIProjectInstrumentor().instrument()` call for the content recording parameter, content recording defaults to `false`. **Important:** The environment variable only controls content recording for built-in traces. When you use custom tracing decorators on your own functions, all parameters and return values are always traced. diff --git a/sdk/ai/azure-ai-projects/assets.json b/sdk/ai/azure-ai-projects/assets.json index 24777c3b7249..af8c0b06a8c4 100644 --- a/sdk/ai/azure-ai-projects/assets.json +++ b/sdk/ai/azure-ai-projects/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/ai/azure-ai-projects", - "Tag": "python/ai/azure-ai-projects_212aab4d9b" + "Tag": "python/ai/azure-ai-projects_92b666ecb8" } diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py index ba9a5da65c3a..6dbc434212d4 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py @@ -21,15 +21,17 @@ from azure.core.settings import settings from azure.core.tracing import AbstractSpan from ._utils import ( - AZURE_AI_AGENTS_PROVIDER, + AGENTS_PROVIDER, ERROR_TYPE, GEN_AI_AGENT_DESCRIPTION, GEN_AI_AGENT_ID, GEN_AI_AGENT_NAME, GEN_AI_EVENT_CONTENT, + GEN_AI_INPUT_MESSAGES, GEN_AI_MESSAGE_ID, GEN_AI_MESSAGE_STATUS, GEN_AI_OPERATION_NAME, + GEN_AI_OUTPUT_MESSAGES, GEN_AI_PROVIDER_NAME, GEN_AI_SYSTEM_MESSAGE, GEN_AI_THREAD_ID, @@ -53,6 +55,7 @@ ERROR_MESSAGE, OperationName, start_span, + _get_use_message_events, ) from ._responses_instrumentor import _ResponsesInstrumentorPreview @@ -76,14 +79,101 @@ "AIProjectInstrumentor", ] -_agents_traces_enabled: bool = False +_projects_traces_enabled: bool = False _trace_agents_content: bool = False +_trace_context_propagation_enabled: bool = False +_trace_context_baggage_propagation_enabled: bool = False + + +def _inject_trace_context_sync(request): + """Synchronous event hook to inject trace context (traceparent) into outgoing requests. + + :param request: The httpx Request object. + :type request: httpx.Request + """ + try: + from opentelemetry import propagate + + carrier = dict(request.headers) + propagate.inject(carrier) + for key, value in carrier.items(): + key_lower = key.lower() + # Always include traceparent and tracestate + # Only include baggage if explicitly enabled + if key_lower in ("traceparent", "tracestate"): + if key_lower not in [h.lower() for h in request.headers.keys()]: + request.headers[key] = value + elif key_lower == "baggage" and _trace_context_baggage_propagation_enabled: + if key_lower not in [h.lower() for h in request.headers.keys()]: + request.headers[key] = value + except Exception as e: # pylint: disable=broad-exception-caught + logger.debug("Failed to inject trace context: %s", e) + + +async def _inject_trace_context_async(request): + """Async event hook to inject trace context (traceparent) into outgoing requests. + + :param request: The httpx Request object. + :type request: httpx.Request + """ + try: + from opentelemetry import propagate + + carrier = dict(request.headers) + propagate.inject(carrier) + for key, value in carrier.items(): + key_lower = key.lower() + # Always include traceparent and tracestate + # Only include baggage if explicitly enabled + if key_lower in ("traceparent", "tracestate"): + if key_lower not in [h.lower() for h in request.headers.keys()]: + request.headers[key] = value + elif key_lower == "baggage" and _trace_context_baggage_propagation_enabled: + if key_lower not in [h.lower() for h in request.headers.keys()]: + request.headers[key] = value + except Exception as e: # pylint: disable=broad-exception-caught + logger.debug("Failed to inject trace context: %s", e) + + +def _enable_trace_propagation_for_openai_client(openai_client): + """Enable trace context propagation for an OpenAI client. + + This function hooks into the httpx client used by the OpenAI SDK to inject + trace context headers (traceparent, tracestate) into outgoing HTTP requests. + This ensures that client-side spans and server-side spans share the same trace ID. + + :param openai_client: The OpenAI client instance. + :type openai_client: Any + """ + try: + # Access the underlying httpx client + if hasattr(openai_client, "_client"): + httpx_client = openai_client._client # pylint: disable=protected-access + + # Check if the client has event hooks support + if hasattr(httpx_client, "_event_hooks"): + event_hooks = httpx_client._event_hooks # pylint: disable=protected-access + + # Determine if this is an async client + is_async = hasattr(httpx_client, "__aenter__") + + # Add appropriate hook based on client type + if "request" in event_hooks: + hook_to_add = _inject_trace_context_async if is_async else _inject_trace_context_sync + + # Check if our hook is already registered to avoid duplicates + if hook_to_add not in event_hooks["request"]: + event_hooks["request"].append(hook_to_add) + logger.debug("Enabled trace propagation for %s OpenAI client", "async" if is_async else "sync") + except Exception as e: # pylint: disable=broad-exception-caught + logger.debug("Failed to enable trace propagation for OpenAI client: %s", e) class TraceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): # pylint: disable=C4747 """An enumeration class to represent different types of traces.""" AGENTS = "Agents" + PROJECT = "Project" class AIProjectInstrumentor: @@ -106,7 +196,12 @@ def __init__(self): self._impl = _AIAgentsInstrumentorPreview() self._responses_impl = _ResponsesInstrumentorPreview() - def instrument(self, enable_content_recording: Optional[bool] = None) -> None: + def instrument( + self, + enable_content_recording: Optional[bool] = None, + enable_trace_context_propagation: Optional[bool] = None, + enable_baggage_propagation: Optional[bool] = None, + ) -> None: """ Enable trace instrumentation for AIProjectClient. @@ -123,9 +218,24 @@ def instrument(self, enable_content_recording: Optional[bool] = None) -> None: if the environment variable is not found), even if instrument was already previously called without uninstrument being called in between the instrument calls. :type enable_content_recording: bool, optional + :param enable_trace_context_propagation: Whether to enable automatic trace context propagation + to OpenAI SDK HTTP requests. When enabled, traceparent and tracestate headers will be injected + into requests made by OpenAI clients obtained via get_openai_client(), allowing server-side + spans to be correlated with client-side spans. `True` will enable it, `False` will + disable it. If no value is provided, then the value read from environment variable + AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION is used. If the environment + variable is not found, then the value will default to `False`. + :type enable_trace_context_propagation: bool, optional + :param enable_baggage_propagation: Whether to include baggage headers in trace context propagation. + Only applies when enable_trace_context_propagation is True. `True` will enable baggage propagation, + `False` will disable it. If no value is provided, then the value read from environment variable + AZURE_TRACING_GEN_AI_TRACE_CONTEXT_PROPAGATION_INCLUDE_BAGGAGE is used. If the environment + variable is not found, then the value will default to `False`. + Note: Baggage may contain sensitive application data. + :type enable_baggage_propagation: bool, optional """ - self._impl.instrument(enable_content_recording) + self._impl.instrument(enable_content_recording, enable_trace_context_propagation, enable_baggage_propagation) self._responses_impl.instrument(enable_content_recording) def uninstrument(self) -> None: @@ -170,7 +280,12 @@ def _str_to_bool(self, s): return False return str(s).lower() == "true" - def instrument(self, enable_content_recording: Optional[bool] = None): + def instrument( + self, + enable_content_recording: Optional[bool] = None, + enable_trace_context_propagation: Optional[bool] = None, + enable_baggage_propagation: Optional[bool] = None, + ): """ Enable trace instrumentation for AI Agents. @@ -187,6 +302,17 @@ def instrument(self, enable_content_recording: Optional[bool] = None): if the environment variable is not found), even if instrument was already previously called without uninstrument being called in between the instrument calls. :type enable_content_recording: bool, optional + :param enable_trace_context_propagation: Whether to enable automatic trace context propagation. + `True` will enable it, `False` will disable it. If no value is provided, then the + value read from environment variable AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION + is used. If the environment variable is not found, then the value will default to `False`. + :type enable_trace_context_propagation: bool, optional + :param enable_baggage_propagation: Whether to include baggage in trace context propagation. + Only applies when enable_trace_context_propagation is True. `True` will enable it, `False` + will disable it. If no value is provided, then the value read from environment variable + AZURE_TRACING_GEN_AI_TRACE_CONTEXT_PROPAGATION_INCLUDE_BAGGAGE is used. If the + environment variable is not found, then the value will default to `False`. + :type enable_baggage_propagation: bool, optional """ if enable_content_recording is None: @@ -194,24 +320,38 @@ def instrument(self, enable_content_recording: Optional[bool] = None): var_value = os.environ.get("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT") enable_content_recording = self._str_to_bool(var_value) + if enable_trace_context_propagation is None: + var_value = os.environ.get("AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION") + enable_trace_context_propagation = self._str_to_bool(var_value) + + if enable_baggage_propagation is None: + var_value = os.environ.get("AZURE_TRACING_GEN_AI_TRACE_CONTEXT_PROPAGATION_INCLUDE_BAGGAGE") + enable_baggage_propagation = self._str_to_bool(var_value) + if not self.is_instrumented(): - self._instrument_agents(enable_content_recording) + self._instrument_projects( + enable_content_recording, enable_trace_context_propagation, enable_baggage_propagation + ) else: self._set_enable_content_recording(enable_content_recording=enable_content_recording) + self._set_enable_trace_context_propagation( + enable_trace_context_propagation=enable_trace_context_propagation + ) + self._set_enable_baggage_propagation(enable_baggage_propagation=enable_baggage_propagation) def uninstrument(self): """ - Disable trace instrumentation for AI Agents. + Disable trace instrumentation for AI Projects. This method removes any active instrumentation, stopping the tracing - of AI Agents. + of AI Projects. """ if self.is_instrumented(): - self._uninstrument_agents() + self._uninstrument_projects() def is_instrumented(self): """ - Check if trace instrumentation for AI Agents is currently enabled. + Check if trace instrumentation for AI Projects is currently enabled. :return: True if instrumentation is active, False otherwise. :rtype: bool @@ -275,7 +415,7 @@ def _create_event_attributes( run_step_last_error: Optional[Any] = None, usage: Optional[Any] = None, ) -> Dict[str, Any]: - attrs: Dict[str, Any] = {GEN_AI_PROVIDER_NAME: AZURE_AI_AGENTS_PROVIDER} + attrs: Dict[str, Any] = {GEN_AI_PROVIDER_NAME: AGENTS_PROVIDER} if thread_id: attrs[GEN_AI_THREAD_ID] = thread_id @@ -366,7 +506,7 @@ def add_thread_message_event( usage=usage, ) - def _add_message_event( + def _add_message_event( # pylint: disable=too-many-branches,too-many-statements self, span, role: str, @@ -423,30 +563,52 @@ def _add_message_event( # No metadata, use content array directly as the event data event_data = content_array if isinstance(content_array, list) else {} - attributes = self._create_event_attributes( - thread_id=thread_id, - agent_id=agent_id, - thread_run_id=thread_run_id, - message_id=message_id, - message_status=message_status, - usage=usage, - ) - # Store as JSON - either array or object depending on metadata - if not metadata and content_array: - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - else: - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(event_data, ensure_ascii=False) + use_events = _get_use_message_events() + + if use_events: + # Use events for message tracing + attributes = self._create_event_attributes( + thread_id=thread_id, + agent_id=agent_id, + thread_run_id=thread_run_id, + message_id=message_id, + message_status=message_status, + usage=usage, + ) + # Store as JSON - either array or object depending on metadata + if not metadata and content_array: + attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) + else: + attributes[GEN_AI_EVENT_CONTENT] = json.dumps(event_data, ensure_ascii=False) + + event_name = None + if role == "user": + event_name = "gen_ai.input.message" + elif role == "system": + event_name = "gen_ai.system_instruction" + else: + event_name = "gen_ai.input.message" - event_name = None - if role == "user": - event_name = "gen_ai.input.message" - elif role == "system": - event_name = "gen_ai.system_instruction" + span.span_instance.add_event(name=event_name, attributes=attributes) else: - event_name = "gen_ai.input.message" + # Use attributes for message tracing + # Prepare message content as JSON + message_json = json.dumps( + [{"role": role, "parts": content_array}] if content_array else [{"role": role}], ensure_ascii=False + ) + + # Determine which attribute to use based on role + if role == "user": + attribute_name = GEN_AI_INPUT_MESSAGES + elif role == "assistant": + attribute_name = GEN_AI_OUTPUT_MESSAGES + else: + # Default to input messages for other roles (including system) + attribute_name = GEN_AI_INPUT_MESSAGES - # span.span_instance.add_event(name=f"gen_ai.{role}.message", attributes=attributes) - span.span_instance.add_event(name=event_name, attributes=attributes) + # Set the attribute on the span + if span and span.span_instance.is_recording: + span.add_attribute(attribute_name, message_json) def _get_field(self, obj: Any, field: str) -> Any: if not obj: @@ -502,10 +664,23 @@ def _add_instructions_event( content_array.append({"type": "response_schema", "content": schema_str}) - attributes = self._create_event_attributes(agent_id=agent_id, thread_id=thread_id) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - span.span_instance.add_event(name=GEN_AI_SYSTEM_MESSAGE, attributes=attributes) + use_events = _get_use_message_events() + + if use_events: + # Use events for instructions tracing + attributes = self._create_event_attributes(agent_id=agent_id, thread_id=thread_id) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) + span.span_instance.add_event(name=GEN_AI_SYSTEM_MESSAGE, attributes=attributes) + else: + # Use attributes for instructions tracing + # System instructions use the same attribute name as the event + message_json = json.dumps( + [{"role": "system", "parts": content_array}] if content_array else [{"role": "system"}], + ensure_ascii=False, + ) + if span and span.span_instance.is_recording: + span.add_attribute(GEN_AI_SYSTEM_MESSAGE, message_json) def _status_to_string(self, status: Any) -> str: return status.value if hasattr(status, "value") else status @@ -1106,11 +1281,64 @@ def _agents_apis(self): ) return sync_apis, async_apis + def _project_apis(self): + """Define AIProjectClient APIs to instrument for trace propagation. + + :return: A tuple containing sync and async API tuples. + :rtype: Tuple[Tuple, Tuple] + """ + sync_apis = ( + ( + "azure.ai.projects", + "AIProjectClient", + "get_openai_client", + TraceType.PROJECT, + "get_openai_client", + ), + ) + async_apis = ( + ( + "azure.ai.projects.aio", + "AIProjectClient", + "get_openai_client", + TraceType.PROJECT, + "get_openai_client", + ), + ) + return sync_apis, async_apis + + def _inject_openai_client(self, f, _trace_type, _name): + """Injector for get_openai_client that enables trace context propagation if opted in. + + :return: The wrapped function with trace context propagation enabled. + :rtype: Callable + """ + + @functools.wraps(f) + def wrapper(*args, **kwargs): + openai_client = f(*args, **kwargs) + if _trace_context_propagation_enabled: + _enable_trace_propagation_for_openai_client(openai_client) + return openai_client + + wrapper._original = f # type: ignore # pylint: disable=protected-access + return wrapper + def _agents_api_list(self): sync_apis, async_apis = self._agents_apis() yield sync_apis, self._inject_sync yield async_apis, self._inject_async + def _project_api_list(self): + """Generate project API list with custom injector. + + :return: A generator yielding API tuples with injectors. + :rtype: Generator + """ + sync_apis, async_apis = self._project_apis() + yield sync_apis, self._inject_openai_client + yield async_apis, self._inject_openai_client + def _generate_api_and_injector(self, apis): for api, injector in apis: for module_name, class_name, method_name, trace_type, name in api: @@ -1134,18 +1362,24 @@ def _generate_api_and_injector(self, apis): "An unexpected error occurred: '%s'", str(e) ) - def _available_agents_apis_and_injectors(self): + def _available_projects_apis_and_injectors(self): """ - Generates a sequence of tuples containing Agents API classes, method names, and + Generates a sequence of tuples containing Agents and Project API classes, method names, and corresponding injector functions. :return: A generator yielding tuples. :rtype: tuple """ yield from self._generate_api_and_injector(self._agents_api_list()) + yield from self._generate_api_and_injector(self._project_api_list()) - def _instrument_agents(self, enable_content_tracing: bool = False): - """This function modifies the methods of the Agents API classes to + def _instrument_projects( + self, + enable_content_tracing: bool = False, + enable_trace_context_propagation: bool = False, + enable_baggage_propagation: bool = False, + ): + """This function modifies the methods of the Projects API classes to inject logic before calling the original methods. The original methods are stored as _original attributes of the methods. @@ -1153,48 +1387,60 @@ def _instrument_agents(self, enable_content_tracing: bool = False): This also controls whether function call tool function names, parameter names and parameter values are traced. :type enable_content_tracing: bool + :param enable_trace_context_propagation: Whether to enable automatic trace context propagation. + :type enable_trace_context_propagation: bool + :param enable_baggage_propagation: Whether to include baggage in trace context propagation. + :type enable_baggage_propagation: bool """ # pylint: disable=W0603 - global _agents_traces_enabled + global _projects_traces_enabled global _trace_agents_content - if _agents_traces_enabled: + global _trace_context_propagation_enabled + global _trace_context_baggage_propagation_enabled + if _projects_traces_enabled: raise RuntimeError("Traces already started for AI Agents") - _agents_traces_enabled = True + _projects_traces_enabled = True _trace_agents_content = enable_content_tracing + _trace_context_propagation_enabled = enable_trace_context_propagation + _trace_context_baggage_propagation_enabled = enable_baggage_propagation for ( api, method, trace_type, injector, name, - ) in self._available_agents_apis_and_injectors(): + ) in self._available_projects_apis_and_injectors(): # Check if the method of the api class has already been modified if not hasattr(getattr(api, method), "_original"): setattr(api, method, injector(getattr(api, method), trace_type, name)) - def _uninstrument_agents(self): - """This function restores the original methods of the Agents API classes + def _uninstrument_projects(self): + """This function restores the original methods of the Projects API classes by assigning them back from the _original attributes of the modified methods. """ # pylint: disable=W0603 - global _agents_traces_enabled + global _projects_traces_enabled global _trace_agents_content + global _trace_context_propagation_enabled + global _trace_context_baggage_propagation_enabled _trace_agents_content = False - for api, method, _, _, _ in self._available_agents_apis_and_injectors(): + _trace_context_propagation_enabled = False + _trace_context_baggage_propagation_enabled = False + for api, method, _, _, _ in self._available_projects_apis_and_injectors(): if hasattr(getattr(api, method), "_original"): setattr(api, method, getattr(getattr(api, method), "_original")) - _agents_traces_enabled = False + _projects_traces_enabled = False def _is_instrumented(self): - """This function returns True if Agents API has already been instrumented + """This function returns True if Projects API has already been instrumented for tracing and False if it has not been instrumented. - :return: A value indicating whether the Agents API is currently instrumented or not. + :return: A value indicating whether the Projects API is currently instrumented or not. :rtype: bool """ - return _agents_traces_enabled + return _projects_traces_enabled def _set_enable_content_recording(self, enable_content_recording: bool = False) -> None: """This function sets the content recording value. @@ -1215,6 +1461,24 @@ def _is_content_recording_enabled(self) -> bool: """ return _trace_agents_content + def _set_enable_trace_context_propagation(self, enable_trace_context_propagation: bool = False) -> None: + """This function sets the trace context propagation value. + + :param enable_trace_context_propagation: Indicates whether automatic trace context propagation should be enabled. + :type enable_trace_context_propagation: bool + """ + global _trace_context_propagation_enabled # pylint: disable=W0603 + _trace_context_propagation_enabled = enable_trace_context_propagation + + def _set_enable_baggage_propagation(self, enable_baggage_propagation: bool = False) -> None: + """This function sets the baggage propagation value. + + :param enable_baggage_propagation: Indicates whether baggage should be included in trace context propagation. + :type enable_baggage_propagation: bool + """ + global _trace_context_baggage_propagation_enabled # pylint: disable=W0603 + _trace_context_baggage_propagation_enabled = enable_baggage_propagation + def record_error(self, span, exc): # Set the span status to error if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py index 37a14d1f682b..c1cf1edd2cad 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_responses_instrumentor.py @@ -33,9 +33,11 @@ GEN_AI_CONVERSATION_ITEM_EVENT, GEN_AI_CONVERSATION_ITEM_ID, GEN_AI_EVENT_CONTENT, + GEN_AI_INPUT_MESSAGES, GEN_AI_OPENAI_RESPONSE_SERVICE_TIER, GEN_AI_OPENAI_RESPONSE_SYSTEM_FINGERPRINT, GEN_AI_OPERATION_NAME, + GEN_AI_OUTPUT_MESSAGES, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TOOLS, @@ -48,14 +50,19 @@ GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USER_MESSAGE_EVENT, GEN_AI_WORKFLOW_ACTION_EVENT, + OPERATION_NAME_CHAT, + OPERATION_NAME_INVOKE_AGENT, OperationName, SERVER_ADDRESS, SERVER_PORT, SPAN_NAME_CHAT, SPAN_NAME_INVOKE_AGENT, + _get_use_message_events, start_span, + RESPONSES_PROVIDER, ) + _Unset: Any = object() logger = logging.getLogger(__name__) @@ -80,9 +87,6 @@ _trace_responses_content: bool = False _trace_binary_data: bool = False -# Azure OpenAI system identifier for traces -AZURE_OPENAI_SYSTEM = "azure.openai" - # Metrics instruments _operation_duration_histogram = None _token_usage_histogram = None @@ -236,7 +240,7 @@ def _record_operation_duration( attributes = { GEN_AI_OPERATION_NAME: operation_name, - GEN_AI_PROVIDER_NAME: AZURE_OPENAI_SYSTEM, + GEN_AI_PROVIDER_NAME: RESPONSES_PROVIDER, } if server_address: @@ -269,7 +273,7 @@ def _record_token_usage( attributes = { GEN_AI_OPERATION_NAME: operation_name, - GEN_AI_PROVIDER_NAME: AZURE_OPENAI_SYSTEM, + GEN_AI_PROVIDER_NAME: RESPONSES_PROVIDER, GEN_AI_TOKEN_TYPE: token_type, } @@ -525,7 +529,7 @@ def _create_event_attributes( conversation_id: Optional[str] = None, # pylint: disable=unused-argument message_role: Optional[str] = None, ) -> Dict[str, Any]: - attrs: Dict[str, Any] = {GEN_AI_PROVIDER_NAME: AZURE_OPENAI_SYSTEM} + attrs: Dict[str, Any] = {GEN_AI_PROVIDER_NAME: RESPONSES_PROVIDER} # Removed conversation_id from event attributes as requested - it's redundant # if conversation_id: # attrs[GEN_AI_CONVERSATION_ID] = conversation_id @@ -534,6 +538,35 @@ def _create_event_attributes( # attrs[GEN_AI_MESSAGE_ROLE] = message_role return attrs + def _append_to_message_attribute( + self, + span: "AbstractSpan", + attribute_name: str, + new_messages: List[Dict[str, Any]], + ) -> None: + """Helper to append messages to an existing attribute, combining with previous messages.""" + # Get existing attribute value + existing_value = span.span_instance.attributes.get(attribute_name) if span.span_instance.attributes else None + + if existing_value: + # Parse existing JSON array + try: + existing_messages = json.loads(existing_value) + if not isinstance(existing_messages, list): + existing_messages = [] + except (json.JSONDecodeError, TypeError): + existing_messages = [] + + # Append new messages + combined_messages = existing_messages + new_messages + else: + # No existing value, just use new messages + combined_messages = new_messages + + # Set the combined value + combined_json = json.dumps(combined_messages, ensure_ascii=False) + span.add_attribute(attribute_name, combined_json) + def _add_message_event( self, span: "AbstractSpan", @@ -542,7 +575,7 @@ def _add_message_event( conversation_id: Optional[str] = None, finish_reason: Optional[str] = None, ) -> None: - """Add a message event to the span.""" + """Add a message event or attribute to the span based on configuration.""" content_array: List[Dict[str, Any]] = [] # Always include role and finish_reason, only include actual content if tracing is enabled @@ -567,23 +600,37 @@ def _add_message_event( content_array.append(role_obj) - attributes = self._create_event_attributes( - conversation_id=conversation_id, - message_role=role, - ) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - - # Map role to appropriate event name constant - if role == "user": - event_name = GEN_AI_USER_MESSAGE_EVENT - elif role == "assistant": - event_name = GEN_AI_ASSISTANT_MESSAGE_EVENT - else: - # Fallback for any other roles (shouldn't happen in practice) - event_name = f"gen_ai.{role}.message" + # Serialize the content array to JSON + json_content = json.dumps(content_array, ensure_ascii=False) + + if _get_use_message_events(): + # Original event-based implementation + attributes = self._create_event_attributes( + conversation_id=conversation_id, + message_role=role, + ) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json_content + + # Map role to appropriate event name constant + if role == "user": + event_name = GEN_AI_USER_MESSAGE_EVENT + elif role == "assistant": + event_name = GEN_AI_ASSISTANT_MESSAGE_EVENT + else: + # Fallback for any other roles (shouldn't happen in practice) + event_name = f"gen_ai.{role}.message" - span.span_instance.add_event(name=event_name, attributes=attributes) + span.span_instance.add_event(name=event_name, attributes=attributes) + else: + # New attribute-based implementation + # Append messages to the appropriate attribute (accumulating multiple messages) + if role in ("user", "tool"): + # User and tool messages go to input.messages + self._append_to_message_attribute(span, GEN_AI_INPUT_MESSAGES, content_array) + elif role == "assistant": + # Assistant messages go to output.messages + self._append_to_message_attribute(span, GEN_AI_OUTPUT_MESSAGES, content_array) def _add_tool_message_events( # pylint: disable=too-many-branches self, @@ -671,15 +718,20 @@ def _add_tool_message_events( # pylint: disable=too-many-branches # Always include parts array with type and id, even when content recording is disabled content_array = [{"role": "tool", "parts": parts}] if parts else [] - attributes = self._create_event_attributes( - conversation_id=conversation_id, - message_role="tool", - ) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) + if _get_use_message_events(): + # Event-based mode: add events + attributes = self._create_event_attributes( + conversation_id=conversation_id, + message_role="tool", + ) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - # Use "tool" for the event name: gen_ai.tool.message - span.span_instance.add_event(name=GEN_AI_TOOL_MESSAGE_EVENT, attributes=attributes) + # Use "tool" for the event name: gen_ai.tool.message + span.span_instance.add_event(name=GEN_AI_TOOL_MESSAGE_EVENT, attributes=attributes) + else: + # Attribute-based mode: append to input messages (tool outputs are inputs to the model) + self._append_to_message_attribute(span, GEN_AI_INPUT_MESSAGES, content_array) def _add_mcp_response_events( self, @@ -748,15 +800,20 @@ def _add_mcp_response_events( # Always include parts array with type and id, even when content recording is disabled content_array = [{"role": "user", "parts": parts}] if parts else [] - attributes = self._create_event_attributes( - conversation_id=conversation_id, - message_role="user", - ) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) + if _get_use_message_events(): + # Event-based mode: add events + attributes = self._create_event_attributes( + conversation_id=conversation_id, + message_role="user", + ) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - # Use user message event name since MCP responses are user inputs - span.span_instance.add_event(name=GEN_AI_USER_MESSAGE_EVENT, attributes=attributes) + # Use user message event name since MCP responses are user inputs + span.span_instance.add_event(name=GEN_AI_USER_MESSAGE_EVENT, attributes=attributes) + else: + # Attribute-based mode: append to input messages (MCP responses are user inputs) + self._append_to_message_attribute(span, GEN_AI_INPUT_MESSAGES, content_array) def _add_workflow_action_events( self, @@ -785,7 +842,7 @@ def _add_workflow_action_events( # Create event attributes event_attributes = { - GEN_AI_PROVIDER_NAME: AZURE_OPENAI_SYSTEM, + GEN_AI_PROVIDER_NAME: RESPONSES_PROVIDER, } # Build workflow action details object @@ -940,25 +997,36 @@ def _add_structured_input_events( role_obj["parts"] = parts content_array = [role_obj] - # Create event attributes - attributes = self._create_event_attributes( - conversation_id=conversation_id, - message_role=role, - ) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) + if _get_use_message_events(): + # Event-based mode + # Create event attributes + attributes = self._create_event_attributes( + conversation_id=conversation_id, + message_role=role, + ) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) + + # Map role to appropriate event name constant + if role == "user": + event_name = GEN_AI_USER_MESSAGE_EVENT + elif role == "assistant": + event_name = GEN_AI_ASSISTANT_MESSAGE_EVENT + else: + # Fallback for any other roles (shouldn't happen in practice) + event_name = f"gen_ai.{role}.message" - # Map role to appropriate event name constant - if role == "user": - event_name = GEN_AI_USER_MESSAGE_EVENT - elif role == "assistant": - event_name = GEN_AI_ASSISTANT_MESSAGE_EVENT + # Add the event + span.span_instance.add_event(name=event_name, attributes=attributes) else: - # Fallback for any other roles (shouldn't happen in practice) - event_name = f"gen_ai.{role}.message" - - # Add the event - span.span_instance.add_event(name=event_name, attributes=attributes) + # Attribute-based mode + # Append messages to the appropriate attribute + if role in ("user", "tool"): + # User and tool messages go to input.messages + self._append_to_message_attribute(span, GEN_AI_INPUT_MESSAGES, content_array) + elif role == "assistant": + # Assistant messages go to output.messages + self._append_to_message_attribute(span, GEN_AI_OUTPUT_MESSAGES, content_array) except Exception: # pylint: disable=broad-exception-caught # Skip items that can't be processed @@ -975,17 +1043,24 @@ def _emit_tool_call_event( tool_call: Dict[str, Any], conversation_id: Optional[str] = None, ) -> None: - """Helper to emit a single tool call event.""" + """Helper to emit a single tool call event or attribute.""" # Wrap tool call in parts array parts = [{"type": "tool_call", "content": tool_call}] content_array = [{"role": "assistant", "parts": parts}] - attributes = self._create_event_attributes( - conversation_id=conversation_id, - message_role="assistant", - ) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - span.span_instance.add_event(name=GEN_AI_ASSISTANT_MESSAGE_EVENT, attributes=attributes) + + if _get_use_message_events(): + # Original event-based implementation + json_content = json.dumps(content_array, ensure_ascii=False) + attributes = self._create_event_attributes( + conversation_id=conversation_id, + message_role="assistant", + ) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json_content + span.span_instance.add_event(name=GEN_AI_ASSISTANT_MESSAGE_EVENT, attributes=attributes) + else: + # New attribute-based implementation - tool calls are output messages + self._append_to_message_attribute(span, GEN_AI_OUTPUT_MESSAGES, content_array) def _emit_tool_output_event( self, @@ -993,19 +1068,26 @@ def _emit_tool_output_event( tool_output: Dict[str, Any], conversation_id: Optional[str] = None, ) -> None: - """Helper to emit a single tool output event.""" + """Helper to emit a single tool output event or attribute.""" # Wrap tool output in parts array # Tool outputs are inputs TO the model (from tool execution), so use role "tool" parts = [{"type": "tool_call_output", "content": tool_output}] content_array = [{"role": "tool", "parts": parts}] - attributes = self._create_event_attributes( - conversation_id=conversation_id, - message_role="tool", - ) - # Store as JSON array directly without outer wrapper - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(content_array, ensure_ascii=False) - # Tool outputs are inputs to the model, so use input.messages event - span.span_instance.add_event(name=GEN_AI_USER_MESSAGE_EVENT, attributes=attributes) + + if _get_use_message_events(): + # Original event-based implementation + json_content = json.dumps(content_array, ensure_ascii=False) + attributes = self._create_event_attributes( + conversation_id=conversation_id, + message_role="tool", + ) + # Store as JSON array directly without outer wrapper + attributes[GEN_AI_EVENT_CONTENT] = json_content + # Tool outputs are inputs to the model, so use input.messages event + span.span_instance.add_event(name=GEN_AI_USER_MESSAGE_EVENT, attributes=attributes) + else: + # New attribute-based implementation - tool outputs are input messages + self._append_to_message_attribute(span, GEN_AI_INPUT_MESSAGES, content_array) def _add_tool_call_events( # pylint: disable=too-many-branches self, @@ -1486,10 +1568,13 @@ def start_responses_span( # Build span name: agent case uses "invoke_agent", non-agent case uses "chat" if assistant_name: span_name = f"{SPAN_NAME_INVOKE_AGENT} {assistant_name}" + operation_name_value = OPERATION_NAME_INVOKE_AGENT elif model: span_name = f"{SPAN_NAME_CHAT} {model}" + operation_name_value = OPERATION_NAME_CHAT else: span_name = OperationName.RESPONSES.value + operation_name_value = OperationName.RESPONSES.value span = start_span( operation_name=OperationName.RESPONSES, @@ -1497,14 +1582,14 @@ def start_responses_span( port=port, span_name=span_name, model=model, - gen_ai_provider=AZURE_OPENAI_SYSTEM, + gen_ai_provider=RESPONSES_PROVIDER, ) if span and span.span_instance.is_recording: # Set operation name attribute (start_span doesn't set this automatically) self._set_attributes( span, - (GEN_AI_OPERATION_NAME, OperationName.RESPONSES.value), + (GEN_AI_OPERATION_NAME, operation_name_value), ) # Set response-specific attributes that start_span doesn't handle @@ -3266,7 +3351,7 @@ def start_create_conversation_span( server_address=server_address, port=port, span_name=OperationName.CREATE_CONVERSATION.value, - gen_ai_provider=AZURE_OPENAI_SYSTEM, + gen_ai_provider=RESPONSES_PROVIDER, ) if span and span.span_instance.is_recording: @@ -3464,7 +3549,7 @@ def start_list_conversation_items_span( server_address=server_address, port=port, span_name=OperationName.LIST_CONVERSATION_ITEMS.value, - gen_ai_provider=AZURE_OPENAI_SYSTEM, + gen_ai_provider=RESPONSES_PROVIDER, ) if span and span.span_instance.is_recording: @@ -4113,7 +4198,7 @@ def _add_conversation_item_event( # pylint: disable=too-many-branches,too-many- # Create event attributes event_attributes = { - GEN_AI_PROVIDER_NAME: AZURE_OPENAI_SYSTEM, + GEN_AI_PROVIDER_NAME: RESPONSES_PROVIDER, GEN_AI_CONVERSATION_ITEM_ID: item_id, } diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py index 050268a6e133..f41f2495b3b1 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_utils.py @@ -91,13 +91,18 @@ GEN_AI_SYSTEM_INSTRUCTION_EVENT = "gen_ai.system.instructions" GEN_AI_AGENT_WORKFLOW_EVENT = "gen_ai.agent.workflow" +# Attribute names for messages (when USE_MESSAGE_EVENTS = False) +GEN_AI_INPUT_MESSAGES = "gen_ai.input.messages" +GEN_AI_OUTPUT_MESSAGES = "gen_ai.output.messages" + # Metric names GEN_AI_CLIENT_OPERATION_DURATION = "gen_ai.client.operation.duration" GEN_AI_CLIENT_TOKEN_USAGE = "gen_ai.client.token.usage" # Constant attribute values AZURE_AI_AGENTS_SYSTEM = "az.ai.agents" -AZURE_AI_AGENTS_PROVIDER = "azure.ai.agents" +AGENTS_PROVIDER = "microsoft.foundry" +RESPONSES_PROVIDER = "microsoft.foundry" AGENT_TYPE_PROMPT = "prompt" AGENT_TYPE_WORKFLOW = "workflow" AGENT_TYPE_HOSTED = "hosted" @@ -107,6 +112,35 @@ SPAN_NAME_INVOKE_AGENT = "invoke_agent" SPAN_NAME_CHAT = "chat" +# Operation names for gen_ai.operation.name attribute +OPERATION_NAME_INVOKE_AGENT = "invoke_agent" +OPERATION_NAME_CHAT = "chat" + +# Configuration: Controls whether input/output messages are emitted as events or attributes +# Can be set at runtime for testing purposes (internal use only) +# Set to True for event-based, False for attribute-based (default) +_use_message_events = False + + +def _get_use_message_events() -> bool: + """Get the current message tracing mode (events vs attributes). Internal use only. + + :return: True if using events, False if using attributes + :rtype: bool + """ + return _use_message_events + + +def _set_use_message_events(use_events: bool) -> None: + """ + Set the message tracing mode at runtime. Internal use only. + + :param use_events: True to use events (default), False to use attributes + :type use_events: bool + """ + global _use_message_events # pylint: disable=global-statement + _use_message_events = use_events + class OperationName(Enum): CREATE_AGENT = "create_agent" @@ -143,7 +177,7 @@ def start_span( reasoning_summary: Optional[str] = None, structured_inputs: Optional[str] = None, gen_ai_system: Optional[str] = None, - gen_ai_provider: Optional[str] = AZURE_AI_AGENTS, + gen_ai_provider: Optional[str] = AGENTS_PROVIDER, kind: SpanKind = SpanKind.CLIENT, ) -> "Optional[AbstractSpan]": global _span_impl_type # pylint: disable=global-statement @@ -164,7 +198,7 @@ def start_span( if span and span.span_instance.is_recording: span.add_attribute(AZ_NAMESPACE, AZ_NAMESPACE_VALUE) - span.add_attribute(GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS) + span.add_attribute(GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER) if gen_ai_provider: span.add_attribute(GEN_AI_PROVIDER_NAME, gen_ai_provider) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor.py index fe1f1ae1c27b..b5e62189aede 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor.py @@ -51,9 +51,10 @@ GEN_AI_AGENT_WORKFLOW_EVENT, GEN_AI_CONVERSATION_ITEM_TYPE, AZURE_AI_AGENTS_SYSTEM, - AZURE_AI_AGENTS_PROVIDER, + AGENTS_PROVIDER, AGENT_TYPE_PROMPT, AGENT_TYPE_WORKFLOW, + _set_use_message_events, ) settings.tracing_implementation = "OpenTelemetry" @@ -182,11 +183,14 @@ def set_env_var(var_name, value): self.cleanup() # This also undefines CONTENT_TRACING_ENV_VARIABLE os.environ.pop(OLD_CONTENT_TRACING_ENV_VARIABLE, None) - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy - def test_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): + def _test_agent_creation_with_tracing_content_recording_enabled_impl(self, use_events: bool, **kwargs): + """Implementation for agent creation with content recording enabled test. + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) self.setup_telemetry() assert True == AIProjectInstrumentor().is_content_recording_enabled() @@ -202,36 +206,6 @@ def test_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): model=model, # Optional parameters instructions="You are a helpful AI assistant. Be polite and provide accurate information.", - # temperature=0.7, - # top_p=0.9, - # # Reasoning configuration - # reasoning=Reasoning( - # effort="medium", - # summary="auto", - # ), - # # Tools that the model can use - # tools=[ - # # Function tool for custom functions - # FunctionTool( - # name="get_weather", - # description="Get the current weather for a location", - # parameters={ - # "type": "object", - # "properties": { - # "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}, - # "unit": { - # "type": "string", - # "enum": ["celsius", "fahrenheit"], - # "description": "The temperature unit", - # }, - # }, - # "required": ["location"], - # }, - # strict=True, # Enforce strict parameter validation - # ), - # ], - # # Text response configuration - # text=PromptAgentDefinitionText(format=ResponseTextFormatConfigurationText()), ) agent = project_client.agents.create_version(agent_name="myagent", definition=agent_definition) @@ -247,40 +221,98 @@ def test_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): assert len(spans) == 1 span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), - # ("gen_ai.request.temperature", "0.7"), - # ("gen_ai.request.top_p", "0.9"), - # ("gen_ai.request.response_format", "text"), - # ("gen_ai.request.reasoning.effort", "medium"), - # ("gen_ai.request.reasoning.summary", "auto"), (GEN_AI_AGENT_NAME, "myagent"), (GEN_AI_AGENT_ID, "myagent:" + str(version)), (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] + + # When using attributes, add the system instructions attribute to expected list + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json + + expected_system_message = json.dumps( + [ + { + "role": "system", + "parts": [ + { + "type": "text", + "content": "You are a helpful AI assistant. Be polite and provide accurate information.", + } + ], + } + ], + ensure_ascii=False, + ) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_message)) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - expected_events = [ - { - "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, - "attributes": { - GEN_AI_PROVIDER_NAME: AZURE_AI_AGENTS_PROVIDER, - GEN_AI_EVENT_CONTENT: '[{"type": "text", "content": "You are a helpful AI assistant. Be polite and provide accurate information."}]', - }, - } - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + if use_events: + # When using events, check for events + expected_events = [ + { + "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, + "attributes": { + GEN_AI_PROVIDER_NAME: AGENTS_PROVIDER, + GEN_AI_EVENT_CONTENT: '[{"type": "text", "content": "You are a helpful AI assistant. Be polite and provide accurate information."}]', + }, + } + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # When using attributes, check for gen_ai.system.instructions attribute + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json + + assert span.attributes is not None + assert GEN_AI_SYSTEM_MESSAGE in span.attributes + + system_message_json = span.attributes[GEN_AI_SYSTEM_MESSAGE] + system_message = json.loads(system_message_json) + + # Verify structure + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + assert "parts" in system_message[0] + assert len(system_message[0]["parts"]) == 1 + assert system_message[0]["parts"][0]["type"] == "text" + assert ( + system_message[0]["parts"][0]["content"] + == "You are a helpful AI assistant. Be polite and provide accurate information." + ) - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy - def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): + def test_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): + """Test agent creation with content recording enabled using events.""" + self._test_agent_creation_with_tracing_content_recording_enabled_impl(use_events=True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_creation_with_tracing_content_recording_enabled_with_attributes(self, **kwargs): + """Test agent creation with content recording enabled using attributes.""" + self._test_agent_creation_with_tracing_content_recording_enabled_impl(use_events=False, **kwargs) + + def _test_agent_creation_with_tracing_content_recording_disabled_impl(self, use_events: bool, **kwargs): + """Implementation for agent creation with content recording disabled test. + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) self.setup_telemetry() assert False == AIProjectInstrumentor().is_content_recording_enabled() @@ -290,46 +322,13 @@ def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): model = kwargs.get("azure_ai_model_deployment_name") agent_definition = PromptAgentDefinition( - # Required parameter model=model, - # Optional parameters instructions="You are a helpful AI assistant. Always be polite and provide accurate information.", - # temperature=0.7, - # top_p=0.9, - # # Reasoning configuration - # reasoning=Reasoning( - # effort="medium", - # summary="auto", - # ), - # # Tools that the model can use - # tools=[ - # # Function tool for custom functions - # FunctionTool( - # name="get_weather", - # description="Get the current weather for a location", - # parameters={ - # "type": "object", - # "properties": { - # "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}, - # "unit": { - # "type": "string", - # "enum": ["celsius", "fahrenheit"], - # "description": "The temperature unit", - # }, - # }, - # "required": ["location"], - # }, - # strict=True, # Enforce strict parameter validation - # ), - # ], - # Text response configuration - # text=PromptAgentDefinitionText(format=ResponseTextFormatConfigurationText()), ) agent = project_client.agents.create_version(agent_name="myagent", definition=agent_definition) version = agent.version - # delete agent and close client project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) print("Deleted agent") @@ -339,119 +338,91 @@ def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): assert len(spans) == 1 span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), - # ("gen_ai.request.temperature", "0.7"), - # ("gen_ai.request.top_p", "0.9"), - # ("gen_ai.request.response_format", "text"), - # ("gen_ai.request.reasoning.effort", "medium"), - # ("gen_ai.request.reasoning.summary", "auto"), (GEN_AI_AGENT_NAME, "myagent"), (GEN_AI_AGENT_ID, "myagent:" + str(version)), (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] - attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) - assert attributes_match == True - - expected_events = [ - { - "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, - "attributes": { - GEN_AI_PROVIDER_NAME: AZURE_AI_AGENTS_PROVIDER, - GEN_AI_EVENT_CONTENT: "[]", - }, - } - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True - - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy - def test_workflow_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): - """Test workflow agent creation with content recording enabled.""" - self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) - self.setup_telemetry() - assert True == AIProjectInstrumentor().is_content_recording_enabled() - assert True == AIProjectInstrumentor().is_instrumented() - from azure.ai.projects.models import WorkflowAgentDefinition + # When using attributes (regardless of content recording), add system message attribute + # When content recording is disabled, it will have empty content (just role) + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json - with self.create_client(operation_group="tracing", **kwargs) as project_client: + # Empty system message (no parts, just role) + expected_system_message = json.dumps([{"role": "system"}], ensure_ascii=False) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_message)) - workflow_yaml = """ -kind: workflow -trigger: - kind: OnConversationStart - id: test_workflow - actions: - - kind: SetVariable - id: set_variable - variable: Local.TestVar - value: "test" -""" - - agent = project_client.agents.create_version( - agent_name="test-workflow-agent", - definition=WorkflowAgentDefinition(workflow=workflow_yaml), - ) - version = agent.version - - # delete agent - project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - print("Deleted workflow agent") - - # ------------------------- Validate "create_agent" span --------------------------------- - self.exporter.force_flush() - spans = self.exporter.get_spans_by_name("create_agent test-workflow-agent") - assert len(spans) == 1 - span = spans[0] - expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), - (GEN_AI_OPERATION_NAME, "create_agent"), - (SERVER_ADDRESS, ""), - (GEN_AI_AGENT_NAME, "test-workflow-agent"), - (GEN_AI_AGENT_ID, "test-workflow-agent:" + str(version)), - (GEN_AI_AGENT_VERSION, str(version)), - (GEN_AI_AGENT_TYPE, AGENT_TYPE_WORKFLOW), - ] attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Verify workflow event with standard content format - events = span.events - assert len(events) == 1 - workflow_event = events[0] - assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT + if use_events: + expected_events = [ + { + "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, + "attributes": { + GEN_AI_PROVIDER_NAME: AGENTS_PROVIDER, + GEN_AI_EVENT_CONTENT: "[]", + }, + } + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # When using attributes and content recording disabled, verify empty structure + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json + + assert span.attributes is not None + assert GEN_AI_SYSTEM_MESSAGE in span.attributes + + system_message_json = span.attributes[GEN_AI_SYSTEM_MESSAGE] + system_message = json.loads(system_message_json) + # Should have empty content (just role, no parts) + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + # No parts field when content recording is disabled + assert "parts" not in system_message[0] - import json - - event_content = json.loads(workflow_event.attributes[GEN_AI_EVENT_CONTENT]) - # New optimized format: direct array with "content" field for workflow YAML - assert isinstance(event_content, list) - assert len(event_content) == 1 - assert event_content[0]["type"] == "workflow" - assert "content" in event_content[0] - assert "kind: workflow" in event_content[0]["content"] + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): + """Test agent creation with content recording disabled using events.""" + self._test_agent_creation_with_tracing_content_recording_disabled_impl(use_events=True, **kwargs) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy - def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): - """Test workflow agent creation with content recording disabled.""" + def test_agent_creation_with_tracing_content_recording_disabled_with_attributes(self, **kwargs): + """Test agent creation with content recording disabled using attributes.""" + self._test_agent_creation_with_tracing_content_recording_disabled_impl(use_events=False, **kwargs) + + def _test_workflow_agent_creation_impl(self, use_events: bool, content_recording_enabled: bool, **kwargs): + """Implementation for workflow agent creation test. + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + :param content_recording_enabled: Whether content recording is enabled. + :type content_recording_enabled: bool + """ self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) + _set_use_message_events(use_events) + os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True" if content_recording_enabled else "False"}) self.setup_telemetry() - assert False == AIProjectInstrumentor().is_content_recording_enabled() + assert content_recording_enabled == AIProjectInstrumentor().is_content_recording_enabled() assert True == AIProjectInstrumentor().is_instrumented() from azure.ai.projects.models import WorkflowAgentDefinition - with self.create_client(operation_group="agents", **kwargs) as project_client: + operation_group = "tracing" if content_recording_enabled else "agents" + with self.create_client(operation_group=operation_group, **kwargs) as project_client: workflow_yaml = """ kind: workflow @@ -471,7 +442,6 @@ def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, * ) version = agent.version - # delete agent project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) print("Deleted workflow agent") @@ -481,7 +451,7 @@ def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, * assert len(spans) == 1 span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_AGENT_NAME, "test-workflow-agent"), @@ -492,120 +462,84 @@ def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, * attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Verify workflow event is present but content is empty when content recording is disabled - events = span.events - assert len(events) == 1 - workflow_event = events[0] - assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT + if use_events: + # Verify workflow event + events = span.events + assert len(events) == 1 + workflow_event = events[0] + assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT - import json + import json - event_content = json.loads(workflow_event.attributes[GEN_AI_EVENT_CONTENT]) - # When content recording is disabled, event should be an empty array - assert isinstance(event_content, list) - assert len(event_content) == 0 + event_content = json.loads(workflow_event.attributes[GEN_AI_EVENT_CONTENT]) + assert isinstance(event_content, list) + + if content_recording_enabled: + assert len(event_content) == 1 + assert event_content[0]["type"] == "workflow" + assert "content" in event_content[0] + assert "kind: workflow" in event_content[0]["content"] + else: + # When content recording is disabled, event should be empty + assert len(event_content) == 0 + else: + # When using attributes, workflow events are still sent as events (not attributes) + # So we still validate events, but this is mainly for consistency + events = span.events + assert len(events) == 1 + workflow_event = events[0] + assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy - def test_agent_with_structured_output_with_instructions_content_recording_enabled(self, **kwargs): - """Test agent creation with structured output and instructions, content recording enabled.""" - self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) - self.setup_telemetry() - assert True == AIProjectInstrumentor().is_content_recording_enabled() - assert True == AIProjectInstrumentor().is_instrumented() - - from azure.ai.projects.models import TextResponseFormatJsonSchema - - with self.create_client(operation_group="tracing", **kwargs) as project_client: - - model = kwargs.get("azure_ai_model_deployment_name") - - # Define a JSON schema for structured output - test_schema = { - "type": "object", - "properties": { - "name": {"type": "string"}, - "age": {"type": "number"}, - }, - "required": ["name", "age"], - } - - agent_definition = PromptAgentDefinition( - model=model, - instructions="You are a helpful assistant that extracts person information.", - text=PromptAgentDefinitionText( - format=TextResponseFormatJsonSchema( - name="PersonInfo", - schema=test_schema, - ) - ), - ) - - agent = project_client.agents.create_version(agent_name="structured-agent", definition=agent_definition) - version = agent.version - - project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - - # Validate span - self.exporter.force_flush() - spans = self.exporter.get_spans_by_name("create_agent structured-agent") - assert len(spans) == 1 - span = spans[0] - - expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), - (GEN_AI_OPERATION_NAME, "create_agent"), - (SERVER_ADDRESS, ""), - (GEN_AI_REQUEST_MODEL, model), - ("gen_ai.request.response_format", "json_schema"), - (GEN_AI_AGENT_NAME, "structured-agent"), - (GEN_AI_AGENT_ID, "structured-agent:" + str(version)), - (GEN_AI_AGENT_VERSION, str(version)), - (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), - ] - attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) - assert attributes_match == True - - # Verify event contains both instructions and schema - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json - - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 2 # Both instructions and schema + def test_workflow_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): + """Test workflow agent creation with content recording enabled using events.""" + self._test_workflow_agent_creation_impl(use_events=True, content_recording_enabled=True, **kwargs) - # Check instructions content - assert event_content[0]["type"] == "text" - assert "helpful assistant" in event_content[0]["content"] + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy + def test_workflow_agent_creation_with_tracing_content_recording_enabled_with_attributes(self, **kwargs): + """Test workflow agent creation with content recording enabled using attributes.""" + self._test_workflow_agent_creation_impl(use_events=False, content_recording_enabled=True, **kwargs) - # Check schema content - assert event_content[1]["type"] == "response_schema" - schema_str = event_content[1]["content"] - schema_obj = json.loads(schema_str) - assert schema_obj["type"] == "object" - assert "name" in schema_obj["properties"] - assert "age" in schema_obj["properties"] + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy + def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): + """Test workflow agent creation with content recording disabled using events.""" + self._test_workflow_agent_creation_impl(use_events=True, content_recording_enabled=False, **kwargs) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy - def test_agent_with_structured_output_with_instructions_content_recording_disabled(self, **kwargs): - """Test agent creation with structured output and instructions, content recording disabled.""" + def test_workflow_agent_creation_with_tracing_content_recording_disabled_with_attributes(self, **kwargs): + """Test workflow agent creation with content recording disabled using attributes.""" + self._test_workflow_agent_creation_impl(use_events=False, content_recording_enabled=False, **kwargs) + + def _test_agent_with_structured_output_with_instructions_impl( + self, use_events: bool, content_recording_enabled: bool, **kwargs + ): + """Implementation for agent with structured output and instructions test. + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + :param content_recording_enabled: Whether content recording is enabled. + :type content_recording_enabled: bool + """ self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) + _set_use_message_events(use_events) + os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True" if content_recording_enabled else "False"}) self.setup_telemetry() - assert False == AIProjectInstrumentor().is_content_recording_enabled() + assert content_recording_enabled == AIProjectInstrumentor().is_content_recording_enabled() assert True == AIProjectInstrumentor().is_instrumented() from azure.ai.projects.models import TextResponseFormatJsonSchema + import json - with self.create_client(operation_group="agents", **kwargs) as project_client: + operation_group = "tracing" if content_recording_enabled else "agents" + with self.create_client(operation_group=operation_group, **kwargs) as project_client: model = kwargs.get("azure_ai_model_deployment_name") @@ -641,7 +575,7 @@ def test_agent_with_structured_output_with_instructions_content_recording_disabl span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), @@ -651,35 +585,145 @@ def test_agent_with_structured_output_with_instructions_content_recording_disabl (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] + + # When using attributes, add system message attribute (with or without content based on content_recording_enabled) + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + + if content_recording_enabled: + expected_system_msg = json.dumps( + [ + { + "role": "system", + "parts": [ + { + "type": "text", + "content": "You are a helpful assistant that extracts person information.", + }, + {"type": "response_schema", "content": json.dumps(test_schema)}, + ], + } + ], + ensure_ascii=False, + ) + else: + # When content recording disabled, attribute has empty structure + expected_system_msg = json.dumps([{"role": "system"}], ensure_ascii=False) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_msg)) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # When content recording is disabled, event should be empty - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json + if use_events: + events = span.events + assert len(events) == 1 + instruction_event = events[0] + assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT + + event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) + assert isinstance(event_content, list) + + if content_recording_enabled: + assert len(event_content) == 2 # Both instructions and schema + assert event_content[0]["type"] == "text" + assert "helpful assistant" in event_content[0]["content"] + assert event_content[1]["type"] == "response_schema" + schema_str = event_content[1]["content"] + schema_obj = json.loads(schema_str) + assert schema_obj["type"] == "object" + assert "name" in schema_obj["properties"] + assert "age" in schema_obj["properties"] + else: + assert len(event_content) == 0 # Empty when content recording disabled + else: + # When using attributes, verify attribute + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + + assert span.attributes is not None + assert GEN_AI_SYSTEM_MESSAGE in span.attributes + + system_message_json = span.attributes[GEN_AI_SYSTEM_MESSAGE] + system_message = json.loads(system_message_json) + + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + + if content_recording_enabled: + assert "parts" in system_message[0] + assert len(system_message[0]["parts"]) == 2 + + # Check instruction part + assert system_message[0]["parts"][0]["type"] == "text" + assert "helpful assistant" in system_message[0]["parts"][0]["content"] + + # Check schema part + assert system_message[0]["parts"][1]["type"] == "response_schema" + schema_obj = json.loads(system_message[0]["parts"][1]["content"]) + assert schema_obj["type"] == "object" + assert "name" in schema_obj["properties"] + else: + # When content recording disabled, no parts field + assert "parts" not in system_message[0] - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 0 # Empty when content recording disabled + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_with_structured_output_with_instructions_content_recording_enabled(self, **kwargs): + """Test agent creation with structured output and instructions, content recording enabled using events.""" + self._test_agent_with_structured_output_with_instructions_impl( + use_events=True, content_recording_enabled=True, **kwargs + ) @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy - def test_agent_with_structured_output_without_instructions_content_recording_enabled(self, **kwargs): - """Test agent creation with structured output but NO instructions, content recording enabled.""" + def test_agent_with_structured_output_with_instructions_content_recording_enabled_with_attributes(self, **kwargs): + """Test agent creation with structured output and instructions, content recording enabled using attributes.""" + self._test_agent_with_structured_output_with_instructions_impl( + use_events=False, content_recording_enabled=True, **kwargs + ) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_with_structured_output_with_instructions_content_recording_disabled(self, **kwargs): + """Test agent creation with structured output and instructions, content recording disabled using events.""" + self._test_agent_with_structured_output_with_instructions_impl( + use_events=True, content_recording_enabled=False, **kwargs + ) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_with_structured_output_with_instructions_content_recording_disabled_with_attributes(self, **kwargs): + """Test agent creation with structured output and instructions, content recording disabled using attributes.""" + self._test_agent_with_structured_output_with_instructions_impl( + use_events=False, content_recording_enabled=False, **kwargs + ) + + def _test_agent_with_structured_output_without_instructions_impl( + self, use_events: bool, content_recording_enabled: bool, **kwargs + ): + """Implementation for agent with structured output but NO instructions test. + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + :param content_recording_enabled: Whether content recording is enabled. + :type content_recording_enabled: bool + """ self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) + _set_use_message_events(use_events) + os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True" if content_recording_enabled else "False"}) self.setup_telemetry() - assert True == AIProjectInstrumentor().is_content_recording_enabled() + assert content_recording_enabled == AIProjectInstrumentor().is_content_recording_enabled() assert True == AIProjectInstrumentor().is_instrumented() from azure.ai.projects.models import TextResponseFormatJsonSchema + import json - with self.create_client(operation_group="tracing", **kwargs) as project_client: + operation_group = "tracing" if content_recording_enabled else "agents" + with self.create_client(operation_group=operation_group, **kwargs) as project_client: model = kwargs.get("azure_ai_model_deployment_name") @@ -693,7 +737,6 @@ def test_agent_with_structured_output_without_instructions_content_recording_ena agent_definition = PromptAgentDefinition( model=model, - # No instructions provided text=PromptAgentDefinitionText( format=TextResponseFormatJsonSchema( name="Result", @@ -716,7 +759,7 @@ def test_agent_with_structured_output_without_instructions_content_recording_ena span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), @@ -726,99 +769,105 @@ def test_agent_with_structured_output_without_instructions_content_recording_ena (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] + + # When using attributes, add system message attribute (with or without content based on content_recording_enabled) + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + + if content_recording_enabled: + expected_system_msg = json.dumps( + [{"role": "system", "parts": [{"type": "response_schema", "content": json.dumps(test_schema)}]}], + ensure_ascii=False, + ) + else: + # When content recording disabled, attribute has empty structure + expected_system_msg = json.dumps([{"role": "system"}], ensure_ascii=False) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_msg)) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Event should be created with just the schema (no instructions) - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json + if use_events: + events = span.events + assert len(events) == 1 + instruction_event = events[0] + assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT + + event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) + assert isinstance(event_content, list) + + if content_recording_enabled: + assert len(event_content) == 1 # Only schema, no instructions + assert event_content[0]["type"] == "response_schema" + schema_str = event_content[0]["content"] + schema_obj = json.loads(schema_str) + assert schema_obj["type"] == "object" + assert "result" in schema_obj["properties"] + else: + assert len(event_content) == 0 # Empty when content recording disabled + else: + # When using attributes, verify attribute + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + + assert span.attributes is not None + assert GEN_AI_SYSTEM_MESSAGE in span.attributes + + system_message_json = span.attributes[GEN_AI_SYSTEM_MESSAGE] + system_message = json.loads(system_message_json) + + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + + if content_recording_enabled: + assert "parts" in system_message[0] + assert len(system_message[0]["parts"]) == 1 + + # Check schema part + assert system_message[0]["parts"][0]["type"] == "response_schema" + schema_obj = json.loads(system_message[0]["parts"][0]["content"]) + assert schema_obj["type"] == "object" + assert "result" in schema_obj["properties"] + else: + # When content recording disabled, no parts field + assert "parts" not in system_message[0] - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 1 # Only schema, no instructions + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_with_structured_output_without_instructions_content_recording_enabled(self, **kwargs): + """Test agent creation with structured output but NO instructions, content recording enabled using events.""" + self._test_agent_with_structured_output_without_instructions_impl( + use_events=True, content_recording_enabled=True, **kwargs + ) - # Check schema content - assert event_content[0]["type"] == "response_schema" - schema_str = event_content[0]["content"] - schema_obj = json.loads(schema_str) - assert schema_obj["type"] == "object" - assert "result" in schema_obj["properties"] + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_with_structured_output_without_instructions_content_recording_enabled_with_attributes( + self, **kwargs + ): + """Test agent creation with structured output but NO instructions, content recording enabled using attributes.""" + self._test_agent_with_structured_output_without_instructions_impl( + use_events=False, content_recording_enabled=True, **kwargs + ) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy def test_agent_with_structured_output_without_instructions_content_recording_disabled(self, **kwargs): - """Test agent creation with structured output but NO instructions, content recording disabled.""" - self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) - self.setup_telemetry() - assert False == AIProjectInstrumentor().is_content_recording_enabled() - assert True == AIProjectInstrumentor().is_instrumented() - - from azure.ai.projects.models import TextResponseFormatJsonSchema - - with self.create_client(operation_group="agents", **kwargs) as project_client: - - model = kwargs.get("azure_ai_model_deployment_name") + """Test agent creation with structured output but NO instructions, content recording disabled using events.""" + self._test_agent_with_structured_output_without_instructions_impl( + use_events=True, content_recording_enabled=False, **kwargs + ) - test_schema = { - "type": "object", - "properties": { - "result": {"type": "string"}, - }, - "required": ["result"], - } - - agent_definition = PromptAgentDefinition( - model=model, - # No instructions provided - text=PromptAgentDefinitionText( - format=TextResponseFormatJsonSchema( - name="Result", - schema=test_schema, - ) - ), - ) - - agent = project_client.agents.create_version( - agent_name="no-instructions-agent", definition=agent_definition - ) - version = agent.version - - project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - - # Validate span - self.exporter.force_flush() - spans = self.exporter.get_spans_by_name("create_agent no-instructions-agent") - assert len(spans) == 1 - span = spans[0] - - expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), - (GEN_AI_OPERATION_NAME, "create_agent"), - (SERVER_ADDRESS, ""), - (GEN_AI_REQUEST_MODEL, model), - ("gen_ai.request.response_format", "json_schema"), - (GEN_AI_AGENT_NAME, "no-instructions-agent"), - (GEN_AI_AGENT_ID, "no-instructions-agent:" + str(version)), - (GEN_AI_AGENT_VERSION, str(version)), - (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), - ] - attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) - assert attributes_match == True - - # Event should be created with empty content due to content recording disabled - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json - - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 0 # Empty because content recording is disabled + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy + def test_agent_with_structured_output_without_instructions_content_recording_disabled_with_attributes( + self, **kwargs + ): + """Test agent creation with structured output but NO instructions, content recording disabled using attributes.""" + self._test_agent_with_structured_output_without_instructions_impl( + use_events=False, content_recording_enabled=False, **kwargs + ) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor_async.py index 39c878fd889c..bda4cd2aba04 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_ai_agents_instrumentor_async.py @@ -48,9 +48,10 @@ GEN_AI_AGENT_WORKFLOW_EVENT, GEN_AI_CONVERSATION_ITEM_TYPE, AZURE_AI_AGENTS_SYSTEM, - AZURE_AI_AGENTS_PROVIDER, + AGENTS_PROVIDER, AGENT_TYPE_PROMPT, AGENT_TYPE_WORKFLOW, + _set_use_message_events, ) settings.tracing_implementation = "OpenTelemetry" @@ -60,11 +61,14 @@ class TestAiAgentsInstrumentor(TestAiAgentsInstrumentorBase): """Tests for AI agents instrumentor.""" - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy_async - async def test_create_agent_with_tracing_content_recording_enabled(self, **kwargs): + async def _test_create_agent_with_tracing_content_recording_enabled_impl(self, use_events: bool, **kwargs): + """Implementation for agent creation with content recording enabled test (async). + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) self.setup_telemetry() assert True == AIProjectInstrumentor().is_content_recording_enabled() @@ -75,43 +79,8 @@ async def test_create_agent_with_tracing_content_recording_enabled(self, **kwarg async with project_client: agent_definition = PromptAgentDefinition( - # Required parameter model=model, - # Optional parameters instructions="You are a helpful AI assistant. Always be polite and provide accurate information.", - # temperature=0.7, - # top_p=0.9, - # # Reasoning configuration - # reasoning=Reasoning( - # effort="medium", - # summary="auto", - # ), - # # Tools that the model can use - # tools=[ - # # Function tool for custom functions - # FunctionTool( - # name="get_weather", - # description="Get the current weather for a location", - # parameters={ - # "type": "object", - # "properties": { - # "location": { - # "type": "string", - # "description": "The city and state, e.g. San Francisco, CA", - # }, - # "unit": { - # "type": "string", - # "enum": ["celsius", "fahrenheit"], - # "description": "The temperature unit", - # }, - # }, - # "required": ["location"], - # }, - # strict=True, # Enforce strict parameter validation - # ), - # ], - # # Text response configuration - # text=PromptAgentDefinitionText(format=ResponseTextFormatConfigurationText()), ) agent = await project_client.agents.create_version(agent_name="myagent", definition=agent_definition) @@ -124,40 +93,97 @@ async def test_create_agent_with_tracing_content_recording_enabled(self, **kwarg assert len(spans) == 1 span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), - # ("gen_ai.request.temperature", "0.7"), - # ("gen_ai.request.top_p", "0.9"), - # ("gen_ai.request.response_format", "text"), - # ("gen_ai.request.reasoning.effort", "medium"), - # ("gen_ai.request.reasoning.summary", "auto"), (GEN_AI_AGENT_NAME, "myagent"), (GEN_AI_AGENT_ID, "myagent:" + str(version)), (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] + + # When using attributes, add the system instructions attribute to expected list + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json + + expected_system_message = json.dumps( + [ + { + "role": "system", + "parts": [ + { + "type": "text", + "content": "You are a helpful AI assistant. Always be polite and provide accurate information.", + } + ], + } + ], + ensure_ascii=False, + ) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_message)) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - expected_events = [ - { - "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, - "attributes": { - GEN_AI_PROVIDER_NAME: AZURE_AI_AGENTS_PROVIDER, - GEN_AI_EVENT_CONTENT: '[{"type": "text", "content": "You are a helpful AI assistant. Always be polite and provide accurate information."}]', - }, - } - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + if use_events: + expected_events = [ + { + "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, + "attributes": { + GEN_AI_PROVIDER_NAME: AGENTS_PROVIDER, + GEN_AI_EVENT_CONTENT: '[{"type": "text", "content": "You are a helpful AI assistant. Always be polite and provide accurate information."}]', + }, + } + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # When using attributes, check for gen_ai.system.instructions attribute + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json + + assert span.attributes is not None + assert GEN_AI_SYSTEM_MESSAGE in span.attributes + + system_message_json = span.attributes[GEN_AI_SYSTEM_MESSAGE] + system_message = json.loads(system_message_json) + + # Verify structure + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + assert "parts" in system_message[0] + assert len(system_message[0]["parts"]) == 1 + assert system_message[0]["parts"][0]["type"] == "text" + assert ( + system_message[0]["parts"][0]["content"] + == "You are a helpful AI assistant. Always be polite and provide accurate information." + ) - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async - async def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): + async def test_create_agent_with_tracing_content_recording_enabled(self, **kwargs): + """Test agent creation with content recording enabled using events (async).""" + await self._test_create_agent_with_tracing_content_recording_enabled_impl(use_events=True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_create_agent_with_tracing_content_recording_enabled_with_attributes(self, **kwargs): + """Test agent creation with content recording enabled using attributes (async).""" + await self._test_create_agent_with_tracing_content_recording_enabled_impl(use_events=False, **kwargs) + + async def _test_agent_creation_with_tracing_content_recording_disabled_impl(self, use_events: bool, **kwargs): + """Implementation for agent creation with content recording disabled test (async). + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) self.setup_telemetry() assert False == AIProjectInstrumentor().is_content_recording_enabled() @@ -168,43 +194,8 @@ async def test_agent_creation_with_tracing_content_recording_disabled(self, **kw async with project_client: agent_definition = PromptAgentDefinition( - # Required parameter model=model, - # Optional parameters instructions="You are a helpful AI assistant. Always be polite and provide accurate information.", - # temperature=0.7, - # top_p=0.9, - # # Reasoning configuration - # reasoning=Reasoning( - # effort="medium", - # summary="auto", - # ), - # # Tools that the model can use - # tools=[ - # # Function tool for custom functions - # FunctionTool( - # name="get_weather", - # description="Get the current weather for a location", - # parameters={ - # "type": "object", - # "properties": { - # "location": { - # "type": "string", - # "description": "The city and state, e.g. San Francisco, CA", - # }, - # "unit": { - # "type": "string", - # "enum": ["celsius", "fahrenheit"], - # "description": "The temperature unit", - # }, - # }, - # "required": ["location"], - # }, - # strict=True, # Enforce strict parameter validation - # ), - # ], - # # Text response configuration - # text=PromptAgentDefinitionText(format=ResponseTextFormatConfigurationText()), ) agent = await project_client.agents.create_version(agent_name="myagent", definition=agent_definition) @@ -217,119 +208,89 @@ async def test_agent_creation_with_tracing_content_recording_disabled(self, **kw assert len(spans) == 1 span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), - # ("gen_ai.request.temperature", "0.7"), - # ("gen_ai.request.top_p", "0.9"), - # ("gen_ai.request.response_format", "text"), - # ("gen_ai.request.reasoning.effort", "medium"), - # ("gen_ai.request.reasoning.summary", "auto"), (GEN_AI_AGENT_NAME, "myagent"), (GEN_AI_AGENT_ID, "myagent:" + str(version)), (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] - attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) - assert attributes_match == True - - expected_events = [ - { - "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, - "attributes": { - GEN_AI_PROVIDER_NAME: AZURE_AI_AGENTS_PROVIDER, - GEN_AI_EVENT_CONTENT: "[]", - }, - } - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True - - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy_async - async def test_workflow_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): - """Test workflow agent creation with content recording enabled (async).""" - self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) - self.setup_telemetry() - assert True == AIProjectInstrumentor().is_content_recording_enabled() - assert True == AIProjectInstrumentor().is_instrumented() - from azure.ai.projects.models import WorkflowAgentDefinition + # When using attributes, add empty system message attribute + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json - project_client = self.create_async_client(operation_group="tracing", **kwargs) + expected_system_message = json.dumps([{"role": "system"}], ensure_ascii=False) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_message)) - async with project_client: - workflow_yaml = """ -kind: workflow -trigger: - kind: OnConversationStart - id: test_workflow - actions: - - kind: SetVariable - id: set_variable - variable: Local.TestVar - value: "test" -""" - - agent = await project_client.agents.create_version( - agent_name="test-workflow-agent-async", - definition=WorkflowAgentDefinition(workflow=workflow_yaml), - ) - version = agent.version - - # delete agent - await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - - # ------------------------- Validate "create_agent" span --------------------------------- - self.exporter.force_flush() - spans = self.exporter.get_spans_by_name("create_agent test-workflow-agent-async") - assert len(spans) == 1 - span = spans[0] - expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), - (GEN_AI_OPERATION_NAME, "create_agent"), - (SERVER_ADDRESS, ""), - (GEN_AI_AGENT_NAME, "test-workflow-agent-async"), - (GEN_AI_AGENT_ID, "test-workflow-agent-async:" + str(version)), - (GEN_AI_AGENT_VERSION, str(version)), - (GEN_AI_AGENT_TYPE, AGENT_TYPE_WORKFLOW), - ] attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Verify workflow event with standard content format - events = span.events - assert len(events) == 1 - workflow_event = events[0] - assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT + if use_events: + expected_events = [ + { + "name": GEN_AI_SYSTEM_INSTRUCTION_EVENT, + "attributes": { + GEN_AI_PROVIDER_NAME: AGENTS_PROVIDER, + GEN_AI_EVENT_CONTENT: "[]", + }, + } + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # When using attributes and content recording disabled, verify empty structure + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + import json + + assert span.attributes is not None + assert GEN_AI_SYSTEM_MESSAGE in span.attributes + + system_message_json = span.attributes[GEN_AI_SYSTEM_MESSAGE] + system_message = json.loads(system_message_json) + # Should have empty content (just role, no parts) + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + # No parts field when content recording is disabled + assert "parts" not in system_message[0] - import json - - event_content = json.loads(workflow_event.attributes[GEN_AI_EVENT_CONTENT]) - # New optimized format: direct array with "content" field for workflow YAML - assert isinstance(event_content, list) - assert len(event_content) == 1 - assert event_content[0]["type"] == "workflow" - assert "content" in event_content[0] - assert "kind: workflow" in event_content[0]["content"] + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): + """Test agent creation with content recording disabled using events (async).""" + await self._test_agent_creation_with_tracing_content_recording_disabled_impl(use_events=True, **kwargs) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy_async - async def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): - """Test workflow agent creation with content recording disabled (async).""" + async def test_agent_creation_with_tracing_content_recording_disabled_with_attributes(self, **kwargs): + """Test agent creation with content recording disabled using attributes (async).""" + await self._test_agent_creation_with_tracing_content_recording_disabled_impl(use_events=False, **kwargs) + + async def _test_workflow_agent_creation_impl(self, use_events: bool, content_recording_enabled: bool, **kwargs): + """Implementation for workflow agent creation test (async). + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + :param content_recording_enabled: Whether content recording is enabled. + :type content_recording_enabled: bool + """ self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) + _set_use_message_events(use_events) + os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True" if content_recording_enabled else "False"}) self.setup_telemetry() - assert False == AIProjectInstrumentor().is_content_recording_enabled() + assert content_recording_enabled == AIProjectInstrumentor().is_content_recording_enabled() assert True == AIProjectInstrumentor().is_instrumented() from azure.ai.projects.models import WorkflowAgentDefinition - project_client = self.create_async_client(operation_group="agents", **kwargs) + operation_group = "tracing" if content_recording_enabled else "agents" + project_client = self.create_async_client(operation_group=operation_group, **kwargs) async with project_client: workflow_yaml = """ @@ -350,7 +311,6 @@ async def test_workflow_agent_creation_with_tracing_content_recording_disabled(s ) version = agent.version - # delete agent await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) # ------------------------- Validate "create_agent" span --------------------------------- @@ -359,7 +319,7 @@ async def test_workflow_agent_creation_with_tracing_content_recording_disabled(s assert len(spans) == 1 span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_AGENT_NAME, "test-workflow-agent-async"), @@ -370,123 +330,84 @@ async def test_workflow_agent_creation_with_tracing_content_recording_disabled(s attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Verify workflow event is present but content is empty when content recording is disabled - events = span.events - assert len(events) == 1 - workflow_event = events[0] - assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT - - import json - - event_content = json.loads(workflow_event.attributes[GEN_AI_EVENT_CONTENT]) - # When content recording is disabled, event should be an empty array - assert isinstance(event_content, list) - assert len(event_content) == 0 + if use_events: + # Verify workflow event + events = span.events + assert len(events) == 1 + workflow_event = events[0] + assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT + + import json + + event_content = json.loads(workflow_event.attributes[GEN_AI_EVENT_CONTENT]) + assert isinstance(event_content, list) + + if content_recording_enabled: + assert len(event_content) == 1 + assert event_content[0]["type"] == "workflow" + assert "content" in event_content[0] + assert "kind: workflow" in event_content[0]["content"] + else: + # When content recording is disabled, event should be empty + assert len(event_content) == 0 + else: + # When using attributes, workflow events are still sent as events (not attributes) + events = span.events + assert len(events) == 1 + workflow_event = events[0] + assert workflow_event.name == GEN_AI_AGENT_WORKFLOW_EVENT @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async - async def test_agent_with_structured_output_with_instructions_content_recording_enabled(self, **kwargs): - """Test agent creation with structured output and instructions, content recording enabled (async).""" - self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) - self.setup_telemetry() - assert True == AIProjectInstrumentor().is_content_recording_enabled() - assert True == AIProjectInstrumentor().is_instrumented() - - from azure.ai.projects.models import TextResponseFormatJsonSchema - - project_client = self.create_async_client(operation_group="tracing", **kwargs) - - async with project_client: - model = kwargs.get("azure_ai_model_deployment_name") - - # Define a JSON schema for structured output - test_schema = { - "type": "object", - "properties": { - "name": {"type": "string"}, - "age": {"type": "number"}, - }, - "required": ["name", "age"], - } - - agent_definition = PromptAgentDefinition( - model=model, - instructions="You are a helpful assistant that extracts person information.", - text=PromptAgentDefinitionText( - format=TextResponseFormatJsonSchema( - name="PersonInfo", - schema=test_schema, - ) - ), - ) - - agent = await project_client.agents.create_version( - agent_name="structured-agent-async", definition=agent_definition - ) - version = agent.version - - await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - - # Validate span - self.exporter.force_flush() - spans = self.exporter.get_spans_by_name("create_agent structured-agent-async") - assert len(spans) == 1 - span = spans[0] - - expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), - (GEN_AI_OPERATION_NAME, "create_agent"), - (SERVER_ADDRESS, ""), - (GEN_AI_REQUEST_MODEL, model), - ("gen_ai.request.response_format", "json_schema"), - (GEN_AI_AGENT_NAME, "structured-agent-async"), - (GEN_AI_AGENT_ID, "structured-agent-async:" + str(version)), - (GEN_AI_AGENT_VERSION, str(version)), - (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), - ] - attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) - assert attributes_match == True - - # Verify event contains both instructions and schema - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json - - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 2 # Both instructions and schema + async def test_workflow_agent_creation_with_tracing_content_recording_enabled(self, **kwargs): + """Test workflow agent creation with content recording enabled using events (async).""" + await self._test_workflow_agent_creation_impl(use_events=True, content_recording_enabled=True, **kwargs) - # Check instructions content - assert event_content[0]["type"] == "text" - assert "helpful assistant" in event_content[0]["content"] + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_workflow_agent_creation_with_tracing_content_recording_enabled_with_attributes(self, **kwargs): + """Test workflow agent creation with content recording enabled using attributes (async).""" + await self._test_workflow_agent_creation_impl(use_events=False, content_recording_enabled=True, **kwargs) - # Check schema content - assert event_content[1]["type"] == "response_schema" - schema_str = event_content[1]["content"] - schema_obj = json.loads(schema_str) - assert schema_obj["type"] == "object" - assert "name" in schema_obj["properties"] - assert "age" in schema_obj["properties"] + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, **kwargs): + """Test workflow agent creation with content recording disabled using events (async).""" + await self._test_workflow_agent_creation_impl(use_events=True, content_recording_enabled=False, **kwargs) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy_async - async def test_agent_with_structured_output_with_instructions_content_recording_disabled(self, **kwargs): - """Test agent creation with structured output and instructions, content recording disabled (async).""" + async def test_workflow_agent_creation_with_tracing_content_recording_disabled_with_attributes(self, **kwargs): + """Test workflow agent creation with content recording disabled using attributes (async).""" + await self._test_workflow_agent_creation_impl(use_events=False, content_recording_enabled=False, **kwargs) + + async def _test_agent_with_structured_output_with_instructions_impl( + self, use_events: bool, content_recording_enabled: bool, **kwargs + ): + """Implementation for structured output with instructions test (async). + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + :param content_recording_enabled: Whether content recording is enabled. + :type content_recording_enabled: bool + """ + import json + self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) + _set_use_message_events(use_events) + os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True" if content_recording_enabled else "False"}) self.setup_telemetry() - assert False == AIProjectInstrumentor().is_content_recording_enabled() + assert content_recording_enabled == AIProjectInstrumentor().is_content_recording_enabled() assert True == AIProjectInstrumentor().is_instrumented() from azure.ai.projects.models import TextResponseFormatJsonSchema - project_client = self.create_async_client(operation_group="agents", **kwargs) + operation_group = "tracing" if content_recording_enabled else "agents" + project_client = self.create_async_client(operation_group=operation_group, **kwargs) async with project_client: model = kwargs.get("azure_ai_model_deployment_name") @@ -525,7 +446,7 @@ async def test_agent_with_structured_output_with_instructions_content_recording_ span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), @@ -535,35 +456,144 @@ async def test_agent_with_structured_output_with_instructions_content_recording_ (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] + + # Add attribute expectation when using attributes mode + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + + if content_recording_enabled: + expected_system_message = json.dumps( + [ + { + "role": "system", + "parts": [ + { + "type": "text", + "content": "You are a helpful assistant that extracts person information.", + }, + {"type": "response_schema", "content": json.dumps(test_schema)}, + ], + } + ] + ) + else: + expected_system_message = json.dumps([{"role": "system"}]) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_message)) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # When content recording is disabled, event should be empty - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT + if use_events: + # Verify event + events = span.events + assert len(events) == 1 + instruction_event = events[0] + assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT + + import json + + event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) + assert isinstance(event_content, list) + + if content_recording_enabled: + assert len(event_content) == 2 # Both instructions and schema + assert event_content[0]["type"] == "text" + assert "helpful assistant" in event_content[0]["content"] + assert event_content[1]["type"] == "response_schema" + schema_obj = json.loads(event_content[1]["content"]) + assert schema_obj["type"] == "object" + assert "name" in schema_obj["properties"] + else: + assert len(event_content) == 0 + else: + # Validate attribute + attribute_value = None + for attr_key, attr_val in span.attributes.items(): + if attr_key == GEN_AI_SYSTEM_MESSAGE: + attribute_value = attr_val + break + assert attribute_value is not None + + system_message = json.loads(attribute_value) + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + + if content_recording_enabled: + assert "parts" in system_message[0] + parts = system_message[0]["parts"] + assert len(parts) == 2 + assert parts[0]["type"] == "text" + assert "helpful assistant" in parts[0]["content"] + assert parts[1]["type"] == "response_schema" + schema_obj = json.loads(parts[1]["content"]) + assert schema_obj["type"] == "object" + else: + assert "parts" not in system_message[0] - import json - - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 0 # Empty when content recording disabled + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_with_structured_output_with_instructions_content_recording_enabled(self, **kwargs): + """Test agent creation with structured output and instructions, content recording enabled using events (async).""" + await self._test_agent_with_structured_output_with_instructions_impl( + use_events=True, content_recording_enabled=True, **kwargs + ) @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async - async def test_agent_with_structured_output_without_instructions_content_recording_enabled(self, **kwargs): - """Test agent creation with structured output but NO instructions, content recording enabled (async).""" + async def test_agent_with_structured_output_with_instructions_content_recording_enabled_with_attributes( + self, **kwargs + ): + """Test agent creation with structured output and instructions, content recording enabled using attributes (async).""" + await self._test_agent_with_structured_output_with_instructions_impl( + use_events=False, content_recording_enabled=True, **kwargs + ) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_with_structured_output_with_instructions_content_recording_disabled(self, **kwargs): + """Test agent creation with structured output and instructions, content recording disabled using events (async).""" + await self._test_agent_with_structured_output_with_instructions_impl( + use_events=True, content_recording_enabled=False, **kwargs + ) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_with_structured_output_with_instructions_content_recording_disabled_with_attributes( + self, **kwargs + ): + """Test agent creation with structured output and instructions, content recording disabled using attributes (async).""" + await self._test_agent_with_structured_output_with_instructions_impl( + use_events=False, content_recording_enabled=False, **kwargs + ) + + async def _test_agent_with_structured_output_without_instructions_impl( + self, use_events: bool, content_recording_enabled: bool, **kwargs + ): + """Implementation for structured output without instructions test (async). + + :param use_events: If True, use events for messages. If False, use attributes. + :type use_events: bool + :param content_recording_enabled: Whether content recording is enabled. + :type content_recording_enabled: bool + """ + import json + self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"}) + _set_use_message_events(use_events) + os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True" if content_recording_enabled else "False"}) self.setup_telemetry() - assert True == AIProjectInstrumentor().is_content_recording_enabled() + assert content_recording_enabled == AIProjectInstrumentor().is_content_recording_enabled() assert True == AIProjectInstrumentor().is_instrumented() from azure.ai.projects.models import TextResponseFormatJsonSchema - project_client = self.create_async_client(operation_group="tracing", **kwargs) + operation_group = "tracing" if content_recording_enabled else "agents" + project_client = self.create_async_client(operation_group=operation_group, **kwargs) async with project_client: model = kwargs.get("azure_ai_model_deployment_name") @@ -601,7 +631,7 @@ async def test_agent_with_structured_output_without_instructions_content_recordi span = spans[0] expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), + (GEN_AI_PROVIDER_NAME, AGENTS_PROVIDER), (GEN_AI_OPERATION_NAME, "create_agent"), (SERVER_ADDRESS, ""), (GEN_AI_REQUEST_MODEL, model), @@ -611,100 +641,103 @@ async def test_agent_with_structured_output_without_instructions_content_recordi (GEN_AI_AGENT_VERSION, str(version)), (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), ] + + # Add attribute expectation when using attributes mode + if not use_events: + from azure.ai.projects.telemetry._utils import GEN_AI_SYSTEM_MESSAGE + + if content_recording_enabled: + expected_system_message = json.dumps( + [{"role": "system", "parts": [{"type": "response_schema", "content": json.dumps(test_schema)}]}] + ) + else: + expected_system_message = json.dumps([{"role": "system"}]) + expected_attributes.append((GEN_AI_SYSTEM_MESSAGE, expected_system_message)) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Event should be created with just the schema (no instructions) - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json + if use_events: + # Verify event + events = span.events + assert len(events) == 1 + instruction_event = events[0] + assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT + + import json + + event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) + assert isinstance(event_content, list) + + if content_recording_enabled: + assert len(event_content) == 1 # Only schema, no instructions + assert event_content[0]["type"] == "response_schema" + schema_obj = json.loads(event_content[0]["content"]) + assert schema_obj["type"] == "object" + assert "result" in schema_obj["properties"] + else: + assert len(event_content) == 0 + else: + # Validate attribute + attribute_value = None + for attr_key, attr_val in span.attributes.items(): + if attr_key == GEN_AI_SYSTEM_MESSAGE: + attribute_value = attr_val + break + assert attribute_value is not None + + system_message = json.loads(attribute_value) + assert isinstance(system_message, list) + assert len(system_message) == 1 + assert system_message[0]["role"] == "system" + + if content_recording_enabled: + assert "parts" in system_message[0] + parts = system_message[0]["parts"] + assert len(parts) == 1 # Only schema + assert parts[0]["type"] == "response_schema" + schema_obj = json.loads(parts[0]["content"]) + assert schema_obj["type"] == "object" + assert "result" in schema_obj["properties"] + else: + assert "parts" not in system_message[0] - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 1 # Only schema, no instructions + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_with_structured_output_without_instructions_content_recording_enabled(self, **kwargs): + """Test agent creation with structured output but NO instructions, content recording enabled using events (async).""" + await self._test_agent_with_structured_output_without_instructions_impl( + use_events=True, content_recording_enabled=True, **kwargs + ) - # Check schema content - assert event_content[0]["type"] == "response_schema" - schema_str = event_content[0]["content"] - schema_obj = json.loads(schema_str) - assert schema_obj["type"] == "object" - assert "result" in schema_obj["properties"] + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_with_structured_output_without_instructions_content_recording_enabled_with_attributes( + self, **kwargs + ): + """Test agent creation with structured output but NO instructions, content recording enabled using attributes (async).""" + await self._test_agent_with_structured_output_without_instructions_impl( + use_events=False, content_recording_enabled=True, **kwargs + ) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy_async async def test_agent_with_structured_output_without_instructions_content_recording_disabled(self, **kwargs): - """Test agent creation with structured output but NO instructions, content recording disabled (async).""" - self.cleanup() - os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) - self.setup_telemetry() - assert False == AIProjectInstrumentor().is_content_recording_enabled() - assert True == AIProjectInstrumentor().is_instrumented() - - from azure.ai.projects.models import TextResponseFormatJsonSchema - - project_client = self.create_async_client(operation_group="agents", **kwargs) - - async with project_client: - model = kwargs.get("azure_ai_model_deployment_name") - - test_schema = { - "type": "object", - "properties": { - "result": {"type": "string"}, - }, - "required": ["result"], - } - - agent_definition = PromptAgentDefinition( - model=model, - # No instructions provided - text=PromptAgentDefinitionText( - format=TextResponseFormatJsonSchema( - name="Result", - schema=test_schema, - ) - ), - ) + """Test agent creation with structured output but NO instructions, content recording disabled using events (async).""" + await self._test_agent_with_structured_output_without_instructions_impl( + use_events=True, content_recording_enabled=False, **kwargs + ) - agent = await project_client.agents.create_version( - agent_name="no-instructions-agent-async", definition=agent_definition - ) - version = agent.version - - await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - - # Validate span - self.exporter.force_flush() - spans = self.exporter.get_spans_by_name("create_agent no-instructions-agent-async") - assert len(spans) == 1 - span = spans[0] - - expected_attributes = [ - (GEN_AI_PROVIDER_NAME, AZURE_AI_AGENTS_PROVIDER), - (GEN_AI_OPERATION_NAME, "create_agent"), - (SERVER_ADDRESS, ""), - (GEN_AI_REQUEST_MODEL, model), - ("gen_ai.request.response_format", "json_schema"), - (GEN_AI_AGENT_NAME, "no-instructions-agent-async"), - (GEN_AI_AGENT_ID, "no-instructions-agent-async:" + str(version)), - (GEN_AI_AGENT_VERSION, str(version)), - (GEN_AI_AGENT_TYPE, AGENT_TYPE_PROMPT), - ] - attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) - assert attributes_match == True - - # Event should be created with empty content due to content recording disabled - events = span.events - assert len(events) == 1 - instruction_event = events[0] - assert instruction_event.name == GEN_AI_SYSTEM_INSTRUCTION_EVENT - - import json - - event_content = json.loads(instruction_event.attributes[GEN_AI_EVENT_CONTENT]) - assert isinstance(event_content, list) - assert len(event_content) == 0 # Empty because content recording is disabled + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async + async def test_agent_with_structured_output_without_instructions_content_recording_disabled_with_attributes( + self, **kwargs + ): + """Test agent creation with structured output but NO instructions, content recording disabled using attributes (async).""" + await self._test_agent_with_structured_output_without_instructions_impl( + use_events=False, content_recording_enabled=False, **kwargs + ) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py index 8bf3b5077780..b70c801f7bd7 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor.py @@ -9,11 +9,18 @@ import pytest from typing import Optional, Tuple from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_CHAT, SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_CHAT, + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_CHAT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from openai import OpenAI -from devtools_testutils import recorded_by_proxy, RecordedTransport +from devtools_testutils import recorded_by_proxy, RecordedTransport, set_custom_default_matcher, add_body_key_sanitizer from azure.ai.projects.models import PromptAgentDefinition, FunctionTool from test_base import servicePreparer @@ -48,6 +55,19 @@ class TestResponsesInstrumentor(TestAiAgentsInstrumentorBase): """Tests for ResponsesInstrumentor with real endpoints.""" + @pytest.fixture(scope="session", autouse=True) + def configure_playback_matcher(self, test_proxy, add_sanitizers): + """Add body sanitizer and custom matchers for image_url in requests.""" + # Sanitize image_url in request body to a consistent placeholder + add_body_key_sanitizer(json_path="$..image_url", value="SANITIZED_IMAGE_DATA") + + # Configure playback matcher + set_custom_default_matcher( + excluded_headers="Authorization,x-ms-client-request-id,x-ms-request-id", + ignored_query_parameters="api-version", + compare_bodies=True, + ) + def _get_openai_client_and_deployment(self, **kwargs) -> Tuple[OpenAI, str]: """Create OpenAI client through AI Projects client""" # Create AI Projects client using the standard test infrastructure @@ -187,12 +207,10 @@ def set_env_var(var_name, value): finally: self.cleanup() - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.HTTPX) - def test_sync_non_streaming_with_content_recording(self, **kwargs): - """Test synchronous non-streaming responses with content recording enabled.""" + def _test_sync_non_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous non-streaming responses with content recording enabled.""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -232,9 +250,9 @@ def test_sync_non_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -242,37 +260,79 @@ def test_sync_non_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + # Check span events or attributes based on mode + if use_events: + # Check span events + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # Check span attributes for message content + assert "gen_ai.input.messages" in span.attributes # type: ignore + assert "gen_ai.output.messages" in span.attributes # type: ignore + + # Verify input messages attribute + input_messages = json.loads(span.attributes["gen_ai.input.messages"]) # type: ignore + assert len(input_messages) == 1 + assert input_messages[0]["role"] == "user" + assert len(input_messages[0]["parts"]) == 1 + assert input_messages[0]["parts"][0]["type"] == "text" + assert input_messages[0]["parts"][0]["content"] == "Write a short poem about AI" + + # Verify output messages attribute + output_messages = json.loads(span.attributes["gen_ai.output.messages"]) # type: ignore + assert len(output_messages) == 1 + assert output_messages[0]["role"] == "assistant" + assert len(output_messages[0]["parts"]) == 1 + assert output_messages[0]["parts"][0]["type"] == "text" + assert "content" in output_messages[0]["parts"][0] + assert len(output_messages[0]["parts"][0]["content"]) > 0 + assert "finish_reason" in output_messages[0] - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_sync_non_streaming_with_content_recording_events(self, **kwargs): + """Test synchronous non-streaming responses with content recording enabled (event mode).""" + self._test_sync_non_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_sync_non_streaming_without_content_recording(self, **kwargs): - """Test synchronous non-streaming responses with content recording disabled.""" + def test_sync_non_streaming_with_content_recording_attributes(self, **kwargs): + """Test synchronous non-streaming responses with content recording enabled (attribute mode).""" + self._test_sync_non_streaming_with_content_recording_impl(False, **kwargs) + + def _test_sync_non_streaming_without_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous non-streaming responses with content recording disabled.""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -312,9 +372,9 @@ def test_sync_non_streaming_without_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -322,39 +382,80 @@ def test_sync_non_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events (should not contain content, but should have role and finish_reason) - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', + # Check span events or attributes based on mode (no content) + if use_events: + # Check span events (should not contain content, but should have role and finish_reason) + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # Check span attributes for message content (without actual content) + assert "gen_ai.input.messages" in span.attributes # type: ignore + assert "gen_ai.output.messages" in span.attributes # type: ignore + + # Verify input messages attribute (no content) + input_messages = json.loads(span.attributes["gen_ai.input.messages"]) # type: ignore + assert len(input_messages) == 1 + assert input_messages[0]["role"] == "user" + assert len(input_messages[0]["parts"]) == 1 + assert input_messages[0]["parts"][0]["type"] == "text" + assert "content" not in input_messages[0]["parts"][0] # Content should be omitted + + # Verify output messages attribute (no content) + output_messages = json.loads(span.attributes["gen_ai.output.messages"]) # type: ignore + assert len(output_messages) == 1 + assert output_messages[0]["role"] == "assistant" + assert len(output_messages[0]["parts"]) == 1 + assert output_messages[0]["parts"][0]["type"] == "text" + assert "content" not in output_messages[0]["parts"][0] # Content should be omitted + assert "finish_reason" in output_messages[0] - @pytest.mark.usefixtures("instrument_with_content") + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_sync_non_streaming_without_content_recording_events(self, **kwargs): + """Test synchronous non-streaming responses with content recording disabled (event mode).""" + self._test_sync_non_streaming_without_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_sync_streaming_with_content_recording(self, **kwargs): - """Test synchronous streaming responses with content recording enabled.""" + def test_sync_non_streaming_without_content_recording_attributes(self, **kwargs): + """Test synchronous non-streaming responses with content recording disabled (attribute mode).""" + self._test_sync_non_streaming_without_content_recording_impl(False, **kwargs) + + def _test_sync_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous streaming responses with content recording enabled.""" from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -402,9 +503,9 @@ def test_sync_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -412,30 +513,101 @@ def test_sync_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events (should include assistant message for streaming) - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + # Check span events or attributes based on mode (should include assistant message for streaming) + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # Check span attributes for message content + assert "gen_ai.input.messages" in span.attributes # type: ignore + assert "gen_ai.output.messages" in span.attributes # type: ignore + + # Verify input messages attribute + input_messages = json.loads(span.attributes["gen_ai.input.messages"]) # type: ignore + assert len(input_messages) == 1 + assert input_messages[0]["role"] == "user" + assert len(input_messages[0]["parts"]) == 1 + assert input_messages[0]["parts"][0]["type"] == "text" + assert input_messages[0]["parts"][0]["content"] == "Write a short poem about AI" + + # Verify output messages attribute + output_messages = json.loads(span.attributes["gen_ai.output.messages"]) # type: ignore + assert len(output_messages) == 1 + assert output_messages[0]["role"] == "assistant" + assert len(output_messages[0]["parts"]) == 1 + assert output_messages[0]["parts"][0]["type"] == "text" + assert "content" in output_messages[0]["parts"][0] + assert len(output_messages[0]["parts"][0]["content"]) > 0 + assert "finish_reason" in output_messages[0] + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_with_content_recording_non_streaming_events(self, **kwargs): + """Test synchronous function tool usage with content recording enabled, non-streaming (event mode).""" + self._test_sync_function_tool_with_content_recording_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_with_content_recording_non_streaming_attributes(self, **kwargs): + """Test synchronous function tool usage with content recording enabled, non-streaming (attribute mode).""" + self._test_sync_function_tool_with_content_recording_non_streaming_impl(False, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_sync_non_streaming_without_conversation_events(self, **kwargs): + """Test synchronous non-streaming responses without conversation parameter (event mode).""" + self._test_sync_non_streaming_without_conversation_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_sync_non_streaming_without_conversation_attributes(self, **kwargs): + """Test synchronous non-streaming responses without conversation parameter (attribute mode).""" + self._test_sync_non_streaming_without_conversation_impl(False, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_sync_streaming_with_content_recording_events(self, **kwargs): + """Test synchronous streaming responses with content recording enabled (event mode).""" + self._test_sync_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_sync_streaming_with_content_recording_attributes(self, **kwargs): + """Test synchronous streaming responses with content recording enabled (attribute mode).""" + self._test_sync_streaming_with_content_recording_impl(False, **kwargs) @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @@ -474,7 +646,7 @@ def test_sync_conversations_create(self, **kwargs): # Check basic span attributes expected_attributes = [ ("gen_ai.operation.name", "create_conversation"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -487,6 +659,7 @@ def test_sync_conversations_create(self, **kwargs): def test_sync_list_conversation_items_with_content_recording(self, **kwargs): """Test synchronous list_conversation_items with content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -528,7 +701,7 @@ def test_sync_list_conversation_items_with_content_recording(self, **kwargs): expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), ("gen_ai.operation.name", "list_conversation_items"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -540,7 +713,7 @@ def test_sync_list_conversation_items_with_content_recording(self, **kwargs): { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}]}]', }, @@ -548,7 +721,7 @@ def test_sync_list_conversation_items_with_content_recording(self, **kwargs): { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Hello"}]}]', }, @@ -563,6 +736,7 @@ def test_sync_list_conversation_items_with_content_recording(self, **kwargs): def test_sync_list_conversation_items_without_content_recording(self, **kwargs): """Test synchronous list_conversation_items with content recording disabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -604,7 +778,7 @@ def test_sync_list_conversation_items_without_content_recording(self, **kwargs): expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), ("gen_ai.operation.name", "list_conversation_items"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -616,7 +790,7 @@ def test_sync_list_conversation_items_without_content_recording(self, **kwargs): { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}]}]', }, @@ -624,7 +798,7 @@ def test_sync_list_conversation_items_without_content_recording(self, **kwargs): { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -669,12 +843,10 @@ def test_no_instrumentation_no_spans(self): exporter.shutdown() trace._TRACER_PROVIDER = None - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.HTTPX) - def test_sync_non_streaming_without_conversation(self, **kwargs): - """Test synchronous non-streaming responses without conversation parameter.""" + def _test_sync_non_streaming_without_conversation_impl(self, use_events, **kwargs): + """Implementation for testing synchronous non-streaming responses without conversation parameter.""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -708,48 +880,75 @@ def test_sync_non_streaming_without_conversation(self, **kwargs): # Check span attributes - should NOT have conversation.id expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.response.model", deployment_name), ("gen_ai.response.id", ""), ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + # Check span events or attributes based on mode + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True - - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_function_tool_with_content_recording_non_streaming(self, **kwargs): - """Test synchronous function tool usage with content recording enabled (non-streaming).""" + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + else: + # Check span attributes for message content + assert "gen_ai.input.messages" in span.attributes # type: ignore + assert "gen_ai.output.messages" in span.attributes # type: ignore + + # Verify input messages attribute + input_messages = json.loads(span.attributes["gen_ai.input.messages"]) # type: ignore + assert len(input_messages) == 1 + assert input_messages[0]["role"] == "user" + assert len(input_messages[0]["parts"]) == 1 + assert input_messages[0]["parts"][0]["type"] == "text" + assert input_messages[0]["parts"][0]["content"] == "Write a short poem about AI" + + # Verify output messages attribute + output_messages = json.loads(span.attributes["gen_ai.output.messages"]) # type: ignore + assert len(output_messages) == 1 + assert output_messages[0]["role"] == "assistant" + assert len(output_messages[0]["parts"]) == 1 + assert output_messages[0]["parts"][0]["type"] == "text" + assert "content" in output_messages[0]["parts"][0] + assert len(output_messages[0]["parts"][0]["content"]) > 0 + assert "finish_reason" in output_messages[0] + + def _test_sync_function_tool_with_content_recording_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing synchronous function tool usage with content recording (non-streaming).""" from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -841,9 +1040,9 @@ def test_sync_function_tool_with_content_recording_non_streaming(self, **kwargs) span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -851,38 +1050,66 @@ def test_sync_function_tool_with_content_recording_non_streaming(self, **kwargs) ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True - # Check events for first span - user message and assistant tool call - expected_events_1 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Seattle?"}]}]', + # Check events or attributes for first span - user message and assistant tool call + if use_events: + expected_events_1 = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Seattle?"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) + assert events_match == True + else: + # Check span attributes + assert "gen_ai.input.messages" in span1.attributes # type: ignore + assert "gen_ai.output.messages" in span1.attributes # type: ignore + + # Verify input messages - user question + input_messages = json.loads(span1.attributes["gen_ai.input.messages"]) # type: ignore + assert len(input_messages) == 1 + assert input_messages[0]["role"] == "user" + assert input_messages[0]["parts"][0]["type"] == "text" + assert input_messages[0]["parts"][0]["content"] == "What's the weather in Seattle?" + + # Verify output messages - assistant tool call + output_messages = json.loads(span1.attributes["gen_ai.output.messages"]) # type: ignore + assert len(output_messages) == 1 + assert output_messages[0]["role"] == "assistant" + assert output_messages[0]["parts"][0]["type"] == "tool_call" + assert output_messages[0]["parts"][0]["content"]["type"] == "function_call" + assert "id" in output_messages[0]["parts"][0]["content"] + assert output_messages[0]["parts"][0]["content"]["function"]["name"] == "get_weather" + assert "arguments" in output_messages[0]["parts"][0]["content"]["function"] # Validate second span (tool output + final response) span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -890,39 +1117,56 @@ def test_sync_function_tool_with_content_recording_non_streaming(self, **kwargs) ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) assert attributes_match == True - # Check events for second span - tool output and assistant response - expected_events_2 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "tool", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "72°F", "condition": "sunny"}}}]}]', + # Check events or attributes for second span - tool output and assistant response + if use_events: + expected_events_2 = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "72°F", "condition": "sunny"}}}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) - assert events_match == True - - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): - """Test synchronous function tool usage with content recording enabled (streaming).""" + ] + events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) + assert events_match == True + else: + # Check span attributes - span2 only has output messages (continuation span) + assert "gen_ai.output.messages" in span2.attributes # type: ignore + + # Verify output messages - assistant final response + output_messages = json.loads(span2.attributes["gen_ai.output.messages"]) # type: ignore + assert len(output_messages) == 1 + assert output_messages[0]["role"] == "assistant" + assert output_messages[0]["parts"][0]["type"] == "text" + assert "content" in output_messages[0]["parts"][0] + assert len(output_messages[0]["parts"][0]["content"]) > 0 + assert "finish_reason" in output_messages[0] + + def _test_sync_function_tool_with_content_recording_streaming_impl(self, use_events, **kwargs): + """Implementation for testing synchronous function tool usage with content recording (streaming).""" from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -1037,9 +1281,9 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1047,15 +1291,26 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True # Check events for first span - user message and assistant tool call + if not use_events: + # Only validate events mode (no attribute validation yet) + return expected_events_1 = [ { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Seattle?"}]}]', }, @@ -1063,7 +1318,7 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', }, @@ -1076,9 +1331,9 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1086,15 +1341,26 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) assert attributes_match == True # Check events for second span - tool output and assistant response + if not use_events: + # Skip event validation in attribute mode + return expected_events_2 = [ { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "tool", # Commented out - now in event content "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "72°F", "condition": "sunny"}}}]}]', }, @@ -1102,7 +1368,7 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1111,14 +1377,26 @@ def test_sync_function_tool_with_content_recording_streaming(self, **kwargs): events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) assert events_match == True - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_with_content_recording_streaming_events(self, **kwargs): + """Test synchronous function tool usage with content recording enabled, streaming (event mode).""" + self._test_sync_function_tool_with_content_recording_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_function_tool_without_content_recording_non_streaming(self, **kwargs): - """Test synchronous function tool usage without content recording (non-streaming).""" + def test_sync_function_tool_with_content_recording_streaming_attributes(self, **kwargs): + """Test synchronous function tool usage with content recording enabled, streaming (attribute mode).""" + self._test_sync_function_tool_with_content_recording_streaming_impl(False, **kwargs) + + def _test_sync_function_tool_without_content_recording_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing synchronous function tool usage without content recording (non-streaming).""" from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -1209,9 +1487,9 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1219,6 +1497,14 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True @@ -1227,7 +1513,7 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -1235,22 +1521,23 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', }, }, ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True + if use_events: + events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) + assert events_match == True # Validate second span (tool output + final response) - no content span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1258,15 +1545,26 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) assert attributes_match == True # Check events for second span - role included but no content + if not use_events: + # Skip event validation in attribute mode + return expected_events_2 = [ { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "tool", # Commented out - now in event content "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', }, @@ -1274,7 +1572,7 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1283,14 +1581,12 @@ def test_sync_function_tool_without_content_recording_non_streaming(self, **kwar events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) assert events_match == True - @pytest.mark.usefixtures("instrument_without_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): - """Test synchronous function tool usage without content recording (streaming).""" + def _test_sync_function_tool_without_content_recording_streaming_impl(self, use_events, **kwargs): + """Implementation for testing synchronous function tool usage without content recording (streaming).""" from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -1399,9 +1695,9 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1409,6 +1705,14 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True @@ -1417,7 +1721,7 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -1425,22 +1729,23 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', }, }, ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True + if use_events: + events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) + assert events_match == True # Validate second span (tool output + final response) - no content span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1448,15 +1753,26 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + # In attribute mode, also expect message attributes + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) assert attributes_match == True # Check events for second span - role included but no content + if not use_events: + # Skip event validation in attribute mode + return expected_events_2 = [ { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "tool", # Commented out - now in event content "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', }, @@ -1464,7 +1780,7 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1473,6 +1789,34 @@ def test_sync_function_tool_without_content_recording_streaming(self, **kwargs): events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) assert events_match == True + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_without_content_recording_non_streaming_events(self, **kwargs): + """Test synchronous function tool usage without content recording, non-streaming (event mode).""" + self._test_sync_function_tool_without_content_recording_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_without_content_recording_non_streaming_attributes(self, **kwargs): + """Test synchronous function tool usage without content recording, non-streaming (attribute mode).""" + self._test_sync_function_tool_without_content_recording_non_streaming_impl(False, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_without_content_recording_streaming_events(self, **kwargs): + """Test synchronous function tool usage without content recording, streaming (event mode).""" + self._test_sync_function_tool_without_content_recording_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_function_tool_without_content_recording_streaming_attributes(self, **kwargs): + """Test synchronous function tool usage without content recording, streaming (attribute mode).""" + self._test_sync_function_tool_without_content_recording_streaming_impl(False, **kwargs) + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) @@ -1481,6 +1825,7 @@ def test_sync_function_tool_list_conversation_items_with_content_recording(self, from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -1576,7 +1921,7 @@ def test_sync_function_tool_list_conversation_items_with_content_recording(self, expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), ("gen_ai.operation.name", "list_conversation_items"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -1589,7 +1934,7 @@ def test_sync_function_tool_list_conversation_items_with_content_recording(self, { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}]}]', }, @@ -1597,7 +1942,7 @@ def test_sync_function_tool_list_conversation_items_with_content_recording(self, { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "72°F", "condition": "sunny"}}}]}]', }, @@ -1605,7 +1950,7 @@ def test_sync_function_tool_list_conversation_items_with_content_recording(self, { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', }, @@ -1613,7 +1958,7 @@ def test_sync_function_tool_list_conversation_items_with_content_recording(self, { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Seattle?"}]}]', }, @@ -1630,6 +1975,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -1725,7 +2071,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), ("gen_ai.operation.name", "list_conversation_items"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -1738,7 +2084,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}]}]', }, @@ -1746,7 +2092,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', }, @@ -1754,7 +2100,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', }, @@ -1762,7 +2108,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -1777,6 +2123,7 @@ def test_sync_function_tool_list_conversation_items_without_content_recording(se def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, **kwargs): """Test synchronous non-streaming responses with multiple text inputs and content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -1824,9 +2171,9 @@ def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, ** # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1842,7 +2189,7 @@ def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, ** { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Hello"}]}]', }, @@ -1850,7 +2197,7 @@ def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, ** { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a haiku about Python"}]}]', }, @@ -1858,7 +2205,7 @@ def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, ** { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1873,6 +2220,7 @@ def test_sync_multiple_text_inputs_with_content_recording_non_streaming(self, ** def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwargs): """Test synchronous streaming responses with multiple text inputs and content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -1928,9 +2276,9 @@ def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwar # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -1946,7 +2294,7 @@ def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Hello"}]}]', }, @@ -1954,7 +2302,7 @@ def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a haiku about Python"}]}]', }, @@ -1962,7 +2310,7 @@ def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1977,6 +2325,7 @@ def test_sync_multiple_text_inputs_with_content_recording_streaming(self, **kwar def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, **kwargs): """Test synchronous non-streaming responses with multiple text inputs and content recording disabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2024,9 +2373,9 @@ def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -2042,7 +2391,7 @@ def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2050,7 +2399,7 @@ def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2058,7 +2407,7 @@ def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -2073,6 +2422,7 @@ def test_sync_multiple_text_inputs_without_content_recording_non_streaming(self, def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **kwargs): """Test synchronous streaming responses with multiple text inputs and content recording disabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"}) self.setup_telemetry() assert False == AIProjectInstrumentor().is_content_recording_enabled() @@ -2123,9 +2473,9 @@ def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **k # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -2141,7 +2491,7 @@ def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **k { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2149,7 +2499,7 @@ def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **k { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2157,7 +2507,7 @@ def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **k { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -2166,12 +2516,10 @@ def test_sync_multiple_text_inputs_without_content_recording_streaming(self, **k events_match = GenAiTraceVerifier().check_span_events(span, expected_events) assert events_match == True - @pytest.mark.usefixtures("instrument_without_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_off_binary_off_non_streaming(self, **kwargs): - """Test image only with content recording OFF and binary data OFF (non-streaming).""" + def _test_image_only_content_off_binary_off_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording OFF and binary data OFF (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2214,34 +2562,69 @@ def test_image_only_content_off_binary_off_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_off_binary_off_non_streaming_events(self, **kwargs): + """Test image only with content recording OFF and binary data OFF (non-streaming, event-based messages).""" + self._test_image_only_content_off_binary_off_non_streaming_impl(True, **kwargs) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_off_binary_on_non_streaming(self, **kwargs): - """Test image only with content recording OFF and binary data ON (non-streaming).""" + def test_image_only_content_off_binary_off_non_streaming_attributes(self, **kwargs): + """Test image only with content recording OFF and binary data OFF (non-streaming, attribute-based messages).""" + self._test_image_only_content_off_binary_off_non_streaming_impl(False, **kwargs) + + def _test_image_only_content_off_binary_on_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording OFF and binary data ON (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2283,34 +2666,69 @@ def test_image_only_content_off_binary_on_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason (binary flag doesn't matter) - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True - @pytest.mark.usefixtures("instrument_with_content") + @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_on_binary_off_non_streaming(self, **kwargs): - """Test image only with content recording ON and binary data OFF (non-streaming).""" + def test_image_only_content_off_binary_on_non_streaming_events(self, **kwargs): + """Test image only with content recording OFF and binary data ON (non-streaming, event-based messages).""" + self._test_image_only_content_off_binary_on_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_off_binary_on_non_streaming_attributes(self, **kwargs): + """Test image only with content recording OFF and binary data ON (non-streaming, attribute-based messages).""" + self._test_image_only_content_off_binary_on_non_streaming_impl(False, **kwargs) + + def _test_image_only_content_on_binary_off_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording ON and binary data OFF (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2352,34 +2770,69 @@ def test_image_only_content_on_binary_off_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary OFF: should have image type but no image_url - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role":"user","parts":[{"type":"image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role":"user","parts":[{"type":"image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_on_binary_on_non_streaming(self, **kwargs): - """Test image only with content recording ON and binary data ON (non-streaming).""" + def test_image_only_content_on_binary_off_non_streaming_events(self, **kwargs): + """Test image only with content recording ON and binary data OFF (non-streaming, event-based messages).""" + self._test_image_only_content_on_binary_off_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_on_binary_off_non_streaming_attributes(self, **kwargs): + """Test image only with content recording ON and binary data OFF (non-streaming, attribute-based messages).""" + self._test_image_only_content_on_binary_off_non_streaming_impl(False, **kwargs) + + def _test_image_only_content_on_binary_on_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording ON and binary data ON (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2421,38 +2874,73 @@ def test_image_only_content_on_binary_on_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary ON: should have image type AND image_url with base64 data - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_on_binary_on_non_streaming_events(self, **kwargs): + """Test image only with content recording ON and binary data ON (non-streaming, event-based messages).""" + self._test_image_only_content_on_binary_on_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_on_binary_on_non_streaming_attributes(self, **kwargs): + """Test image only with content recording ON and binary data ON (non-streaming, attribute-based messages).""" + self._test_image_only_content_on_binary_on_non_streaming_impl(False, **kwargs) # ======================================== # Binary Data Tracing Tests (Text + Image) # ======================================== - @pytest.mark.usefixtures("instrument_without_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_off_binary_off_non_streaming(self, **kwargs): - """Test text + image with content recording OFF and binary data OFF (non-streaming).""" + def _test_text_and_image_content_off_binary_off_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording OFF and binary data OFF (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2499,34 +2987,69 @@ def test_text_and_image_content_off_binary_off_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_off_binary_off_non_streaming_events(self, **kwargs): + """Test text + image with content recording OFF and binary data OFF (non-streaming, event-based messages).""" + self._test_text_and_image_content_off_binary_off_non_streaming_impl(True, **kwargs) @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_off_binary_on_non_streaming(self, **kwargs): - """Test text + image with content recording OFF and binary data ON (non-streaming).""" + def test_text_and_image_content_off_binary_off_non_streaming_attributes(self, **kwargs): + """Test text + image with content recording OFF and binary data OFF (non-streaming, attribute-based messages).""" + self._test_text_and_image_content_off_binary_off_non_streaming_impl(False, **kwargs) + + def _test_text_and_image_content_off_binary_on_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording OFF and binary data ON (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2572,34 +3095,70 @@ def test_text_and_image_content_off_binary_on_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + # Content OFF + attribute mode: both input and output messages are captured + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason (binary flag doesn't matter) - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True - @pytest.mark.usefixtures("instrument_with_content") + @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_on_binary_off_non_streaming(self, **kwargs): - """Test text + image with content recording ON and binary data OFF (non-streaming).""" + def test_text_and_image_content_off_binary_on_non_streaming_events(self, **kwargs): + """Test text + image with content recording OFF and binary data ON (non-streaming, event-based messages).""" + self._test_text_and_image_content_off_binary_on_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_off_binary_on_non_streaming_attributes(self, **kwargs): + """Test text + image with content recording OFF and binary data ON (non-streaming, attribute-based messages).""" + self._test_text_and_image_content_off_binary_on_non_streaming_impl(False, **kwargs) + + def _test_text_and_image_content_on_binary_off_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording ON and binary data OFF (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2645,34 +3204,69 @@ def test_text_and_image_content_on_binary_off_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary OFF: should have text and image type but no image_url - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role":"user","parts":[{"type":"text","content":"What is shown in this image?"},{"type":"image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role":"user","parts":[{"type":"text","content":"What is shown in this image?"},{"type":"image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_on_binary_on_non_streaming(self, **kwargs): - """Test text + image with content recording ON and binary data ON (non-streaming).""" + def test_text_and_image_content_on_binary_off_non_streaming_events(self, **kwargs): + """Test text + image with content recording ON and binary data OFF (non-streaming, event-based messages).""" + self._test_text_and_image_content_on_binary_off_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_on_binary_off_non_streaming_attributes(self, **kwargs): + """Test text + image with content recording ON and binary data OFF (non-streaming, attribute-based messages).""" + self._test_text_and_image_content_on_binary_off_non_streaming_impl(False, **kwargs) + + def _test_text_and_image_content_on_binary_on_non_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording ON and binary data ON (non-streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2718,38 +3312,73 @@ def test_text_and_image_content_on_binary_on_non_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary ON: should have text and image with full base64 data - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"text","content":"What is shown in this image?"}},{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"text","content":"What is shown in this image?"}},{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_on_binary_on_non_streaming_events(self, **kwargs): + """Test text + image with content recording ON and binary data ON (non-streaming, event-based messages).""" + self._test_text_and_image_content_on_binary_on_non_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_on_binary_on_non_streaming_attributes(self, **kwargs): + """Test text + image with content recording ON and binary data ON (non-streaming, attribute-based messages).""" + self._test_text_and_image_content_on_binary_on_non_streaming_impl(False, **kwargs) # ======================================== # Binary Data Tracing Tests - Streaming (Image Only) # ======================================== - @pytest.mark.usefixtures("instrument_without_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_off_binary_off_streaming(self, **kwargs): - """Test image only with content recording OFF and binary data OFF (streaming).""" + def _test_image_only_content_off_binary_off_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording OFF and binary data OFF (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2800,34 +3429,69 @@ def test_image_only_content_off_binary_off_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_off_binary_on_streaming(self, **kwargs): - """Test image only with content recording OFF and binary data ON (streaming).""" + def test_image_only_content_off_binary_off_streaming_events(self, **kwargs): + """Test image only with content recording OFF and binary data OFF (streaming, event-based messages).""" + self._test_image_only_content_off_binary_off_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_off_binary_off_streaming_attributes(self, **kwargs): + """Test image only with content recording OFF and binary data OFF (streaming, attribute-based messages).""" + self._test_image_only_content_off_binary_off_streaming_impl(False, **kwargs) + + def _test_image_only_content_off_binary_on_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording OFF and binary data ON (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -2877,34 +3541,69 @@ def test_image_only_content_off_binary_on_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True - @pytest.mark.usefixtures("instrument_with_content") + @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_on_binary_off_streaming(self, **kwargs): - """Test image only with content recording ON and binary data OFF (streaming).""" + def test_image_only_content_off_binary_on_streaming_events(self, **kwargs): + """Test image only with content recording OFF and binary data ON (streaming, event-based messages).""" + self._test_image_only_content_off_binary_on_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_off_binary_on_streaming_attributes(self, **kwargs): + """Test image only with content recording OFF and binary data ON (streaming, attribute-based messages).""" + self._test_image_only_content_off_binary_on_streaming_impl(False, **kwargs) + + def _test_image_only_content_on_binary_off_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording ON and binary data OFF (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2954,34 +3653,69 @@ def test_image_only_content_on_binary_off_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary OFF: should have image type but no image_url - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role":"user","parts":[{"type":"image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role":"user","parts":[{"type":"image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_image_only_content_on_binary_on_streaming(self, **kwargs): - """Test image only with content recording ON and binary data ON (streaming).""" + def test_image_only_content_on_binary_off_streaming_events(self, **kwargs): + """Test image only with content recording ON and binary data OFF (streaming, event-based messages).""" + self._test_image_only_content_on_binary_off_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_on_binary_off_streaming_attributes(self, **kwargs): + """Test image only with content recording ON and binary data OFF (streaming, attribute-based messages).""" + self._test_image_only_content_on_binary_off_streaming_impl(False, **kwargs) + + def _test_image_only_content_on_binary_on_streaming_impl(self, use_events, **kwargs): + """Implementation for testing image only with content recording ON and binary data ON (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -3031,38 +3765,73 @@ def test_image_only_content_on_binary_on_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary ON: should have image type AND image_url with base64 data - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_on_binary_on_streaming_events(self, **kwargs): + """Test image only with content recording ON and binary data ON (streaming, event-based messages).""" + self._test_image_only_content_on_binary_on_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_image_only_content_on_binary_on_streaming_attributes(self, **kwargs): + """Test image only with content recording ON and binary data ON (streaming, attribute-based messages).""" + self._test_image_only_content_on_binary_on_streaming_impl(False, **kwargs) # ======================================== # Binary Data Tracing Tests - Streaming (Text + Image) # ======================================== - @pytest.mark.usefixtures("instrument_without_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_off_binary_off_streaming(self, **kwargs): - """Test text + image with content recording OFF and binary data OFF (streaming).""" + def _test_text_and_image_content_off_binary_off_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording OFF and binary data OFF (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -3116,34 +3885,70 @@ def test_text_and_image_content_off_binary_off_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + # Content OFF + attribute mode: both input and output messages are captured + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_off_binary_on_streaming(self, **kwargs): - """Test text + image with content recording OFF and binary data ON (streaming).""" + def test_text_and_image_content_off_binary_off_streaming_events(self, **kwargs): + """Test text + image with content recording OFF and binary data OFF (streaming, event-based messages).""" + self._test_text_and_image_content_off_binary_off_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_off_binary_off_streaming_attributes(self, **kwargs): + """Test text + image with content recording OFF and binary data OFF (streaming, attribute-based messages).""" + self._test_text_and_image_content_off_binary_off_streaming_impl(False, **kwargs) + + def _test_text_and_image_content_off_binary_on_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording OFF and binary data ON (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -3197,34 +4002,70 @@ def test_text_and_image_content_off_binary_on_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + # Content OFF + attribute mode: both input and output messages are captured + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording OFF: event content should have role, parts with type only, and finish_reason - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True - @pytest.mark.usefixtures("instrument_with_content") + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_off_binary_on_streaming_events(self, **kwargs): + """Test text + image with content recording OFF and binary data ON (streaming, event-based messages).""" + self._test_text_and_image_content_off_binary_on_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_on_binary_off_streaming(self, **kwargs): - """Test text + image with content recording ON and binary data OFF (streaming).""" + def test_text_and_image_content_off_binary_on_streaming_attributes(self, **kwargs): + """Test text + image with content recording OFF and binary data ON (streaming, attribute-based messages).""" + self._test_text_and_image_content_off_binary_on_streaming_impl(False, **kwargs) + + def _test_text_and_image_content_on_binary_off_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording ON and binary data OFF (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -3278,34 +4119,69 @@ def test_text_and_image_content_on_binary_off_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary OFF: should have text and image type but no image_url - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role":"user","parts":[{"type":"text","content":"What is shown in this image?"},{"type":"image"}]}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role":"user","parts":[{"type":"text","content":"What is shown in this image?"},{"type":"image"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) - def test_text_and_image_content_on_binary_on_streaming(self, **kwargs): - """Test text + image with content recording ON and binary data ON (streaming).""" + def test_text_and_image_content_on_binary_off_streaming_events(self, **kwargs): + """Test text + image with content recording ON and binary data OFF (streaming, event-based messages).""" + self._test_text_and_image_content_on_binary_off_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_on_binary_off_streaming_attributes(self, **kwargs): + """Test text + image with content recording ON and binary data OFF (streaming, attribute-based messages).""" + self._test_text_and_image_content_on_binary_off_streaming_impl(False, **kwargs) + + def _test_text_and_image_content_on_binary_on_streaming_impl(self, use_events, **kwargs): + """Implementation for testing text + image with content recording ON and binary data ON (streaming).""" self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -3359,27 +4235,64 @@ def test_text_and_image_content_on_binary_on_streaming(self, **kwargs): assert len(spans) == 1 span = spans[0] + expected_attributes = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) + assert attributes_match == True + # Content recording ON, binary ON: should have text and image with full base64 data - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"text","content":"What is shown in this image?"}},{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"text","content":"What is shown in this image?"}},{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_on_binary_on_streaming_events(self, **kwargs): + """Test text + image with content recording ON and binary data ON (streaming, event-based messages).""" + self._test_text_and_image_content_on_binary_on_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.HTTPX) + def test_text_and_image_content_on_binary_on_streaming_attributes(self, **kwargs): + """Test text + image with content recording ON and binary data ON (streaming, attribute-based messages).""" + self._test_text_and_image_content_on_binary_on_streaming_impl(False, **kwargs) # ======================================== # responses.stream() Method Tests @@ -3423,41 +4336,21 @@ def test_responses_stream_method_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), ("gen_ai.response.id", ""), ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short haiku about testing"}]}]', - }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', - }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True - @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) @@ -3496,41 +4389,21 @@ def test_responses_stream_method_without_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), ("gen_ai.response.id", ""), ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events - should have events with role, parts with type, and finish_reason but no actual content - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', - }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', - }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True - @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.HTTPX) @@ -3620,63 +4493,23 @@ def test_responses_stream_method_with_tools_with_content_recording(self, **kwarg span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), ("gen_ai.response.id", ""), ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True - # Check events for first span - expected_events_1 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Boston?"}]}]', - }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', - }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True - # Validate second span (tool output + final response) span2 = spans[1] - expected_events_2 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "tool", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "65°F", "condition": "cloudy"}}}]}]', - }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', - }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) - assert events_match == True @pytest.mark.usefixtures("instrument_without_content") @servicePreparer() @@ -3770,51 +4603,45 @@ def test_responses_stream_method_with_tools_without_content_recording(self, **kw spans = self.exporter.get_spans_by_name(f"{SPAN_NAME_CHAT} {deployment_name}") assert len(spans) == 2 - # Validate first span - should have events with tool call structure but no details + # Validate first span - should have both attribute and events with tool call structure but no details span1 = spans[0] - expected_events_1 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', - }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', - }, - }, + + # In attribute mode (default for this test), check attributes include both input and output + expected_attributes_1 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True + attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) + assert attributes_match == True - # Validate second span - should include parts with tool output metadata (type, id) but no output field + # Validate second span - in attribute mode, check attributes include tool output span2 = spans[1] - expected_events_2 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "tool", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', - }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', - }, - }, + expected_attributes_2 = [ + ("az.namespace", "Microsoft.CognitiveServices"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), + ("gen_ai.request.model", deployment_name), + ("gen_ai.provider.name", RESPONSES_PROVIDER), + ("server.address", ""), + ("gen_ai.conversation.id", conversation.id), + ("gen_ai.response.model", deployment_name), + ("gen_ai.response.id", ""), + ("gen_ai.usage.input_tokens", "+"), + ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] - events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) - assert events_match == True + attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) + assert attributes_match == True # ======================================== # Workflow Agent Tracing Tests @@ -4516,16 +5343,18 @@ def test_prompt_agent_with_responses_non_streaming(self, **kwargs): span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), ("gen_ai.agent.id", agent.id), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), ("gen_ai.response.id", ""), ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True @@ -4593,16 +5422,18 @@ def test_prompt_agent_with_responses_streaming(self, **kwargs): span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), ("gen_ai.agent.id", agent.id), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), ("gen_ai.response.id", ""), ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), ] attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py index 171ac7cc53dc..be30ffd057bf 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_async.py @@ -8,7 +8,14 @@ import json import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_CHAT, SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_CHAT, + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_CHAT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.ai.projects.models import FunctionTool, PromptAgentDefinition from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier @@ -32,12 +39,14 @@ class TestResponsesInstrumentor(TestAiAgentsInstrumentorBase): """Tests for ResponsesInstrumentor with real endpoints (async).""" - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.HTTPX) - async def test_async_non_streaming_with_content_recording(self, **kwargs): - """Test asynchronous non-streaming responses with content recording enabled.""" + async def _test_async_non_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous non-streaming responses with content recording. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -79,9 +88,9 @@ async def test_async_non_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -89,37 +98,61 @@ async def test_async_non_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + # Check span events (only in events mode) + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async(RecordedTransport.HTTPX) - async def test_async_streaming_with_content_recording(self, **kwargs): - """Test asynchronous streaming responses with content recording enabled.""" + async def test_async_non_streaming_with_content_recording_events(self, **kwargs): + """Test asynchronous non-streaming responses with content recording enabled (event-based messages).""" + await self._test_async_non_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.HTTPX) + async def test_async_non_streaming_with_content_recording_attributes(self, **kwargs): + """Test asynchronous non-streaming responses with content recording enabled (attribute-based messages).""" + await self._test_async_non_streaming_with_content_recording_impl(False, **kwargs) + + async def _test_async_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous streaming responses with content recording. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -169,9 +202,9 @@ async def test_async_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -179,30 +212,52 @@ async def test_async_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + if not use_events: + expected_attributes.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes) assert attributes_match == True - # Check span events (should include assistant message for streaming) - expected_events = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + # Check span events (only in events mode) + if use_events: + expected_events = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short poem about AI"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span, expected_events) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span, expected_events) + assert events_match == True + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.HTTPX) + async def test_async_streaming_with_content_recording_events(self, **kwargs): + """Test asynchronous streaming responses with content recording enabled (event-based messages).""" + await self._test_async_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.HTTPX) + async def test_async_streaming_with_content_recording_attributes(self, **kwargs): + """Test asynchronous streaming responses with content recording enabled (attribute-based messages).""" + await self._test_async_streaming_with_content_recording_impl(False, **kwargs) @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @@ -244,7 +299,7 @@ async def test_async_conversations_create(self, **kwargs): expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), ("gen_ai.operation.name", "create_conversation"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -257,6 +312,7 @@ async def test_async_conversations_create(self, **kwargs): async def test_async_list_conversation_items_with_content_recording(self, **kwargs): """Test asynchronous list_conversation_items with content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -302,7 +358,7 @@ async def test_async_list_conversation_items_with_content_recording(self, **kwar expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), ("gen_ai.operation.name", "list_conversation_items"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ] @@ -314,7 +370,7 @@ async def test_async_list_conversation_items_with_content_recording(self, **kwar { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}]}]', }, @@ -322,7 +378,7 @@ async def test_async_list_conversation_items_with_content_recording(self, **kwar { "name": "gen_ai.conversation.item", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, "gen_ai.conversation.item.id": "*", "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Hello"}]}]', }, @@ -331,14 +387,16 @@ async def test_async_list_conversation_items_with_content_recording(self, **kwar events_match = GenAiTraceVerifier().check_span_events(span, expected_events) assert events_match == True - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_async_function_tool_with_content_recording_streaming(self, **kwargs): - """Test asynchronous function tool usage with content recording enabled (streaming).""" + async def _test_async_function_tool_with_content_recording_streaming_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous function tool usage with content recording (streaming). + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + """ from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -455,9 +513,9 @@ async def test_async_function_tool_with_content_recording_streaming(self, **kwar span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -465,38 +523,46 @@ async def test_async_function_tool_with_content_recording_streaming(self, **kwar ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True - # Check events for first span - user message and assistant tool call - expected_events_1 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Seattle?"}]}]', + # Check events for first span - user message and assistant tool call (only in events mode) + if use_events: + expected_events_1 = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Seattle?"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) + assert events_match == True # Validate second span (tool output + final response) span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -504,39 +570,64 @@ async def test_async_function_tool_with_content_recording_streaming(self, **kwar ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + if not use_events: + # Span2 has both input messages (tool output) and output messages (assistant response) + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) assert attributes_match == True - # Check events for second span - tool output and assistant response - expected_events_2 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "tool", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "72°F", "condition": "sunny"}}}]}]', + # Check events for second span - tool output and assistant response (only in events mode) + if use_events: + expected_events_2 = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "tool", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "72°F", "condition": "sunny"}}}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) + assert events_match == True - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_async_function_tool_without_content_recording_streaming(self, **kwargs): - """Test asynchronous function tool usage without content recording (streaming).""" + async def test_async_function_tool_with_content_recording_streaming_events(self, **kwargs): + """Test asynchronous function tool usage with content recording enabled (streaming, event-based messages).""" + await self._test_async_function_tool_with_content_recording_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_function_tool_with_content_recording_streaming_attributes(self, **kwargs): + """Test asynchronous function tool usage with content recording enabled (streaming, attribute-based messages).""" + await self._test_async_function_tool_with_content_recording_streaming_impl(False, **kwargs) + + async def _test_async_function_tool_without_content_recording_streaming_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous function tool usage without content recording (streaming). + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + """ from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -647,9 +738,9 @@ async def test_async_function_tool_without_content_recording_streaming(self, **k span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -657,38 +748,46 @@ async def test_async_function_tool_without_content_recording_streaming(self, **k ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) assert attributes_match == True - # Check events for first span - tool call ID included but no function details, role and finish_reason included - expected_events_1 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "user", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', + # Check events for first span - tool call ID included but no function details (only in events mode) + if use_events: + expected_events_1 = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "user", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span1, expected_events_1) + assert events_match == True # Validate second span (tool output + final response) - no content span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -696,30 +795,53 @@ async def test_async_function_tool_without_content_recording_streaming(self, **k ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + if not use_events: + # Span2 has both input messages (tool output) and output messages (assistant response) + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) attributes_match = GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) assert attributes_match == True - # Check events for second span - should include parts with tool output metadata (type, id) but no output field - expected_events_2 = [ - { - "name": "gen_ai.input.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "tool", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', + # Check events for second span - tool output metadata and response (only in events mode) + if use_events: + expected_events_2 = [ + { + "name": "gen_ai.input.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "tool", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', + }, }, - }, - { - "name": "gen_ai.output.messages", - "attributes": { - "gen_ai.provider.name": "azure.openai", - # "gen_ai.message.role": "assistant", # Commented out - now in event content - "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + { + "name": "gen_ai.output.messages", + "attributes": { + "gen_ai.provider.name": RESPONSES_PROVIDER, + # "gen_ai.message.role": "assistant", # Commented out - now in event content + "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', + }, }, - }, - ] - events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) - assert events_match == True + ] + events_match = GenAiTraceVerifier().check_span_events(span2, expected_events_2) + assert events_match == True + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_function_tool_without_content_recording_streaming_events(self, **kwargs): + """Test asynchronous function tool usage without content recording (streaming, event-based messages).""" + await self._test_async_function_tool_without_content_recording_streaming_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_function_tool_without_content_recording_streaming_attributes(self, **kwargs): + """Test asynchronous function tool usage without content recording (streaming, attribute-based messages).""" + await self._test_async_function_tool_without_content_recording_streaming_impl(False, **kwargs) @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @@ -727,6 +849,7 @@ async def test_async_function_tool_without_content_recording_streaming(self, **k async def test_async_multiple_text_inputs_with_content_recording_non_streaming(self, **kwargs): """Test asynchronous non-streaming responses with multiple text inputs and content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -774,9 +897,9 @@ async def test_async_multiple_text_inputs_with_content_recording_non_streaming(s # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -792,7 +915,7 @@ async def test_async_multiple_text_inputs_with_content_recording_non_streaming(s { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Hello"}]}]', }, @@ -800,7 +923,7 @@ async def test_async_multiple_text_inputs_with_content_recording_non_streaming(s { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a haiku about Python"}]}]', }, @@ -808,7 +931,7 @@ async def test_async_multiple_text_inputs_with_content_recording_non_streaming(s { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -823,6 +946,7 @@ async def test_async_multiple_text_inputs_with_content_recording_non_streaming(s async def test_async_multiple_text_inputs_with_content_recording_streaming(self, **kwargs): """Test asynchronous streaming responses with multiple text inputs and content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -878,9 +1002,9 @@ async def test_async_multiple_text_inputs_with_content_recording_streaming(self, # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -896,7 +1020,7 @@ async def test_async_multiple_text_inputs_with_content_recording_streaming(self, { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Hello"}]}]', }, @@ -904,7 +1028,7 @@ async def test_async_multiple_text_inputs_with_content_recording_streaming(self, { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a haiku about Python"}]}]', }, @@ -912,7 +1036,7 @@ async def test_async_multiple_text_inputs_with_content_recording_streaming(self, { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -927,6 +1051,7 @@ async def test_async_multiple_text_inputs_with_content_recording_streaming(self, async def test_async_multiple_text_inputs_without_content_recording_non_streaming(self, **kwargs): """Test asynchronous non-streaming responses with multiple text inputs and content recording disabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -974,9 +1099,9 @@ async def test_async_multiple_text_inputs_without_content_recording_non_streamin # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -992,7 +1117,7 @@ async def test_async_multiple_text_inputs_without_content_recording_non_streamin { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -1000,7 +1125,7 @@ async def test_async_multiple_text_inputs_without_content_recording_non_streamin { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -1008,7 +1133,7 @@ async def test_async_multiple_text_inputs_without_content_recording_non_streamin { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1075,7 +1200,7 @@ async def test_async_image_only_content_off_binary_off_non_streaming(self, **kwa { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', }, @@ -1083,7 +1208,7 @@ async def test_async_image_only_content_off_binary_off_non_streaming(self, **kwa { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1145,7 +1270,7 @@ async def test_async_image_only_content_off_binary_on_non_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', }, @@ -1153,7 +1278,7 @@ async def test_async_image_only_content_off_binary_on_non_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1215,7 +1340,7 @@ async def test_async_image_only_content_on_binary_off_non_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role":"user","parts":[{"type":"image"}]}]', }, @@ -1223,7 +1348,7 @@ async def test_async_image_only_content_on_binary_off_non_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1285,7 +1410,7 @@ async def test_async_image_only_content_on_binary_on_non_streaming(self, **kwarg { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', }, @@ -1293,7 +1418,7 @@ async def test_async_image_only_content_on_binary_on_non_streaming(self, **kwarg { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1364,7 +1489,7 @@ async def test_async_text_and_image_content_off_binary_off_non_streaming(self, * { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', }, @@ -1372,7 +1497,7 @@ async def test_async_text_and_image_content_off_binary_off_non_streaming(self, * { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1438,7 +1563,7 @@ async def test_async_text_and_image_content_off_binary_on_non_streaming(self, ** { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', }, @@ -1446,7 +1571,7 @@ async def test_async_text_and_image_content_off_binary_on_non_streaming(self, ** { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1512,7 +1637,7 @@ async def test_async_text_and_image_content_on_binary_off_non_streaming(self, ** { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role":"user","parts":[{"type":"text","content":"What is shown in this image?"},{"type":"image"}]}]', }, @@ -1520,7 +1645,7 @@ async def test_async_text_and_image_content_on_binary_off_non_streaming(self, ** { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1586,7 +1711,7 @@ async def test_async_text_and_image_content_on_binary_on_non_streaming(self, **k { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"text","content":"What is shown in this image?"}},{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', }, @@ -1594,7 +1719,7 @@ async def test_async_text_and_image_content_on_binary_on_non_streaming(self, **k { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1669,7 +1794,7 @@ async def test_async_image_only_content_off_binary_off_streaming(self, **kwargs) { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', }, @@ -1677,7 +1802,7 @@ async def test_async_image_only_content_off_binary_off_streaming(self, **kwargs) { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1747,7 +1872,7 @@ async def test_async_image_only_content_off_binary_on_streaming(self, **kwargs): { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "image"}]}]', }, @@ -1755,7 +1880,7 @@ async def test_async_image_only_content_off_binary_on_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -1825,7 +1950,7 @@ async def test_async_image_only_content_on_binary_off_streaming(self, **kwargs): { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role":"user","parts":[{"type":"image"}]}]', }, @@ -1833,7 +1958,7 @@ async def test_async_image_only_content_on_binary_off_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1903,7 +2028,7 @@ async def test_async_image_only_content_on_binary_on_streaming(self, **kwargs): { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', }, @@ -1911,7 +2036,7 @@ async def test_async_image_only_content_on_binary_on_streaming(self, **kwargs): { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -1989,7 +2114,7 @@ async def test_async_text_and_image_content_off_binary_off_streaming(self, **kwa { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', }, @@ -1997,7 +2122,7 @@ async def test_async_text_and_image_content_off_binary_off_streaming(self, **kwa { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -2071,7 +2196,7 @@ async def test_async_text_and_image_content_off_binary_on_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}, {"type": "image"}]}]', }, @@ -2079,7 +2204,7 @@ async def test_async_text_and_image_content_off_binary_on_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -2153,7 +2278,7 @@ async def test_async_text_and_image_content_on_binary_off_streaming(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role":"user","parts":[{"type":"text","content":"What is shown in this image?"},{"type":"image"}]}]', }, @@ -2161,7 +2286,7 @@ async def test_async_text_and_image_content_on_binary_off_streaming(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -2235,7 +2360,7 @@ async def test_async_text_and_image_content_on_binary_on_streaming(self, **kwarg { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": f'[{{"role":"user","parts":[{{"type":"text","content":"What is shown in this image?"}},{{"type":"image","content":"data:image/png;base64,{TEST_IMAGE_BASE64}"}}]}}]', }, @@ -2243,7 +2368,7 @@ async def test_async_text_and_image_content_on_binary_on_streaming(self, **kwarg { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -2313,9 +2438,9 @@ async def test_async_multiple_text_inputs_without_content_recording_streaming(se # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -2331,7 +2456,7 @@ async def test_async_multiple_text_inputs_without_content_recording_streaming(se { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2339,7 +2464,7 @@ async def test_async_multiple_text_inputs_without_content_recording_streaming(se { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2347,7 +2472,7 @@ async def test_async_multiple_text_inputs_without_content_recording_streaming(se { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -2366,6 +2491,7 @@ async def test_async_multiple_text_inputs_without_content_recording_streaming(se async def test_async_responses_stream_method_with_content_recording(self, **kwargs): """Test async responses.stream() method with content recording enabled.""" self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2405,9 +2531,9 @@ async def test_async_responses_stream_method_with_content_recording(self, **kwar # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -2423,7 +2549,7 @@ async def test_async_responses_stream_method_with_content_recording(self, **kwar { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "Write a short haiku about testing"}]}]', }, @@ -2431,7 +2557,7 @@ async def test_async_responses_stream_method_with_content_recording(self, **kwar { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -2485,9 +2611,9 @@ async def test_async_responses_stream_method_without_content_recording(self, **k # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -2503,7 +2629,7 @@ async def test_async_responses_stream_method_without_content_recording(self, **k { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2511,7 +2637,7 @@ async def test_async_responses_stream_method_without_content_recording(self, **k { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -2528,6 +2654,7 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s from openai.types.responses.response_input_param import FunctionCallOutput self.cleanup() + _set_use_message_events(True) # Use event-based mode for this test os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -2616,9 +2743,9 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_CHAT), ("gen_ai.request.model", deployment_name), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -2634,7 +2761,7 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Boston?"}]}]', }, @@ -2642,7 +2769,7 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*", "function": {"name": "get_weather", "arguments": "*"}}}]}]', }, @@ -2657,7 +2784,7 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "tool", # Commented out - now in event content "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*", "output": {"temperature": "65°F", "condition": "cloudy"}}}]}]', }, @@ -2665,7 +2792,7 @@ async def test_async_responses_stream_method_with_tools_with_content_recording(s { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text", "content": "*"}], "finish_reason": "*"}]', }, @@ -2772,7 +2899,7 @@ async def test_async_responses_stream_method_with_tools_without_content_recordin { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "user", # Commented out - now in event content "gen_ai.event.content": '[{"role": "user", "parts": [{"type": "text"}]}]', }, @@ -2780,7 +2907,7 @@ async def test_async_responses_stream_method_with_tools_without_content_recordin { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "tool_call", "content": {"type": "function_call", "id": "*"}}]}]', }, @@ -2795,7 +2922,7 @@ async def test_async_responses_stream_method_with_tools_without_content_recordin { "name": "gen_ai.input.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "tool", # Commented out - now in event content "gen_ai.event.content": '[{"role": "tool", "parts": [{"type": "tool_call_output", "content": {"type": "function_call_output", "id": "*"}}]}]', }, @@ -2803,7 +2930,7 @@ async def test_async_responses_stream_method_with_tools_without_content_recordin { "name": "gen_ai.output.messages", "attributes": { - "gen_ai.provider.name": "azure.openai", + "gen_ai.provider.name": RESPONSES_PROVIDER, # "gen_ai.message.role": "assistant", # Commented out - now in event content "gen_ai.event.content": '[{"role": "assistant", "parts": [{"type": "text"}], "finish_reason": "*"}]', }, @@ -3361,10 +3488,10 @@ async def test_async_prompt_agent_with_responses_non_streaming(self, **kwargs): span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), ("gen_ai.agent.id", agent.id), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), @@ -3440,10 +3567,10 @@ async def test_async_prompt_agent_with_responses_streaming(self, **kwargs): span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), ("gen_ai.agent.name", agent.name), ("gen_ai.agent.id", agent.id), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.response.model", deployment_name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py index 5dbcb4566c87..323a43dd0c6f 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation.py @@ -9,7 +9,12 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -38,6 +43,7 @@ class TestResponsesInstrumentorBrowserAutomation(TestAiAgentsInstrumentorBase): def test_sync_browser_automation_non_streaming_with_content_recording(self, **kwargs): """Test synchronous browser automation agent with non-streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -105,8 +111,8 @@ def test_sync_browser_automation_non_streaming_with_content_recording(self, **kw expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -173,6 +179,7 @@ def test_sync_browser_automation_non_streaming_with_content_recording(self, **kw def test_sync_browser_automation_non_streaming_without_content_recording(self, **kwargs): """Test synchronous browser automation agent with non-streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -236,8 +243,8 @@ def test_sync_browser_automation_non_streaming_without_content_recording(self, * expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -302,6 +309,7 @@ def test_sync_browser_automation_non_streaming_without_content_recording(self, * def test_sync_browser_automation_streaming_with_content_recording(self, **kwargs): """Test synchronous browser automation agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( {CONTENT_TRACING_ENV_VARIABLE: "True", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} ) @@ -365,8 +373,8 @@ def test_sync_browser_automation_streaming_with_content_recording(self, **kwargs expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -429,6 +437,7 @@ def test_sync_browser_automation_streaming_with_content_recording(self, **kwargs def test_sync_browser_automation_streaming_without_content_recording(self, **kwargs): """Test synchronous browser automation agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( {CONTENT_TRACING_ENV_VARIABLE: "False", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} ) @@ -490,8 +499,8 @@ def test_sync_browser_automation_streaming_without_content_recording(self, **kwa expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py index 0631495ff0b2..87b89d8343f6 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_browser_automation_async.py @@ -9,7 +9,12 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -41,6 +46,7 @@ class TestResponsesInstrumentorBrowserAutomationAsync(TestAiAgentsInstrumentorBa async def test_async_browser_automation_non_streaming_with_content_recording(self, **kwargs): """Test asynchronous browser automation agent with non-streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -108,8 +114,8 @@ async def test_async_browser_automation_non_streaming_with_content_recording(sel expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -172,6 +178,7 @@ async def test_async_browser_automation_non_streaming_with_content_recording(sel async def test_async_browser_automation_non_streaming_without_content_recording(self, **kwargs): """Test asynchronous browser automation agent with non-streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -235,8 +242,8 @@ async def test_async_browser_automation_non_streaming_without_content_recording( expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -297,6 +304,7 @@ async def test_async_browser_automation_non_streaming_without_content_recording( async def test_async_browser_automation_streaming_with_content_recording(self, **kwargs): """Test asynchronous browser automation agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( {CONTENT_TRACING_ENV_VARIABLE: "True", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} ) @@ -360,8 +368,8 @@ async def test_async_browser_automation_streaming_with_content_recording(self, * expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -421,6 +429,7 @@ async def test_async_browser_automation_streaming_with_content_recording(self, * async def test_async_browser_automation_streaming_without_content_recording(self, **kwargs): """Test asynchronous browser automation agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( {CONTENT_TRACING_ENV_VARIABLE: "False", "AZURE_TRACING_GEN_AI_INSTRUMENT_RESPONSES_API": "True"} ) @@ -482,8 +491,8 @@ async def test_async_browser_automation_streaming_without_content_recording(self expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py index 13b0d8342186..df073393af8c 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter.py @@ -10,7 +10,12 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -48,6 +53,7 @@ class TestResponsesInstrumentorCodeInterpreter(TestAiAgentsInstrumentorBase): def test_sync_code_interpreter_non_streaming_with_content_recording(self, **kwargs): """Test synchronous Code Interpreter agent with content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -118,8 +124,8 @@ def test_sync_code_interpreter_non_streaming_with_content_recording(self, **kwar expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -235,6 +241,7 @@ def test_sync_code_interpreter_non_streaming_with_content_recording(self, **kwar def test_sync_code_interpreter_non_streaming_without_content_recording(self, **kwargs): """Test synchronous Code Interpreter agent with content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -304,8 +311,8 @@ def test_sync_code_interpreter_non_streaming_without_content_recording(self, **k expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -425,6 +432,7 @@ def test_sync_code_interpreter_non_streaming_without_content_recording(self, **k def test_sync_code_interpreter_streaming_with_content_recording(self, **kwargs): """Test synchronous Code Interpreter agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -499,8 +507,8 @@ def test_sync_code_interpreter_streaming_with_content_recording(self, **kwargs): expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -615,6 +623,7 @@ def test_sync_code_interpreter_streaming_with_content_recording(self, **kwargs): def test_sync_code_interpreter_streaming_without_content_recording(self, **kwargs): """Test synchronous Code Interpreter agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -689,8 +698,8 @@ def test_sync_code_interpreter_streaming_without_content_recording(self, **kwarg expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py index 5f2eb03e3fbe..850a2eb6e542 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_code_interpreter_async.py @@ -10,7 +10,12 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -49,6 +54,7 @@ class TestResponsesInstrumentorCodeInterpreterAsync(TestAiAgentsInstrumentorBase async def test_async_code_interpreter_non_streaming_with_content_recording(self, **kwargs): """Test asynchronous Code Interpreter agent with content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -118,8 +124,8 @@ async def test_async_code_interpreter_non_streaming_with_content_recording(self, expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -235,6 +241,7 @@ async def test_async_code_interpreter_non_streaming_with_content_recording(self, async def test_async_code_interpreter_non_streaming_without_content_recording(self, **kwargs): """Test asynchronous Code Interpreter agent with content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -304,8 +311,8 @@ async def test_async_code_interpreter_non_streaming_without_content_recording(se expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -425,6 +432,7 @@ async def test_async_code_interpreter_non_streaming_without_content_recording(se async def test_async_code_interpreter_streaming_with_content_recording(self, **kwargs): """Test asynchronous Code Interpreter agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -499,8 +507,8 @@ async def test_async_code_interpreter_streaming_with_content_recording(self, **k expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -615,6 +623,7 @@ async def test_async_code_interpreter_streaming_with_content_recording(self, **k async def test_async_code_interpreter_streaming_without_content_recording(self, **kwargs): """Test asynchronous Code Interpreter agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -689,8 +698,8 @@ async def test_async_code_interpreter_streaming_without_content_recording(self, expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py index 92902d6fa908..773f7c60614f 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search.py @@ -10,7 +10,12 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -35,6 +40,7 @@ class TestResponsesInstrumentorFileSearch(TestAiAgentsInstrumentorBase): def test_sync_file_search_non_streaming_with_content_recording(self, **kwargs): """Test synchronous File Search agent with non-streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -118,8 +124,8 @@ def test_sync_file_search_non_streaming_with_content_recording(self, **kwargs): span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -243,6 +249,7 @@ def test_sync_file_search_non_streaming_with_content_recording(self, **kwargs): def test_sync_file_search_non_streaming_without_content_recording(self, **kwargs): """Test synchronous File Search agent with non-streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -326,8 +333,8 @@ def test_sync_file_search_non_streaming_without_content_recording(self, **kwargs span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -449,6 +456,7 @@ def test_sync_file_search_non_streaming_without_content_recording(self, **kwargs def test_sync_file_search_streaming_with_content_recording(self, **kwargs): """Test synchronous File Search agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -538,8 +546,8 @@ def test_sync_file_search_streaming_with_content_recording(self, **kwargs): expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -653,6 +661,7 @@ def test_sync_file_search_streaming_with_content_recording(self, **kwargs): def test_sync_file_search_streaming_without_content_recording(self, **kwargs): """Test synchronous File Search agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -742,8 +751,8 @@ def test_sync_file_search_streaming_without_content_recording(self, **kwargs): expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py index f215ee1072f2..4e3e94308413 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_file_search_async.py @@ -10,7 +10,12 @@ import pytest from io import BytesIO from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -36,6 +41,7 @@ class TestResponsesInstrumentorFileSearchAsync(TestAiAgentsInstrumentorBase): async def test_async_file_search_non_streaming_with_content_recording(self, **kwargs): """Test asynchronous File Search agent with non-streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -119,8 +125,8 @@ async def test_async_file_search_non_streaming_with_content_recording(self, **kw span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -244,6 +250,7 @@ async def test_async_file_search_non_streaming_with_content_recording(self, **kw async def test_async_file_search_non_streaming_without_content_recording(self, **kwargs): """Test asynchronous File Search agent with non-streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -327,8 +334,8 @@ async def test_async_file_search_non_streaming_without_content_recording(self, * span = spans[0] expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -450,6 +457,7 @@ async def test_async_file_search_non_streaming_without_content_recording(self, * async def test_async_file_search_streaming_with_content_recording(self, **kwargs): """Test asynchronous File Search agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -539,8 +547,8 @@ async def test_async_file_search_streaming_with_content_recording(self, **kwargs expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -654,6 +662,7 @@ async def test_async_file_search_streaming_with_content_recording(self, **kwargs async def test_async_file_search_streaming_without_content_recording(self, **kwargs): """Test asynchronous File Search agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -743,8 +752,8 @@ async def test_async_file_search_streaming_without_content_recording(self, **kwa expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py index 9152d4b244f2..a0640b93e62d 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp.py @@ -9,7 +9,12 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -33,12 +38,15 @@ class TestResponsesInstrumentorMCP(TestAiAgentsInstrumentorBase): # Sync MCP Agent Tests - Non-Streaming # ======================================== - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): - """Test synchronous MCP agent with non-streaming and content recording enabled.""" + def _test_sync_mcp_non_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous MCP agent with non-streaming and content recording enabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -120,8 +128,8 @@ def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -130,75 +138,87 @@ def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation for first span - verify content IS present + # Only validate events when use_events is True from collections.abc import Mapping - for event in span1.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - # Validate content fields ARE present - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - and isinstance(part["content"], str) - and part["content"].strip() != "" - ), "Text content should be present when content recording is enabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - first = data[0] - assert first.get("role") in ("assistant", "tool") - parts = first.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - # Check for MCP-specific content - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - assert isinstance(tool_content, dict) - tool_type = tool_content.get("type") - if tool_type in ("mcp_list_tools", "mcp_approval_request"): - assert "id" in tool_content - if tool_type == "mcp_list_tools": - assert ( - "server_label" in tool_content - ), "server_label should be present for mcp_list_tools when content recording is enabled" - elif tool_type == "mcp_approval_request": - assert ( - "name" in tool_content - ), "name should be present for mcp_approval_request when content recording is enabled" - assert ( - "server_label" in tool_content - ), "server_label should be present for mcp_approval_request when content recording is enabled" - assert ( - "arguments" in tool_content - ), "arguments should be present for mcp_approval_request when content recording is enabled" + if use_events: + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields ARE present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_list_tools when content recording is enabled" + elif tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" # Validate second response span (approval response) span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -207,113 +227,126 @@ def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate MCP approval response and call in second span - for event in span2.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Check for MCP approval response content - for entry in data: - if entry.get("role") == "user": + # Only validate events when use_events is True + if use_events: + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content + for entry in data: parts = entry.get("parts") - for part in parts: - if part.get("type") == "mcp": - mcp_content = part.get("content") - assert isinstance(mcp_content, dict) - if mcp_content.get("type") == "mcp_approval_response": - assert "id" in mcp_content - assert ( - "approval_request_id" in mcp_content - ), "approval_request_id should be present when content recording is enabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Check for MCP call content - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content and tool_content.get("type") == "mcp_call": - assert "id" in tool_content - assert ( - "name" in tool_content - ), "name should be present for mcp_call when content recording is enabled" - assert ( - "arguments" in tool_content - ), "arguments should be present for mcp_call when content recording is enabled" + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": assert ( - "server_label" in tool_content - ), "server_label should be present for mcp_call when content recording is enabled" - elif part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present when content recording is enabled" + "content" in part + ), "text content should be present when content recording is enabled" # Check list_conversation_items span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) == 1, "Should have one list_conversation_items span" list_span = list_spans[0] - for event in list_span.events: - if event.name == "gen_ai.conversation.item": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Validate MCP content in conversation items - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present in conversation items when content recording is enabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content and mcp_content.get("type") == "mcp_approval_response": + if use_events: + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": assert ( - "approval_request_id" in mcp_content - ), "approval_request_id should be present when content recording is enabled" - elif entry.get("role") == "assistant": - parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present in conversation items when content recording is enabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content: - mcp_type = mcp_content.get("type") - if mcp_type in ("mcp_list_tools", "mcp_call", "mcp_approval_request"): - assert "id" in mcp_content - if mcp_type == "mcp_call": - assert ( - "name" in mcp_content - ), "name should be present for mcp_call in conversation items" - assert ( - "server_label" in mcp_content - ), "server_label should be present for mcp_call in conversation items" - else: - assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type in ("mcp_list_tools", "mcp_call", "mcp_approval_request"): + assert "id" in mcp_content + if mcp_type == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items" + assert ( + "server_label" in mcp_content + ), "server_label should be present for mcp_call in conversation items" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" # Cleanup openai_client.conversations.delete(conversation_id=conversation.id) @@ -321,12 +354,29 @@ def test_sync_mcp_non_streaming_with_content_recording(self, **kwargs): finally: project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_non_streaming_with_content_recording_events(self, **kwargs): + """Test synchronous MCP agent with non-streaming and content recording enabled (event-based messages).""" + self._test_sync_mcp_non_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): - """Test synchronous MCP agent with non-streaming and content recording disabled.""" + def test_sync_mcp_non_streaming_with_content_recording_attributes(self, **kwargs): + """Test synchronous MCP agent with non-streaming and content recording enabled (attribute-based messages).""" + self._test_sync_mcp_non_streaming_with_content_recording_impl(False, **kwargs) + + def _test_sync_mcp_non_streaming_without_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous MCP agent with non-streaming and content recording disabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -408,8 +458,8 @@ def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -418,70 +468,82 @@ def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation for first span - verify content is NOT present + # Only validate events when use_events is True from collections.abc import Mapping - for event in span1.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - # Validate content fields are NOT present - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - for part in parts: - if part.get("type") == "text": - assert ( - "content" not in part - ), "Text content should NOT be present when content recording is disabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - first = data[0] - assert first.get("role") in ("assistant", "tool") - parts = first.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - # Check for MCP-specific content - should have type and id but not detailed fields - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - assert isinstance(tool_content, dict) - tool_type = tool_content.get("type") - if tool_type in ("mcp_list_tools", "mcp_approval_request"): - assert "id" in tool_content - if tool_type == "mcp_list_tools": - # server_label might be present but other details should not - pass - elif tool_type == "mcp_approval_request": - # Should not have name, arguments when content recording is disabled - assert ( - "name" not in tool_content - ), "name should NOT be present for mcp_approval_request when content recording is disabled" - assert ( - "arguments" not in tool_content - ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + if use_events: + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields are NOT present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content - should have type and id but not detailed fields + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + # server_label might be present but other details should not + pass + elif tool_type == "mcp_approval_request": + # Should not have name, arguments when content recording is disabled + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" # Validate second response span (approval response) span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -490,6 +552,16 @@ def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate MCP approval response and call in second span - content should be minimal @@ -595,16 +667,33 @@ def test_sync_mcp_non_streaming_without_content_recording(self, **kwargs): finally: project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_non_streaming_without_content_recording_events(self, **kwargs): + """Test synchronous MCP agent with non-streaming and content recording disabled (event-based messages).""" + self._test_sync_mcp_non_streaming_without_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_non_streaming_without_content_recording_attributes(self, **kwargs): + """Test synchronous MCP agent with non-streaming and content recording disabled (attribute-based messages).""" + self._test_sync_mcp_non_streaming_without_content_recording_impl(False, **kwargs) + # ======================================== # Sync MCP Agent Tests - Streaming # ======================================== - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_mcp_streaming_with_content_recording(self, **kwargs): - """Test synchronous MCP agent with streaming and content recording enabled.""" + def _test_sync_mcp_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous MCP agent with streaming and content recording enabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -695,8 +784,8 @@ def test_sync_mcp_streaming_with_content_recording(self, **kwargs): expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -705,6 +794,16 @@ def test_sync_mcp_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation - verify content IS present @@ -761,8 +860,8 @@ def test_sync_mcp_streaming_with_content_recording(self, **kwargs): expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -771,6 +870,16 @@ def test_sync_mcp_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate second span events @@ -838,12 +947,29 @@ def test_sync_mcp_streaming_with_content_recording(self, **kwargs): finally: project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sync_mcp_streaming_without_content_recording(self, **kwargs): - """Test synchronous MCP agent with streaming and content recording disabled.""" + def test_sync_mcp_streaming_with_content_recording_events(self, **kwargs): + """Test synchronous MCP agent with streaming and content recording enabled (event-based messages).""" + self._test_sync_mcp_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_streaming_with_content_recording_attributes(self, **kwargs): + """Test synchronous MCP agent with streaming and content recording enabled (attribute-based messages).""" + self._test_sync_mcp_streaming_with_content_recording_impl(False, **kwargs) + + def _test_sync_mcp_streaming_without_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing synchronous MCP agent with streaming and content recording disabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -934,8 +1060,8 @@ def test_sync_mcp_streaming_without_content_recording(self, **kwargs): expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -944,6 +1070,16 @@ def test_sync_mcp_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation - verify content is NOT present @@ -998,8 +1134,8 @@ def test_sync_mcp_streaming_without_content_recording(self, **kwargs): expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -1008,6 +1144,16 @@ def test_sync_mcp_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate second span events - content should be minimal @@ -1074,3 +1220,17 @@ def test_sync_mcp_streaming_without_content_recording(self, **kwargs): finally: project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_streaming_without_content_recording_events(self, **kwargs): + """Test synchronous MCP agent with streaming and content recording disabled (event-based messages).""" + self._test_sync_mcp_streaming_without_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_sync_mcp_streaming_without_content_recording_attributes(self, **kwargs): + """Test synchronous MCP agent with streaming and content recording disabled (attribute-based messages).""" + self._test_sync_mcp_streaming_without_content_recording_impl(False, **kwargs) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py index c0fd327890da..d0d4fb384984 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_mcp_async.py @@ -9,7 +9,12 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -34,12 +39,15 @@ class TestResponsesInstrumentorMCPAsync(TestAiAgentsInstrumentorBase): # Async MCP Agent Tests - Non-Streaming # ======================================== - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): - """Test asynchronous MCP agent with non-streaming and content recording enabled.""" + async def _test_async_mcp_non_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous MCP agent with non-streaming and content recording enabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -121,8 +129,8 @@ async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -131,75 +139,86 @@ async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation for first span - verify content IS present from collections.abc import Mapping - for event in span1.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - # Validate content fields ARE present - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - and isinstance(part["content"], str) - and part["content"].strip() != "" - ), "Text content should be present when content recording is enabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - first = data[0] - assert first.get("role") in ("assistant", "tool") - parts = first.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - # Check for MCP-specific content - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - assert isinstance(tool_content, dict) - tool_type = tool_content.get("type") - if tool_type in ("mcp_list_tools", "mcp_approval_request"): - assert "id" in tool_content - if tool_type == "mcp_list_tools": - assert ( - "server_label" in tool_content - ), "server_label should be present for mcp_list_tools when content recording is enabled" - elif tool_type == "mcp_approval_request": - assert ( - "name" in tool_content - ), "name should be present for mcp_approval_request when content recording is enabled" - assert ( - "server_label" in tool_content - ), "server_label should be present for mcp_approval_request when content recording is enabled" - assert ( - "arguments" in tool_content - ), "arguments should be present for mcp_approval_request when content recording is enabled" + if use_events: + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields ARE present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_list_tools when content recording is enabled" + elif tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" # Validate second response span (approval response) span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -208,113 +227,126 @@ async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate MCP approval response and call in second span - for event in span2.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Check for MCP approval response content - for entry in data: - if entry.get("role") == "user": + # Only validate events when use_events is True + if use_events: + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content + for entry in data: parts = entry.get("parts") - for part in parts: - if part.get("type") == "mcp": - mcp_content = part.get("content") - assert isinstance(mcp_content, dict) - if mcp_content.get("type") == "mcp_approval_response": - assert "id" in mcp_content - assert ( - "approval_request_id" in mcp_content - ), "approval_request_id should be present when content recording is enabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Check for MCP call content - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content and tool_content.get("type") == "mcp_call": - assert "id" in tool_content - assert ( - "name" in tool_content - ), "name should be present for mcp_call when content recording is enabled" - assert ( - "arguments" in tool_content - ), "arguments should be present for mcp_call when content recording is enabled" + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + assert ( + "server_label" in tool_content + ), "server_label should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": assert ( - "server_label" in tool_content - ), "server_label should be present for mcp_call when content recording is enabled" - elif part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present when content recording is enabled" + "content" in part + ), "text content should be present when content recording is enabled" # Check list_conversation_items span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) == 1, "Should have one list_conversation_items span" list_span = list_spans[0] - for event in list_span.events: - if event.name == "gen_ai.conversation.item": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Validate MCP content in conversation items - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present in conversation items when content recording is enabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content and mcp_content.get("type") == "mcp_approval_response": + if use_events: + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": assert ( - "approval_request_id" in mcp_content - ), "approval_request_id should be present when content recording is enabled" - elif entry.get("role") == "assistant": - parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present in conversation items when content recording is enabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content: - mcp_type = mcp_content.get("type") - if mcp_type in ("mcp_list_tools", "mcp_call", "mcp_approval_request"): - assert "id" in mcp_content - if mcp_type == "mcp_call": - assert ( - "name" in mcp_content - ), "name should be present for mcp_call in conversation items" - assert ( - "server_label" in mcp_content - ), "server_label should be present for mcp_call in conversation items" - else: - assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + assert ( + "approval_request_id" in mcp_content + ), "approval_request_id should be present when content recording is enabled" + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type in ("mcp_list_tools", "mcp_call", "mcp_approval_request"): + assert "id" in mcp_content + if mcp_type == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items" + assert ( + "server_label" in mcp_content + ), "server_label should be present for mcp_call in conversation items" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" # Cleanup await openai_client.conversations.delete(conversation_id=conversation.id) @@ -322,12 +354,29 @@ async def test_async_mcp_non_streaming_with_content_recording(self, **kwargs): finally: await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs): - """Test asynchronous MCP agent with non-streaming and content recording disabled.""" + async def test_async_mcp_non_streaming_with_content_recording_events(self, **kwargs): + """Test asynchronous MCP agent with non-streaming and content recording enabled (event-based messages).""" + await self._test_async_mcp_non_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_non_streaming_with_content_recording_attributes(self, **kwargs): + """Test asynchronous MCP agent with non-streaming and content recording enabled (attribute-based messages).""" + await self._test_async_mcp_non_streaming_with_content_recording_impl(False, **kwargs) + + async def _test_async_mcp_non_streaming_without_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous MCP agent with non-streaming and content recording disabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -409,8 +458,8 @@ async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs) span1 = spans[0] expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -419,70 +468,81 @@ async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs) ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation for first span - verify content is NOT present from collections.abc import Mapping - for event in span1.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - # Validate content fields are NOT present - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - for part in parts: - if part.get("type") == "text": - assert ( - "content" not in part - ), "Text content should NOT be present when content recording is disabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - assert isinstance(data, list) and len(data) > 0 - first = data[0] - assert first.get("role") in ("assistant", "tool") - parts = first.get("parts") - assert isinstance(parts, list) and len(parts) > 0 - # Check for MCP-specific content - should have type and id but not detailed fields - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - assert isinstance(tool_content, dict) - tool_type = tool_content.get("type") - if tool_type in ("mcp_list_tools", "mcp_approval_request"): - assert "id" in tool_content - if tool_type == "mcp_list_tools": - # server_label might be present but other details should not - pass - elif tool_type == "mcp_approval_request": - # Should not have name, arguments when content recording is disabled - assert ( - "name" not in tool_content - ), "name should NOT be present for mcp_approval_request when content recording is disabled" - assert ( - "arguments" not in tool_content - ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + if use_events: + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + # Validate content fields are NOT present + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + assert isinstance(data, list) and len(data) > 0 + first = data[0] + assert first.get("role") in ("assistant", "tool") + parts = first.get("parts") + assert isinstance(parts, list) and len(parts) > 0 + # Check for MCP-specific content - should have type and id but not detailed fields + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + assert isinstance(tool_content, dict) + tool_type = tool_content.get("type") + if tool_type in ("mcp_list_tools", "mcp_approval_request"): + assert "id" in tool_content + if tool_type == "mcp_list_tools": + # server_label might be present but other details should not + pass + elif tool_type == "mcp_approval_request": + # Should not have name, arguments when content recording is disabled + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" # Validate second response span (approval response) span2 = spans[1] expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -491,104 +551,117 @@ async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs) ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate MCP approval response and call in second span - content should be minimal - for event in span2.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Check for MCP approval response content - should be minimal - for entry in data: - if entry.get("role") == "user": + # Only validate events when use_events is True + if use_events: + for event in span2.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP approval response content - should be minimal + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "mcp": + mcp_content = part.get("content") + assert isinstance(mcp_content, dict) + if mcp_content.get("type") == "mcp_approval_response": + assert "id" in mcp_content + # approval_request_id might not be present when content recording is disabled + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Check for MCP call content - should be minimal + for entry in data: parts = entry.get("parts") - for part in parts: - if part.get("type") == "mcp": - mcp_content = part.get("content") - assert isinstance(mcp_content, dict) - if mcp_content.get("type") == "mcp_approval_response": - assert "id" in mcp_content - # approval_request_id might not be present when content recording is disabled - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Check for MCP call content - should be minimal - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content and tool_content.get("type") == "mcp_call": - assert "id" in tool_content - assert ( - "name" not in tool_content - ), "name should NOT be present for mcp_call when content recording is disabled" + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert "id" in tool_content + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_call when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_call when content recording is disabled" + elif part.get("type") == "text": assert ( - "arguments" not in tool_content - ), "arguments should NOT be present for mcp_call when content recording is disabled" - elif part.get("type") == "text": - assert ( - "content" not in part - ), "text content should NOT be present when content recording is disabled" + "content" not in part + ), "text content should NOT be present when content recording is disabled" # Check list_conversation_items span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) == 1, "Should have one list_conversation_items span" list_span = list_spans[0] - for event in list_span.events: - if event.name == "gen_ai.conversation.item": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - # Validate MCP content in conversation items - should be minimal - for entry in data: - if entry.get("role") == "user": - parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" not in part - ), "text content should NOT be present in conversation items when content recording is disabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content and mcp_content.get("type") == "mcp_approval_response": - # Should have id but might not have other details - assert "id" in mcp_content - elif entry.get("role") == "assistant": - parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" not in part - ), "text content should NOT be present in conversation items when content recording is disabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content: - mcp_type = mcp_content.get("type") - if mcp_type == "mcp_call": + if use_events: + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + # Validate MCP content in conversation items - should be minimal + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_approval_response": + # Should have id but might not have other details assert "id" in mcp_content - # Should not have name, server_label, arguments when content recording is disabled - assert ( - "name" not in mcp_content - ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" - else: - assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + elif entry.get("role") == "assistant": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content: + mcp_type = mcp_content.get("type") + if mcp_type == "mcp_call": + assert "id" in mcp_content + # Should not have name, server_label, arguments when content recording is disabled + assert ( + "name" not in mcp_content + ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" # Cleanup await openai_client.conversations.delete(conversation_id=conversation.id) @@ -596,16 +669,33 @@ async def test_async_mcp_non_streaming_without_content_recording(self, **kwargs) finally: await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_non_streaming_without_content_recording_events(self, **kwargs): + """Test asynchronous MCP agent with non-streaming and content recording disabled (event-based messages).""" + await self._test_async_mcp_non_streaming_without_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_non_streaming_without_content_recording_attributes(self, **kwargs): + """Test asynchronous MCP agent with non-streaming and content recording disabled (attribute-based messages).""" + await self._test_async_mcp_non_streaming_without_content_recording_impl(False, **kwargs) + # ======================================== # Async MCP Agent Tests - Streaming # ======================================== - @pytest.mark.usefixtures("instrument_with_content") - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_async_mcp_streaming_with_content_recording(self, **kwargs): - """Test asynchronous MCP agent with streaming and content recording enabled.""" + async def _test_async_mcp_streaming_with_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous MCP agent with streaming and content recording enabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -696,8 +786,8 @@ async def test_async_mcp_streaming_with_content_recording(self, **kwargs): expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -706,53 +796,64 @@ async def test_async_mcp_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation - verify content IS present from collections.abc import Mapping - for event in span1.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - if entry.get("role") == "user": + if use_events: + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" in part + and isinstance(part["content"], str) + and part["content"].strip() != "" + ), "Text content should be present when content recording is enabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - and isinstance(part["content"], str) - and part["content"].strip() != "" - ), "Text content should be present when content recording is enabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content: - tool_type = tool_content.get("type") - if tool_type == "mcp_approval_request": - assert ( - "name" in tool_content - ), "name should be present for mcp_approval_request when content recording is enabled" - assert ( - "arguments" in tool_content - ), "arguments should be present for mcp_approval_request when content recording is enabled" + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content: + tool_type = tool_content.get("type") + if tool_type == "mcp_approval_request": + assert ( + "name" in tool_content + ), "name should be present for mcp_approval_request when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_approval_request when content recording is enabled" # Validate second response span span2 = spans[1] @@ -762,8 +863,8 @@ async def test_async_mcp_streaming_with_content_recording(self, **kwargs): expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -772,66 +873,78 @@ async def test_async_mcp_streaming_with_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate second span events - for event in span2.events: - if event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content and tool_content.get("type") == "mcp_call": - assert ( - "name" in tool_content - ), "name should be present for mcp_call when content recording is enabled" + if use_events: + for event in span2.events: + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert ( + "name" in tool_content + ), "name should be present for mcp_call when content recording is enabled" + assert ( + "arguments" in tool_content + ), "arguments should be present for mcp_call when content recording is enabled" + elif part.get("type") == "text": assert ( - "arguments" in tool_content - ), "arguments should be present for mcp_call when content recording is enabled" - elif part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present when content recording is enabled" + "content" in part + ), "text content should be present when content recording is enabled" # Check list_conversation_items span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) == 1 list_span = list_spans[0] - for event in list_span.events: - if event.name == "gen_ai.conversation.item": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "text": - assert ( - "content" in part - ), "text content should be present in conversation items when content recording is enabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content and mcp_content.get("type") == "mcp_call": + if use_events: + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": assert ( - "name" in mcp_content - ), "name should be present for mcp_call in conversation items when content recording is enabled" - else: - assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + "content" in part + ), "text content should be present in conversation items when content recording is enabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_call": + assert ( + "name" in mcp_content + ), "name should be present for mcp_call in conversation items when content recording is enabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" # Cleanup await openai_client.conversations.delete(conversation_id=conversation.id) @@ -839,12 +952,29 @@ async def test_async_mcp_streaming_with_content_recording(self, **kwargs): finally: await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) - @pytest.mark.usefixtures("instrument_without_content") + @pytest.mark.usefixtures("instrument_with_content") @servicePreparer() @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_async_mcp_streaming_without_content_recording(self, **kwargs): - """Test asynchronous MCP agent with streaming and content recording disabled.""" + async def test_async_mcp_streaming_with_content_recording_events(self, **kwargs): + """Test asynchronous MCP agent with streaming and content recording enabled (event-based messages).""" + await self._test_async_mcp_streaming_with_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_with_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_streaming_with_content_recording_attributes(self, **kwargs): + """Test asynchronous MCP agent with streaming and content recording enabled (attribute-based messages).""" + await self._test_async_mcp_streaming_with_content_recording_impl(False, **kwargs) + + async def _test_async_mcp_streaming_without_content_recording_impl(self, use_events, **kwargs): + """Implementation for testing asynchronous MCP agent with streaming and content recording disabled. + + Args: + use_events: If True, use event-based message tracing. If False, use attribute-based. + Note: MCP tests currently only validate event mode regardless of this setting. + """ self.cleanup() + _set_use_message_events(use_events) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -935,8 +1065,8 @@ async def test_async_mcp_streaming_without_content_recording(self, **kwargs): expected_attributes_1 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -945,51 +1075,62 @@ async def test_async_mcp_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_1.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span1, expected_attributes_1) # Comprehensive event validation - verify content is NOT present from collections.abc import Mapping - for event in span1.events: - if event.name == "gen_ai.input.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - if entry.get("role") == "user": + if use_events: + for event in span1.events: + if event.name == "gen_ai.input.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + if entry.get("role") == "user": + parts = entry.get("parts") + for part in parts: + if part.get("type") == "text": + assert ( + "content" not in part + ), "Text content should NOT be present when content recording is disabled" + elif event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: parts = entry.get("parts") - for part in parts: - if part.get("type") == "text": - assert ( - "content" not in part - ), "Text content should NOT be present when content recording is disabled" - elif event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content: - tool_type = tool_content.get("type") - if tool_type == "mcp_approval_request": - assert ( - "name" not in tool_content - ), "name should NOT be present for mcp_approval_request when content recording is disabled" - assert ( - "arguments" not in tool_content - ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content: + tool_type = tool_content.get("type") + if tool_type == "mcp_approval_request": + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_approval_request when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_approval_request when content recording is disabled" # Validate second response span span2 = spans[1] @@ -999,8 +1140,8 @@ async def test_async_mcp_streaming_without_content_recording(self, **kwargs): expected_attributes_2 = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", agent.name), @@ -1009,69 +1150,95 @@ async def test_async_mcp_streaming_without_content_recording(self, **kwargs): ("gen_ai.usage.input_tokens", "+"), ("gen_ai.usage.output_tokens", "+"), ] + + # Add message attributes when not using events + if not use_events: + expected_attributes_2.extend( + [ + ("gen_ai.input.messages", ""), + ("gen_ai.output.messages", ""), + ] + ) + assert GenAiTraceVerifier().check_span_attributes(span2, expected_attributes_2) # Validate second span events - content should be minimal - for event in span2.events: - if event.name == "gen_ai.output.messages": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "tool_call": - tool_content = part.get("content") - if tool_content and tool_content.get("type") == "mcp_call": - assert ( - "name" not in tool_content - ), "name should NOT be present for mcp_call when content recording is disabled" + if use_events: + for event in span2.events: + if event.name == "gen_ai.output.messages": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "tool_call": + tool_content = part.get("content") + if tool_content and tool_content.get("type") == "mcp_call": + assert ( + "name" not in tool_content + ), "name should NOT be present for mcp_call when content recording is disabled" + assert ( + "arguments" not in tool_content + ), "arguments should NOT be present for mcp_call when content recording is disabled" + elif part.get("type") == "text": assert ( - "arguments" not in tool_content - ), "arguments should NOT be present for mcp_call when content recording is disabled" - elif part.get("type") == "text": - assert ( - "content" not in part - ), "text content should NOT be present when content recording is disabled" + "content" not in part + ), "text content should NOT be present when content recording is disabled" # Check list_conversation_items span list_spans = self.exporter.get_spans_by_name("list_conversation_items") assert len(list_spans) == 1 list_span = list_spans[0] - for event in list_span.events: - if event.name == "gen_ai.conversation.item": - attrs = event.attributes - assert attrs is not None and isinstance(attrs, Mapping) - content = attrs.get("gen_ai.event.content") - assert isinstance(content, str) and content.strip() != "" - import json - - data = json.loads(content) - for entry in data: - parts = entry.get("parts") - if parts: - for part in parts: - if part.get("type") == "text": - assert ( - "content" not in part - ), "text content should NOT be present in conversation items when content recording is disabled" - elif part.get("type") == "mcp": - mcp_content = part.get("content") - if mcp_content and mcp_content.get("type") == "mcp_call": + if use_events: + for event in list_span.events: + if event.name == "gen_ai.conversation.item": + attrs = event.attributes + assert attrs is not None and isinstance(attrs, Mapping) + content = attrs.get("gen_ai.event.content") + assert isinstance(content, str) and content.strip() != "" + import json + + data = json.loads(content) + for entry in data: + parts = entry.get("parts") + if parts: + for part in parts: + if part.get("type") == "text": assert ( - "name" not in mcp_content - ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" - else: - assert False, f"Unexpected event name in list_conversation_items span: {event.name}" + "content" not in part + ), "text content should NOT be present in conversation items when content recording is disabled" + elif part.get("type") == "mcp": + mcp_content = part.get("content") + if mcp_content and mcp_content.get("type") == "mcp_call": + assert ( + "name" not in mcp_content + ), "name should NOT be present for mcp_call in conversation items when content recording is disabled" + else: + assert False, f"Unexpected event name in list_conversation_items span: {event.name}" # Cleanup await openai_client.conversations.delete(conversation_id=conversation.id) finally: await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_streaming_without_content_recording_events(self, **kwargs): + """Test asynchronous MCP agent with streaming and content recording disabled (event-based messages).""" + await self._test_async_mcp_streaming_without_content_recording_impl(True, **kwargs) + + @pytest.mark.usefixtures("instrument_without_content") + @servicePreparer() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_async_mcp_streaming_without_content_recording_attributes(self, **kwargs): + """Test asynchronous MCP agent with streaming and content recording disabled (attribute-based messages).""" + await self._test_async_mcp_streaming_without_content_recording_impl(False, **kwargs) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py index dca9a911fd75..5d9254d23c80 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow.py @@ -9,7 +9,12 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils import recorded_by_proxy, RecordedTransport @@ -189,6 +194,7 @@ def _create_student_teacher_workflow(self, project_client, student_agent, teache def test_sync_workflow_non_streaming_with_content_recording(self, **kwargs): """Test synchronous workflow agent with non-streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -264,8 +270,8 @@ def test_sync_workflow_non_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), @@ -353,6 +359,7 @@ def test_sync_workflow_non_streaming_with_content_recording(self, **kwargs): def test_sync_workflow_non_streaming_without_content_recording(self, **kwargs): """Test synchronous workflow agent with non-streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -425,8 +432,8 @@ def test_sync_workflow_non_streaming_without_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), @@ -519,6 +526,7 @@ def test_sync_workflow_non_streaming_without_content_recording(self, **kwargs): def test_sync_workflow_streaming_with_content_recording(self, **kwargs): """Test synchronous workflow agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -596,8 +604,8 @@ def test_sync_workflow_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), @@ -686,6 +694,7 @@ def test_sync_workflow_streaming_with_content_recording(self, **kwargs): def test_sync_workflow_streaming_without_content_recording(self, **kwargs): """Test synchronous workflow agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -763,8 +772,8 @@ def test_sync_workflow_streaming_without_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py index fcb55113a0eb..494c29e71fd3 100644 --- a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_responses_instrumentor_workflow_async.py @@ -9,7 +9,12 @@ import os import pytest from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils -from azure.ai.projects.telemetry._utils import SPAN_NAME_INVOKE_AGENT +from azure.ai.projects.telemetry._utils import ( + OPERATION_NAME_INVOKE_AGENT, + SPAN_NAME_INVOKE_AGENT, + _set_use_message_events, + RESPONSES_PROVIDER, +) from azure.core.settings import settings from gen_ai_trace_verifier import GenAiTraceVerifier from devtools_testutils.aio import recorded_by_proxy_async @@ -188,6 +193,7 @@ async def _create_student_teacher_workflow(self, project_client, student_agent, async def test_async_workflow_non_streaming_with_content_recording(self, **kwargs): """Test asynchronous workflow agent with non-streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -260,8 +266,8 @@ async def test_async_workflow_non_streaming_with_content_recording(self, **kwarg # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), @@ -348,6 +354,7 @@ async def test_async_workflow_non_streaming_with_content_recording(self, **kwarg async def test_async_workflow_non_streaming_without_content_recording(self, **kwargs): """Test asynchronous workflow agent with non-streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -420,8 +427,8 @@ async def test_async_workflow_non_streaming_without_content_recording(self, **kw # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), @@ -512,6 +519,7 @@ async def test_async_workflow_non_streaming_without_content_recording(self, **kw async def test_async_workflow_streaming_with_content_recording(self, **kwargs): """Test asynchronous workflow agent with streaming and content recording enabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "True", @@ -589,8 +597,8 @@ async def test_async_workflow_streaming_with_content_recording(self, **kwargs): # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), @@ -677,6 +685,7 @@ async def test_async_workflow_streaming_with_content_recording(self, **kwargs): async def test_async_workflow_streaming_without_content_recording(self, **kwargs): """Test asynchronous workflow agent with streaming and content recording disabled.""" self.cleanup() + _set_use_message_events(True) os.environ.update( { CONTENT_TRACING_ENV_VARIABLE: "False", @@ -754,8 +763,8 @@ async def test_async_workflow_streaming_without_content_recording(self, **kwargs # Check span attributes expected_attributes = [ ("az.namespace", "Microsoft.CognitiveServices"), - ("gen_ai.operation.name", "responses"), - ("gen_ai.provider.name", "azure.openai"), + ("gen_ai.operation.name", OPERATION_NAME_INVOKE_AGENT), + ("gen_ai.provider.name", RESPONSES_PROVIDER), ("server.address", ""), ("gen_ai.conversation.id", conversation.id), ("gen_ai.agent.name", workflow.name), From 98537a2c642b1b76f563cfbb7b7eb529ab998302 Mon Sep 17 00:00:00 2001 From: Sydney Lister <103153180+slister1001@users.noreply.github.com> Date: Thu, 5 Feb 2026 10:54:54 -0500 Subject: [PATCH 63/84] fix(azure-ai-evaluation): Add missing filter params to get_attack_objectives API (#45013) The autogenerated SDK client for get_attack_objectives was missing three filter parameters that the server API supports: strategy, risk_category, and target_type. These parameters were being passed by the wrapper in _generated_rai_client.py but were absorbed by **kwargs and never sent to the server. This caused the attack objectives fetch to return unexpected results, leading to empty attack_details in RedTeam scan results. Changes: - Add strategy, risk_category, target_type optional params to build_rai_svc_get_attack_objectives_request() - Add same params to RAISvcOperations.get_attack_objectives() - Forward params to query string when provided Co-authored-by: Claude Opus 4.5 --- .../raiclient/operations/_operations.py | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/autogen/raiclient/operations/_operations.py b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/autogen/raiclient/operations/_operations.py index 4eb1057a3ebe..15f3987cefa1 100644 --- a/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/autogen/raiclient/operations/_operations.py +++ b/sdk/evaluation/azure-ai-evaluation/azure/ai/evaluation/autogen/raiclient/operations/_operations.py @@ -112,7 +112,13 @@ def build_rai_svc_get_jail_break_dataset_with_type_request( # pylint: disable=n def build_rai_svc_get_attack_objectives_request( # pylint: disable=name-too-long - *, risk_types: List[str], lang: str, **kwargs: Any + *, + risk_types: List[str], + lang: str, + strategy: Optional[str] = None, + risk_category: Optional[str] = None, + target_type: Optional[str] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -127,6 +133,12 @@ def build_rai_svc_get_attack_objectives_request( # pylint: disable=name-too-lon _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["riskTypes"] = _SERIALIZER.query("risk_types", risk_types, "[str]", div=",") _params["lang"] = _SERIALIZER.query("lang", lang, "str") + if strategy: + _params["strategy"] = _SERIALIZER.query("strategy", strategy, "str") + if risk_category: + _params["riskCategory"] = _SERIALIZER.query("risk_category", risk_category, "str") + if target_type: + _params["targetType"] = _SERIALIZER.query("target_type", target_type, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -566,13 +578,28 @@ def get_jail_break_dataset_with_type(self, type: str, **kwargs: Any) -> str: return deserialized # type: ignore @distributed_trace - def get_attack_objectives(self, *, risk_types: List[str], lang: str, **kwargs: Any) -> str: + def get_attack_objectives( + self, + *, + risk_types: List[str], + lang: str, + strategy: Optional[str] = None, + risk_category: Optional[str] = None, + target_type: Optional[str] = None, + **kwargs: Any, + ) -> str: """Get the attack objectives. :keyword risk_types: Risk types for the attack objectives dataset. Required. :paramtype risk_types: list[str] :keyword lang: The language for the attack objectives dataset, defaults to 'en'. Required. :paramtype lang: str + :keyword strategy: Attack strategy filter. Optional. + :paramtype strategy: str + :keyword risk_category: Risk category filter. Optional. + :paramtype risk_category: str + :keyword target_type: Target type filter (e.g., "agent"). Optional. + :paramtype target_type: str :return: str :rtype: str :raises ~azure.core.exceptions.HttpResponseError: @@ -593,6 +620,9 @@ def get_attack_objectives(self, *, risk_types: List[str], lang: str, **kwargs: A _request = build_rai_svc_get_attack_objectives_request( risk_types=risk_types, lang=lang, + strategy=strategy, + risk_category=risk_category, + target_type=target_type, api_version=self._config.api_version, headers=_headers, params=_params, From 2505166b25b3deda01ecf62f17fa7442697383f8 Mon Sep 17 00:00:00 2001 From: rads-1996 Date: Thu, 5 Feb 2026 08:53:40 -0800 Subject: [PATCH 64/84] Exporter release 1.0.0b48 (#45010) --- .../azure-monitor-opentelemetry-exporter/CHANGELOG.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index 47e55f37f2ac..0b2b8a29c67f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -1,10 +1,6 @@ # Release History -## 1.0.0b48 (Unreleased) - -### Features Added - -### Breaking Changes +## 1.0.0b48 (2026-02-05) ### Bugs Fixed - Fix CPU usage calculation logic for live metrics From 71c91bdcc06e5ed09621c2cb296b042364a2b37c Mon Sep 17 00:00:00 2001 From: Scott Addie <10702007+scottaddie@users.noreply.github.com> Date: Thu, 5 Feb 2026 12:52:29 -0600 Subject: [PATCH 65/84] Simplify Identity README (#45015) * Simplify Identity README * Update sdk/identity/azure-identity/README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update sdk/identity/azure-identity/README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update sdk/identity/azure-identity/README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Fix cspell error --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .vscode/cspell.json | 1 + sdk/identity/azure-identity/README.md | 205 ++++++-------------------- 2 files changed, 45 insertions(+), 161 deletions(-) diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 62a0ca562da0..a42733f5cf0f 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -449,6 +449,7 @@ "toxenv", "tzname", "tzutc", + "uami", "uamqp", "uksouth", "ukwest", diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index fe8869008ad3..5961a9657dcb 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -23,29 +23,9 @@ pip install azure-identity - An [Azure subscription](https://azure.microsoft.com/free/python) - Python 3.9 or a recent version of Python 3 (this library doesn't support end-of-life versions) -### Authenticate during local development +### Authenticate the client -When debugging and executing code locally, it's typical for developers to use their own accounts for authenticating calls to Azure services. The Azure Identity library supports authenticating through developer tools to simplify local development. - -#### Authenticate via the Azure CLI - -`DefaultAzureCredential` and `AzureCliCredential` can authenticate as the user signed in to the [Azure CLI][azure_cli]. To sign in to the Azure CLI, run `az login`. On a system with a default web browser, the Azure CLI launches the browser to authenticate a user. - -When no default browser is available, `az login` uses the device code authentication flow. This flow can also be selected manually by running `az login --use-device-code`. - -#### Authenticate via the Azure Developer CLI - -Developers coding outside of an IDE can also use the [Azure Developer CLI][azure_developer_cli] to authenticate. Applications using `DefaultAzureCredential` or `AzureDeveloperCliCredential` can then use this account to authenticate calls in their application when running locally. - -To authenticate with the [Azure Developer CLI][azure_developer_cli], run the command `azd auth login`. For users running on a system with a default web browser, the Azure Developer CLI launches the browser to authenticate the user. - -For systems without a default web browser, the `azd auth login --use-device-code` command uses the device code authentication flow. - -#### Authenticate via Azure PowerShell - -Developers coding outside of an IDE can also use [Azure PowerShell][azure_powershell] to authenticate. Applications using `DefaultAzureCredential` or `AzurePowerShellCredential` can then use this account to authenticate calls in their application when running locally. - -To authenticate with Azure PowerShell, run the `Connect-AzAccount` cmdlet. By default, like the Azure CLI, `Connect-AzAccount` launches the default web browser to authenticate the user. For systems without a default web browser, the `Connect-AzAccount` uses the device code authentication flow. The user can also force Azure PowerShell to use the device code flow rather than launching a browser by specifying the `-UseDeviceAuthentication` argument. +When debugging and executing code locally, it's typical for a developer to use their own account for authenticating calls to Azure services. There are several developer tools that can be used to perform this authentication in your development environment. For more information, see [Authentication during local development](https://learn.microsoft.com/azure/developer/python/sdk/authentication/overview#authentication-during-local-development). ## Key concepts @@ -69,53 +49,9 @@ This allows for trying all of the developer credentials on your machine while ha The following examples are provided: -- [Authenticate with DefaultAzureCredential](#authenticate-with-defaultazurecredential "Authenticate with DefaultAzureCredential") - [Define a custom authentication flow with ChainedTokenCredential](#define-a-custom-authentication-flow-with-chainedtokencredential "Define a custom authentication flow with ChainedTokenCredential") - [Async credentials](#async-credentials "Async credentials") -### Authenticate with `DefaultAzureCredential` - -More details on configuring your environment to use `DefaultAzureCredential` can be found in the class's [reference documentation][default_cred_ref]. - -This example demonstrates authenticating the `BlobServiceClient` from the [azure-storage-blob][azure_storage_blob] library using `DefaultAzureCredential`. - -```python -from azure.identity import DefaultAzureCredential -from azure.storage.blob import BlobServiceClient - -default_credential = DefaultAzureCredential() - -client = BlobServiceClient(account_url, credential=default_credential) -``` - -#### Enable interactive authentication with `DefaultAzureCredential` - -By default, interactive authentication is disabled in `DefaultAzureCredential` and can be enabled with a keyword argument: - -```python -DefaultAzureCredential(exclude_interactive_browser_credential=False) -``` - -When enabled, `DefaultAzureCredential` falls back to interactively authenticating via the system's default web browser when no other credential is available. - -#### Specify a user-assigned managed identity with `DefaultAzureCredential` - -Many Azure hosts allow the assignment of a user-assigned managed identity. To configure `DefaultAzureCredential` to authenticate a user-assigned managed identity, use the `managed_identity_client_id` keyword argument: - -```python -DefaultAzureCredential(managed_identity_client_id=client_id) -``` - -Alternatively, set the environment variable `AZURE_CLIENT_ID` to the identity's client ID. - -#### Authenticate Using Visual Studio Code with `DefaultAzureCredential` - -To authenticate using Visual Studio Code, ensure you have signed in through the **Azure Resources** extension. The signed-in user is then picked up automatically by `DefaultAzureCredential`. Currently, this is only supported on Windows and WSL. To use this method of authentication, ensure the following prerequisites are met: - -- [Azure Resources Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureresourcegroups) is installed in Visual Studio Code. -- You are signed in using the `Azure: Sign In` command in VS Code. -- You have the [`azure-identity-broker`][azure_identity_broker] package installed. - ### Define a custom authentication flow with `ChainedTokenCredential` While `DefaultAzureCredential` is generally the quickest way to authenticate apps for Azure, you can create a customized chain of credentials to be considered. `ChainedTokenCredential` enables users to combine multiple credential instances to define a customized chain of credentials. For more information, see [ChainedTokenCredential overview][ctc_overview]. @@ -152,7 +88,7 @@ client = SecretClient("https://my-vault.vault.azure.net", default_credential) ## Managed identity support -[Managed identity authentication](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview) is supported via either `DefaultAzureCredential` or `ManagedIdentityCredential` directly for the following Azure services: +[Managed identity authentication](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview) is supported either indirectly via `DefaultAzureCredential` or directly via `ManagedIdentityCredential` for the following Azure services: - [Azure App Service and Azure Functions](https://learn.microsoft.com/azure/app-service/overview-managed-identity?tabs=python) - [Azure Arc](https://learn.microsoft.com/azure/azure-arc/servers/managed-identity-authentication) @@ -162,57 +98,6 @@ client = SecretClient("https://my-vault.vault.azure.net", default_credential) - [Azure Virtual Machines](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/how-to-use-vm-token) - [Azure Virtual Machines Scale Sets](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/qs-configure-powershell-windows-vmss) -### Examples - -These examples demonstrate authenticating `SecretClient` from the [`azure-keyvault-secrets`](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-secrets) library with `ManagedIdentityCredential`. - - -#### Authenticate with a user-assigned managed identity - -To authenticate with a user-assigned managed identity, you must specify one of the following IDs for the managed identity. - -##### Client ID - -```python -from azure.identity import ManagedIdentityCredential -from azure.keyvault.secrets import SecretClient - -credential = ManagedIdentityCredential(client_id="managed_identity_client_id") -client = SecretClient("https://my-vault.vault.azure.net", credential) -``` - -##### Resource ID - -```python -from azure.identity import ManagedIdentityCredential -from azure.keyvault.secrets import SecretClient - -resource_id = "/subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities/" - -credential = ManagedIdentityCredential(identity_config={"resource_id": resource_id}) -client = SecretClient("https://my-vault.vault.azure.net", credential) -``` - -##### Object ID - -```python -from azure.identity import ManagedIdentityCredential -from azure.keyvault.secrets import SecretClient - -credential = ManagedIdentityCredential(identity_config={"object_id": "managed_identity_object_id"}) -client = SecretClient("https://my-vault.vault.azure.net", credential) -``` - -#### Authenticate with a system-assigned managed identity - -```python -from azure.identity import ManagedIdentityCredential -from azure.keyvault.secrets import SecretClient - -credential = ManagedIdentityCredential() -client = SecretClient("https://my-vault.vault.azure.net", credential) -``` - ## Cloud configuration Credentials default to authenticating to the Microsoft Entra endpoint for Azure Public Cloud. To access resources in other clouds, such as Azure Government or a private cloud, configure credentials with the `authority` argument. [AzureAuthorityHosts](https://aka.ms/azsdk/python/identity/docs#azure.identity.AzureAuthorityHosts) defines authorities for well-known clouds: @@ -241,45 +126,45 @@ Not all credentials require this configuration. Credentials that authenticate th ### Credential chains -|Credential|Usage -|-|- -|[`DefaultAzureCredential`][default_cred_ref]| Provides a simplified authentication experience to quickly start developing applications run in Azure. -|[`ChainedTokenCredential`][chain_cred_ref]| Allows users to define custom authentication flows composing multiple credentials. +| Credential | Usage | Reference | +|----------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------| +| [`DefaultAzureCredential`][default_cred_ref] | Provides a simplified authentication experience to quickly start developing applications run in Azure. | [DefaultAzureCredential overview][dac_overview] | +| [`ChainedTokenCredential`][chain_cred_ref] | Allows users to define custom authentication flows composing multiple credentials. | [ChainedTokenCredential overview][ctc_overview] | ### Authenticate Azure-hosted applications -|Credential|Usage -|-|- -|[`EnvironmentCredential`][environment_cred_ref]| Authenticates a service principal or user via credential information specified in environment variables. -|[`ManagedIdentityCredential`][managed_id_cred_ref]| Authenticates the managed identity of an Azure resource. -|[`WorkloadIdentityCredential`][workload_id_cred_ref]| Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/aks/workload-identity-overview) on Kubernetes. +| Credential | Usage | Reference | +|------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------| +| [`EnvironmentCredential`][environment_cred_ref] | Authenticates a service principal or user via credential information specified in environment variables. | | +| [`ManagedIdentityCredential`][managed_id_cred_ref] | Authenticates the managed identity of an Azure resource. | [user-assigned managed identity][uami_doc]
[system-assigned managed identity][sami_doc] | +| [`WorkloadIdentityCredential`][workload_id_cred_ref] | Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/aks/workload-identity-overview) on Kubernetes. | | ### Authenticate service principals -|Credential|Usage|Reference -|-|-|- -|[`AzurePipelinesCredential`][az_pipelines_cred_ref]| Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/devops/pipelines/release/configure-workload-identity?view=azure-devops) on Azure Pipelines. | -|[`CertificateCredential`][cert_cred_ref]| Authenticates a service principal using a certificate. | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) -|[`ClientAssertionCredential`][client_assertion_cred_ref]| Authenticates a service principal using a signed client assertion. | -|[`ClientSecretCredential`][client_secret_cred_ref]| Authenticates a service principal using a secret. | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) +| Credential | Usage | Reference | +|----------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------| +| [`AzurePipelinesCredential`][az_pipelines_cred_ref] | Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/devops/pipelines/release/configure-workload-identity?view=azure-devops) on Azure Pipelines. | | +| [`CertificateCredential`][cert_cred_ref] | Authenticates a service principal using a certificate. | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) | +| [`ClientAssertionCredential`][client_assertion_cred_ref] | Authenticates a service principal using a signed client assertion. | | +| [`ClientSecretCredential`][client_secret_cred_ref] | Authenticates a service principal using a secret. | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) | ### Authenticate users -|Credential|Usage| Reference | Notes -|-|-|-|- -|[`AuthorizationCodeCredential`][auth_code_cred_ref]| Authenticates a user with a previously obtained authorization code. | [OAuth2 authentication code](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow)| -|[`DeviceCodeCredential`][device_code_cred_ref]| Interactively authenticates a user on devices with limited UI. | [Device code authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-device-code)| -|[`InteractiveBrowserCredential`][interactive_cred_ref]| Interactively authenticates a user with the default system browser. | [OAuth2 authentication code](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow)| `InteractiveBrowserCredential` doesn't support GitHub Codespaces. As a workaround, use [`DeviceCodeCredential`][device_code_cred_ref]. -|[`OnBehalfOfCredential`][obo_cred_ref]| Propagates the delegated user identity and permissions through the request chain. | [On-behalf-of authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow)| +| Credential | Usage | Reference | Notes | +|--------------------------------------------------------|-----------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| +| [`AuthorizationCodeCredential`][auth_code_cred_ref] | Authenticates a user with a previously obtained authorization code. | [OAuth2 authentication code](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow) | | +| [`DeviceCodeCredential`][device_code_cred_ref] | Interactively authenticates a user on devices with limited UI. | [Device code authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-device-code) | | +| [`InteractiveBrowserCredential`][interactive_cred_ref] | Interactively authenticates a user with the default system browser. | [OAuth2 authentication code](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow) | `InteractiveBrowserCredential` doesn't support GitHub Codespaces. As a workaround, use [`DeviceCodeCredential`][device_code_cred_ref]. | +| [`OnBehalfOfCredential`][obo_cred_ref] | Propagates the delegated user identity and permissions through the request chain. | [On-behalf-of authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow) | | ### Authenticate via development tools -|Credential|Usage|Reference -|-|-|- -|[`AzureCliCredential`][cli_cred_ref]| Authenticates in a development environment with the Azure CLI. | [Azure CLI authentication](https://learn.microsoft.com/cli/azure/authenticate-azure-cli) -|[`AzureDeveloperCliCredential`][azd_cli_cred_ref]| Authenticates in a development environment with the Azure Developer CLI. | [Azure Developer CLI Reference](https://learn.microsoft.com/azure/developer/azure-developer-cli/reference) -|[`AzurePowerShellCredential`][powershell_cred_ref]| Authenticates in a development environment with the Azure PowerShell. | [Azure PowerShell authentication](https://learn.microsoft.com/powershell/azure/authenticate-azureps) -|[`VisualStudioCodeCredential`][vsc_cred_ref]| Authenticates in a development environment with Visual Studio Code. | +| Credential | Usage | Reference | +|----------------------------------------------------|--------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------| +| [`AzureCliCredential`][cli_cred_ref] | Authenticates in a development environment with the Azure CLI. | [Azure CLI authentication](https://learn.microsoft.com/cli/azure/authenticate-azure-cli) | +| [`AzureDeveloperCliCredential`][azd_cli_cred_ref] | Authenticates in a development environment with the Azure Developer CLI. | [Azure Developer CLI Reference](https://learn.microsoft.com/azure/developer/azure-developer-cli/reference) | +| [`AzurePowerShellCredential`][powershell_cred_ref] | Authenticates in a development environment with the Azure PowerShell. | [Azure PowerShell authentication](https://learn.microsoft.com/powershell/azure/authenticate-azureps) | +| [`VisualStudioCodeCredential`][vsc_cred_ref] | Authenticates in a development environment with Visual Studio Code. | | ## Environment variables @@ -288,21 +173,21 @@ variables: ### Service principal with secret -|Variable name|Value -|-|- -|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application -|`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant -|`AZURE_CLIENT_SECRET`|one of the application's client secrets +| Variable name | Value | +|-----------------------|------------------------------------------------| +| `AZURE_CLIENT_ID` | ID of a Microsoft Entra application | +| `AZURE_TENANT_ID` | ID of the application's Microsoft Entra tenant | +| `AZURE_CLIENT_SECRET` | one of the application's client secrets | ### Service principal with certificate -|Variable name|Value|Required -|-|-|- -|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application|X -|`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant|X -|`AZURE_CLIENT_CERTIFICATE_PATH`|path to a PEM or PKCS12 certificate file including private key|X -|`AZURE_CLIENT_CERTIFICATE_PASSWORD`|password of the certificate file, if any| -|`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN`|If `True`, the credential sends the public certificate chain in the x5c header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. Defaults to False. There's a [known limitation](https://github.com/Azure/azure-sdk-for-python/issues/13349) that async SNI authentication isn't supported.| +| Variable name | Value | Required | +|---------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `AZURE_CLIENT_ID` | ID of a Microsoft Entra application | X | +| `AZURE_TENANT_ID` | ID of the application's Microsoft Entra tenant | X | +| `AZURE_CLIENT_CERTIFICATE_PATH` | path to a PEM or PKCS12 certificate file including private key | X | +| `AZURE_CLIENT_CERTIFICATE_PASSWORD` | password of the certificate file, if any | | +| `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN` | If `True`, the credential sends the public certificate chain in the x5c header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. Defaults to False. There's a [known limitation](https://github.com/Azure/azure-sdk-for-python/issues/13349) that async SNI authentication isn't supported. | | Configuration is attempted in the preceding order. For example, if values for a client secret and certificate are both present, the client secret is used. @@ -376,14 +261,10 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [auth_code_cred_ref]: https://aka.ms/azsdk/python/identity/authorizationcodecredential [az_pipelines_cred_ref]: https://aka.ms/azsdk/python/identity/azurepipelinescredential [azd_cli_cred_ref]: https://aka.ms/azsdk/python/identity/azuredeveloperclicredential -[azure_cli]: https://learn.microsoft.com/cli/azure -[azure_developer_cli]:https://aka.ms/azure-dev -[azure_powershell]: https://learn.microsoft.com/powershell/azure [azure_core_transport_doc]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#transport [azure_identity_broker]: https://pypi.org/project/azure-identity-broker [azure_identity_broker_readme]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity-broker [azure_keyvault_secrets]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/keyvault/azure-keyvault-secrets -[azure_storage_blob]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/storage/azure-storage-blob [b2c]: https://learn.microsoft.com/azure/active-directory-b2c/overview [cae]: https://learn.microsoft.com/entra/identity/conditional-access/concept-continuous-access-evaluation [cert_cred_ref]: https://aka.ms/azsdk/python/identity/certificatecredential @@ -403,7 +284,9 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [ref_docs]: https://aka.ms/azsdk/python/identity/docs [ref_docs_aio]: https://aka.ms/azsdk/python/identity/aio/docs [token_cred_ref]: https://learn.microsoft.com/python/api/azure-core/azure.core.credentials.tokencredential?view=azure-python +[sami_doc]: https://learn.microsoft.com/azure/developer/python/sdk/authentication/system-assigned-managed-identity [supports_token_info_ref]: https://learn.microsoft.com/python/api/azure-core/azure.core.credentials.supportstokeninfo?view=azure-python [troubleshooting_guide]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md +[uami_doc]: https://learn.microsoft.com/azure/developer/python/sdk/authentication/user-assigned-managed-identity [vsc_cred_ref]: https://aka.ms/azsdk/python/identity/vscodecredential [workload_id_cred_ref]: https://aka.ms/azsdk/python/identity/workloadidentitycredential From d49c16320b2bfe9116be38302289bab56dcd69c7 Mon Sep 17 00:00:00 2001 From: xitzhang Date: Thu, 5 Feb 2026 11:49:54 -0800 Subject: [PATCH 66/84] Remove portaudio installation from CI pipelines (#45011) * Remove portaudio installation from CI pipelines - Remove InstallPortAudio variable from Build_Extended and Analyze jobs in ci.yml - Delete install-portaudio.yml step template (no longer needed) - Remove portaudio installation step from use-venv.yml - Remove InstallPortAudio setting from sdk/ai/platform-matrix.json - Bump azure-ai-voicelive version to 1.2.0b4 - Add changelog entry for upcoming 1.2.0b4 release * removed unused file * remove metrix config/filter --------- Co-authored-by: Xiting Zhang --- eng/pipelines/templates/jobs/ci.yml | 8 -------- eng/pipelines/templates/steps/install-portaudio.yml | 11 ----------- eng/pipelines/templates/steps/use-venv.yml | 2 -- sdk/ai/azure-ai-voicelive/CHANGELOG.md | 10 ++++++++++ .../azure-ai-voicelive/azure/ai/voicelive/_version.py | 2 +- sdk/ai/ci.yml | 7 ------- sdk/ai/platform-matrix.json | 6 ------ 7 files changed, 11 insertions(+), 35 deletions(-) delete mode 100644 eng/pipelines/templates/steps/install-portaudio.yml delete mode 100644 sdk/ai/platform-matrix.json diff --git a/eng/pipelines/templates/jobs/ci.yml b/eng/pipelines/templates/jobs/ci.yml index 1de53286d7ec..8ad87408ae29 100644 --- a/eng/pipelines/templates/jobs/ci.yml +++ b/eng/pipelines/templates/jobs/ci.yml @@ -147,10 +147,6 @@ jobs: image: $(LINUXVMIMAGE) os: linux - variables: - # default to true just in this job until #42714 can be completed - InstallPortAudio: true - steps: - template: /eng/pipelines/templates/steps/download-package-artifacts.yml @@ -209,10 +205,6 @@ jobs: dependsOn: - 'Build_Extended' - variables: - # default to true just in this job until #42714 can be completed - InstallPortAudio: true - pool: name: $(LINUXPOOL) image: $(LINUXVMIMAGE) diff --git a/eng/pipelines/templates/steps/install-portaudio.yml b/eng/pipelines/templates/steps/install-portaudio.yml deleted file mode 100644 index 0e2cb7ff2837..000000000000 --- a/eng/pipelines/templates/steps/install-portaudio.yml +++ /dev/null @@ -1,11 +0,0 @@ -steps: - - script: | - if [[ "$AGENT_OS" == "Linux" ]]; then - sudo apt-get update - sudo apt-get install -y portaudio19-dev libasound2-dev - elif [[ "$AGENT_OS" == "Darwin" ]]; then - brew update - brew install portaudio - fi - displayName: Install portaudio dependencies if necessary - condition: and(succeeded(), ne(variables['InstallPortAudio'], ''), or(eq(variables['Agent.OS'], 'Linux'), eq(variables['Agent.OS'], 'Darwin'))) \ No newline at end of file diff --git a/eng/pipelines/templates/steps/use-venv.yml b/eng/pipelines/templates/steps/use-venv.yml index f26a918c1861..ef972f0eaf27 100644 --- a/eng/pipelines/templates/steps/use-venv.yml +++ b/eng/pipelines/templates/steps/use-venv.yml @@ -43,5 +43,3 @@ steps: -RepoRoot "$(Build.SourcesDirectory)" displayName: Use ${{ parameters.VirtualEnvironmentName }} Virtual Environment condition: ${{ parameters.Condition }} - - - template: install-portaudio.yml \ No newline at end of file diff --git a/sdk/ai/azure-ai-voicelive/CHANGELOG.md b/sdk/ai/azure-ai-voicelive/CHANGELOG.md index 9020d860c114..6f028321e3a5 100644 --- a/sdk/ai/azure-ai-voicelive/CHANGELOG.md +++ b/sdk/ai/azure-ai-voicelive/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.2.0b4 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.2.0b3 (2026-02-02) ### Features Added diff --git a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_version.py b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_version.py index c04584b58b20..d0e147b4ec1e 100644 --- a/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_version.py +++ b/sdk/ai/azure-ai-voicelive/azure/ai/voicelive/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.2.0b3" +VERSION = "1.2.0b4" diff --git a/sdk/ai/ci.yml b/sdk/ai/ci.yml index 43dbf57d4feb..ef6f9dbcd248 100644 --- a/sdk/ai/ci.yml +++ b/sdk/ai/ci.yml @@ -34,13 +34,6 @@ extends: TestTimeoutInMinutes: 60 # The job "Test ubuntu2404_pypy39" in the "python - ai" pipeline hangs and eventually times out. # Disable it until the issue is understood. - MatrixConfigs: - - Name: communication_ci_matrix - Path: sdk/ai/platform-matrix.json - Selection: sparse - GenerateVMJobs: true - MatrixFilters: - - PythonVersion=^(?!pypy3).* Artifacts: - name: azure-ai-projects safeName: azureaiprojects diff --git a/sdk/ai/platform-matrix.json b/sdk/ai/platform-matrix.json deleted file mode 100644 index b3e63e38fdf7..000000000000 --- a/sdk/ai/platform-matrix.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "matrix": { - "$IMPORT": "eng/pipelines/templates/stages/platform-matrix.json", - "InstallPortAudio": [ "1" ] - } -} \ No newline at end of file From d428f0912d0f1abcd216d5b7dc52d32f0ba89cfe Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Thu, 5 Feb 2026 12:06:46 -0800 Subject: [PATCH 67/84] [Corehttp] Prepare release (#45008) Signed-off-by: Paul Van Eck --- sdk/core/corehttp/CHANGELOG.md | 4 +--- sdk/core/corehttp/setup.py | 5 +++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/sdk/core/corehttp/CHANGELOG.md b/sdk/core/corehttp/CHANGELOG.md index 8b30d36ab798..6bf7890eab42 100644 --- a/sdk/core/corehttp/CHANGELOG.md +++ b/sdk/core/corehttp/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0b7 (Unreleased) +## 1.0.0b7 (2026-02-05) ### Features Added @@ -16,8 +16,6 @@ - Added `set_span_error_status` static method to `OpenTelemetryTracer` for setting a span's status to ERROR. - Added `is_generated_model`, `attribute_list`, and `TypeHandlerRegistry` to `corehttp.serialization` module for SDK model handling. -### Breaking Changes - ### Bugs Fixed - Fixed `retry_backoff_max` being ignored in retry policies when configuring retries. diff --git a/sdk/core/corehttp/setup.py b/sdk/core/corehttp/setup.py index 4e0ce43b08a6..61a20dac1121 100644 --- a/sdk/core/corehttp/setup.py +++ b/sdk/core/corehttp/setup.py @@ -49,11 +49,12 @@ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -65,7 +66,7 @@ package_data={ "pytyped": ["py.typed"], }, - python_requires=">=3.8", + python_requires=">=3.9", install_requires=[ "typing-extensions>=4.6.0", ], From 8e51decec1058e44a7097666de437463bd51334d Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 12:17:45 -0800 Subject: [PATCH 68/84] Increment package version after release of azure-monitor-opentelemetry-exporter (#45039) Co-authored-by: rads-1996 --- .../azure-monitor-opentelemetry-exporter/CHANGELOG.md | 10 ++++++++++ .../azure/monitor/opentelemetry/exporter/_version.py | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index 0b2b8a29c67f..2ab49efeb43e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.0.0b49 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.0.0b48 (2026-02-05) ### Bugs Fixed diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py index 0c991711c5fc..b11ffa27554b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_version.py @@ -5,4 +5,4 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "1.0.0b48" +VERSION = "1.0.0b49" From e72c26f2c88c4878240fe2ebf8726b6f0107134d Mon Sep 17 00:00:00 2001 From: Peter Wu <162184229+weirongw23-msft@users.noreply.github.com> Date: Thu, 5 Feb 2026 16:31:45 -0500 Subject: [PATCH 69/84] self.fail does not exist (#45003) --- sdk/storage/azure-storage-file-share/tests/test_file.py | 2 +- sdk/storage/azure-storage-file-share/tests/test_file_async.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/storage/azure-storage-file-share/tests/test_file.py b/sdk/storage/azure-storage-file-share/tests/test_file.py index 1224a52dbbd8..6d404b365fd9 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file.py @@ -136,7 +136,7 @@ def _wait_for_async_copy(self, share_name, file_path): while properties.copy.status != 'success': count = count + 1 if count > 10: - self.fail('Timed out waiting for async copy to complete.') + pytest.fail('Timed out waiting for async copy to complete.') self.sleep(6) properties = file_client.get_file_properties() assert properties.copy.status == 'success' diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_async.py b/sdk/storage/azure-storage-file-share/tests/test_file_async.py index 6d4d0d56426d..4daa252d6dce 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_async.py @@ -151,7 +151,7 @@ async def _wait_for_async_copy(self, share_name, file_path): while properties.copy.status != 'success': count = count + 1 if count > 10: - self.fail('Timed out waiting for async copy to complete.') + pytest.fail('Timed out waiting for async copy to complete.') self.sleep(6) properties = await file_client.get_file_properties() assert properties.copy.status == 'success' From cb212d8acddf307092c68d7d5f1f388847184d53 Mon Sep 17 00:00:00 2001 From: M-Hietala <78813398+M-Hietala@users.noreply.github.com> Date: Thu, 5 Feb 2026 15:46:24 -0600 Subject: [PATCH 70/84] adding test for trace_function decorator (#45037) * adding test for trace_function decorator * fixing review findings * code reformatting and pylint fixes --- .../telemetry/_ai_project_instrumentor.py | 6 +- .../ai/projects/telemetry/_trace_function.py | 14 +- .../test_trace_function_decorator.py | 345 +++++++++++++++ .../test_trace_function_decorator_async.py | 408 ++++++++++++++++++ 4 files changed, 764 insertions(+), 9 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator.py create mode 100644 sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator_async.py diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py index 6dbc434212d4..a55cfa902f82 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_ai_project_instrumentor.py @@ -1283,7 +1283,7 @@ def _agents_apis(self): def _project_apis(self): """Define AIProjectClient APIs to instrument for trace propagation. - + :return: A tuple containing sync and async API tuples. :rtype: Tuple[Tuple, Tuple] """ @@ -1309,7 +1309,7 @@ def _project_apis(self): def _inject_openai_client(self, f, _trace_type, _name): """Injector for get_openai_client that enables trace context propagation if opted in. - + :return: The wrapped function with trace context propagation enabled. :rtype: Callable """ @@ -1331,7 +1331,7 @@ def _agents_api_list(self): def _project_api_list(self): """Generate project API list with custom injector. - + :return: A generator yielding API tuples with injectors. :rtype: Generator """ diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py index 04a5989795df..956b43792d71 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py @@ -3,14 +3,14 @@ # Licensed under the MIT License. # ------------------------------------ import functools -import asyncio # pylint: disable = do-not-import-asyncio +import inspect from typing import Any, Callable, Optional, Dict try: # pylint: disable = no-name-in-module from opentelemetry import trace as opentelemetry_trace - tracer = opentelemetry_trace.get_tracer(__name__) # type: ignore[attr-defined] + _tracer = opentelemetry_trace.get_tracer(__name__) # type: ignore[attr-defined] _tracing_library_available = True except ModuleNotFoundError: _tracing_library_available = False @@ -50,6 +50,7 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any: :return: The result of the decorated asynchronous function. :rtype: Any """ + tracer = opentelemetry_trace.get_tracer(__name__) # type: ignore[attr-defined] name = span_name if span_name else func.__name__ with tracer.start_as_current_span(name) as span: try: @@ -79,6 +80,7 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any: :return: The result of the decorated synchronous function. :rtype: Any """ + tracer = opentelemetry_trace.get_tracer(__name__) # type: ignore[attr-defined] name = span_name if span_name else func.__name__ with tracer.start_as_current_span(name) as span: try: @@ -99,7 +101,7 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any: raise # Determine if the function is async - if asyncio.iscoroutinefunction(func): + if inspect.iscoroutinefunction(func): return async_wrapper return sync_wrapper @@ -134,15 +136,15 @@ def sanitize_parameters(func, *args, **kwargs) -> Dict[str, Any]: :return: A dictionary of sanitized parameters. :rtype: Dict[str, Any] """ - import inspect - params = inspect.signature(func).parameters sanitized_params = {} for i, (name, param) in enumerate(params.items()): - if param.default == inspect.Parameter.empty and i < len(args): + if i < len(args): + # Use positional argument if provided value = args[i] else: + # Use keyword argument if provided, otherwise fall back to default value value = kwargs.get(name, param.default) sanitized_value = sanitize_for_attributes(value) diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator.py new file mode 100644 index 000000000000..18a96fd8eae3 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator.py @@ -0,0 +1,345 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Tests for the trace_function decorator with synchronous functions.""" +import pytest +from opentelemetry import trace +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from azure.ai.projects.telemetry._trace_function import trace_function +from gen_ai_trace_verifier import GenAiTraceVerifier +from memory_trace_exporter import MemoryTraceExporter + + +class TestTraceFunctionDecorator: + """Tests for trace_function decorator with synchronous functions.""" + + @pytest.fixture(scope="function") + def setup_telemetry(self): + """Setup telemetry for tests.""" + tracer_provider = TracerProvider() + trace._TRACER_PROVIDER = tracer_provider + self.exporter = MemoryTraceExporter() + span_processor = SimpleSpanProcessor(self.exporter) + tracer_provider.add_span_processor(span_processor) + yield + self.exporter.shutdown() + trace._TRACER_PROVIDER = None + + def test_basic_function_with_primitives(self, setup_telemetry): + """Test decorator with a function that has primitive type parameters and return value.""" + + @trace_function() + def add_numbers(a: int, b: int) -> int: + return a + b + + result = add_numbers(5, 3) + assert result == 8 + + spans = self.exporter.get_spans_by_name("add_numbers") + assert len(spans) == 1 + span = spans[0] + + # Verify parameters are traced + expected_attributes = [ + ("code.function.parameter.a", 5), + ("code.function.parameter.b", 3), + ("code.function.return.value", 8), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_string_parameters(self, setup_telemetry): + """Test decorator with string parameters.""" + + @trace_function() + def greet(name: str, greeting: str = "Hello") -> str: + return f"{greeting}, {name}!" + + result = greet("Alice", "Hi") + assert result == "Hi, Alice!" + + spans = self.exporter.get_spans_by_name("greet") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.name", "Alice"), + ("code.function.parameter.greeting", "Hi"), + ("code.function.return.value", "Hi, Alice!"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_list_parameter(self, setup_telemetry): + """Test decorator with list parameters.""" + + @trace_function() + def sum_list(numbers: list) -> int: + return sum(numbers) + + result = sum_list([1, 2, 3, 4, 5]) + assert result == 15 + + spans = self.exporter.get_spans_by_name("sum_list") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.numbers", [1, 2, 3, 4, 5]), + ("code.function.return.value", 15), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_dict_parameter(self, setup_telemetry): + """Test decorator with dict parameters (converted to string).""" + + @trace_function() + def get_value(data: dict, key: str) -> str: + return data.get(key, "not found") + + result = get_value({"name": "Alice", "age": 30}, "name") + assert result == "Alice" + + spans = self.exporter.get_spans_by_name("get_value") + assert len(spans) == 1 + span = spans[0] + + # Dict parameters are converted to strings + expected_dict_str = str({"name": "Alice", "age": 30}) + expected_attributes = [ + ("code.function.parameter.data", expected_dict_str), + ("code.function.parameter.key", "name"), + ("code.function.return.value", "Alice"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_nested_collections(self, setup_telemetry): + """Test decorator with nested collections (converted to string).""" + + @trace_function() + def process_nested(data: list) -> int: + return len(data) + + nested_data = [[1, 2], [3, 4], [5, 6]] + result = process_nested(nested_data) + assert result == 3 + + spans = self.exporter.get_spans_by_name("process_nested") + assert len(spans) == 1 + span = spans[0] + + # Nested collections are converted to strings + expected_data_str = str(nested_data) + expected_attributes = [ + ("code.function.parameter.data", expected_data_str), + ("code.function.return.value", 3), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_custom_span_name(self, setup_telemetry): + """Test decorator with custom span name.""" + + @trace_function(span_name="custom_operation") + def calculate(x: int, y: int) -> int: + return x * y + + result = calculate(4, 7) + assert result == 28 + + spans = self.exporter.get_spans_by_name("custom_operation") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.x", 4), + ("code.function.parameter.y", 7), + ("code.function.return.value", 28), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_no_return_value(self, setup_telemetry): + """Test decorator with a function that returns None.""" + + @trace_function() + def log_message(message: str) -> None: + pass # Just a placeholder + + result = log_message("Test message") + assert result is None + + spans = self.exporter.get_spans_by_name("log_message") + assert len(spans) == 1 + span = spans[0] + + # Only parameter should be traced, no return value attribute + expected_attributes = [ + ("code.function.parameter.message", "Test message"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_boolean_parameters(self, setup_telemetry): + """Test decorator with boolean parameters.""" + + @trace_function() + def check_status(is_active: bool, is_verified: bool) -> str: + if is_active and is_verified: + return "approved" + return "pending" + + result = check_status(True, False) + assert result == "pending" + + spans = self.exporter.get_spans_by_name("check_status") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.is_active", True), + ("code.function.parameter.is_verified", False), + ("code.function.return.value", "pending"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_float_parameters(self, setup_telemetry): + """Test decorator with float parameters.""" + + @trace_function() + def calculate_average(a: float, b: float, c: float) -> float: + return (a + b + c) / 3 + + result = calculate_average(10.5, 20.3, 15.2) + assert abs(result - 15.333333333333334) < 0.0001 + + spans = self.exporter.get_spans_by_name("calculate_average") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.a", 10.5), + ("code.function.parameter.b", 20.3), + ("code.function.parameter.c", 15.2), + ("code.function.return.value", result), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_tuple_parameter(self, setup_telemetry): + """Test decorator with tuple parameters.""" + + @trace_function() + def get_coordinates(point: tuple) -> str: + return f"x={point[0]}, y={point[1]}" + + result = get_coordinates((10, 20)) + assert result == "x=10, y=20" + + spans = self.exporter.get_spans_by_name("get_coordinates") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.point", (10, 20)), + ("code.function.return.value", "x=10, y=20"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + def test_function_with_set_parameter(self, setup_telemetry): + """Test decorator with set parameters (converted to string).""" + + @trace_function() + def count_unique(items: set) -> int: + return len(items) + + result = count_unique({1, 2, 3, 4, 5}) + assert result == 5 + + spans = self.exporter.get_spans_by_name("count_unique") + assert len(spans) == 1 + span = spans[0] + + # Sets are converted to strings, but we need to compare the actual set values + # since set string representation order is non-deterministic + assert span.attributes is not None + assert "code.function.parameter.items" in span.attributes + assert "code.function.return.value" in span.attributes + + # Convert the string back to a set for comparison + import ast + + items_str = span.attributes["code.function.parameter.items"] + assert isinstance(items_str, str) + items_value = ast.literal_eval(items_str) + assert items_value == {1, 2, 3, 4, 5} + assert span.attributes["code.function.return.value"] == 5 + + def test_function_with_exception(self, setup_telemetry): + """Test decorator records exception information.""" + + @trace_function() + def divide(a: int, b: int) -> float: + return a / b + + with pytest.raises(ZeroDivisionError): + divide(10, 0) + + spans = self.exporter.get_spans_by_name("divide") + assert len(spans) == 1 + span = spans[0] + + # Check that parameters were traced + expected_attributes = [ + ("code.function.parameter.a", 10), + ("code.function.parameter.b", 0), + ("error.type", "ZeroDivisionError"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + # Verify exception was recorded as an event + assert len(span.events) > 0 + exception_event = None + for event in span.events: + if event.name == "exception": + exception_event = event + break + assert exception_event is not None + + def test_function_with_mixed_parameters(self, setup_telemetry): + """Test decorator with mixed parameter types.""" + + @trace_function() + def process_data(name: str, count: int, active: bool, scores: list) -> dict: + return { + "name": name, + "count": count, + "active": active, + "average": sum(scores) / len(scores) if scores else 0, + } + + result = process_data("test", 5, True, [90, 85, 95]) + assert result["name"] == "test" + assert result["average"] == 90 + + spans = self.exporter.get_spans_by_name("process_data") + assert len(spans) == 1 + span = spans[0] + + expected_result_str = str(result) + expected_attributes = [ + ("code.function.parameter.name", "test"), + ("code.function.parameter.count", 5), + ("code.function.parameter.active", True), + ("code.function.parameter.scores", [90, 85, 95]), + ("code.function.return.value", expected_result_str), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True diff --git a/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator_async.py b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator_async.py new file mode 100644 index 000000000000..dd7d92bed63c --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/agents/telemetry/test_trace_function_decorator_async.py @@ -0,0 +1,408 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Tests for the trace_function decorator with asynchronous functions.""" +import pytest +from opentelemetry import trace +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from azure.ai.projects.telemetry._trace_function import trace_function +from gen_ai_trace_verifier import GenAiTraceVerifier +from memory_trace_exporter import MemoryTraceExporter + + +class TestTraceFunctionDecoratorAsync: + """Tests for trace_function decorator with asynchronous functions.""" + + @pytest.fixture(scope="function") + def setup_telemetry(self): + """Setup telemetry for tests.""" + tracer_provider = TracerProvider() + trace._TRACER_PROVIDER = tracer_provider + self.exporter = MemoryTraceExporter() + span_processor = SimpleSpanProcessor(self.exporter) + tracer_provider.add_span_processor(span_processor) + yield + self.exporter.shutdown() + trace._TRACER_PROVIDER = None + + @pytest.mark.asyncio + async def test_async_basic_function_with_primitives(self, setup_telemetry): + """Test decorator with an async function that has primitive type parameters.""" + + @trace_function() + async def add_numbers_async(a: int, b: int) -> int: + return a + b + + result = await add_numbers_async(5, 3) + assert result == 8 + + spans = self.exporter.get_spans_by_name("add_numbers_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.a", 5), + ("code.function.parameter.b", 3), + ("code.function.return.value", 8), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_string_parameters(self, setup_telemetry): + """Test decorator with async function and string parameters.""" + + @trace_function() + async def greet_async(name: str, greeting: str = "Hello") -> str: + return f"{greeting}, {name}!" + + result = await greet_async("Bob", "Good morning") + assert result == "Good morning, Bob!" + + spans = self.exporter.get_spans_by_name("greet_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.name", "Bob"), + ("code.function.parameter.greeting", "Good morning"), + ("code.function.return.value", "Good morning, Bob!"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_list_parameter(self, setup_telemetry): + """Test decorator with async function and list parameters.""" + + @trace_function() + async def sum_list_async(numbers: list) -> int: + return sum(numbers) + + result = await sum_list_async([10, 20, 30, 40]) + assert result == 100 + + spans = self.exporter.get_spans_by_name("sum_list_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.numbers", [10, 20, 30, 40]), + ("code.function.return.value", 100), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_dict_parameter(self, setup_telemetry): + """Test decorator with async function and dict parameters.""" + + @trace_function() + async def get_value_async(data: dict, key: str) -> str: + return data.get(key, "not found") + + result = await get_value_async({"city": "Seattle", "state": "WA"}, "city") + assert result == "Seattle" + + spans = self.exporter.get_spans_by_name("get_value_async") + assert len(spans) == 1 + span = spans[0] + + expected_dict_str = str({"city": "Seattle", "state": "WA"}) + expected_attributes = [ + ("code.function.parameter.data", expected_dict_str), + ("code.function.parameter.key", "city"), + ("code.function.return.value", "Seattle"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_nested_collections(self, setup_telemetry): + """Test decorator with async function and nested collections.""" + + @trace_function() + async def process_nested_async(data: list) -> int: + total = 0 + for sublist in data: + total += sum(sublist) + return total + + nested_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + result = await process_nested_async(nested_data) + assert result == 45 + + spans = self.exporter.get_spans_by_name("process_nested_async") + assert len(spans) == 1 + span = spans[0] + + expected_data_str = str(nested_data) + expected_attributes = [ + ("code.function.parameter.data", expected_data_str), + ("code.function.return.value", 45), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_custom_span_name(self, setup_telemetry): + """Test decorator with custom span name on async function.""" + + @trace_function(span_name="async_custom_operation") + async def calculate_async(x: int, y: int) -> int: + return x * y + + result = await calculate_async(6, 9) + assert result == 54 + + spans = self.exporter.get_spans_by_name("async_custom_operation") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.x", 6), + ("code.function.parameter.y", 9), + ("code.function.return.value", 54), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_no_return_value(self, setup_telemetry): + """Test decorator with async function that returns None.""" + + @trace_function() + async def log_message_async(message: str) -> None: + pass # Just a placeholder + + result = await log_message_async("Async test message") + assert result is None + + spans = self.exporter.get_spans_by_name("log_message_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.message", "Async test message"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_boolean_parameters(self, setup_telemetry): + """Test decorator with async function and boolean parameters.""" + + @trace_function() + async def check_status_async(is_active: bool, is_verified: bool) -> str: + if is_active and is_verified: + return "approved" + elif is_active: + return "pending" + return "inactive" + + result = await check_status_async(True, True) + assert result == "approved" + + spans = self.exporter.get_spans_by_name("check_status_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.is_active", True), + ("code.function.parameter.is_verified", True), + ("code.function.return.value", "approved"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_float_parameters(self, setup_telemetry): + """Test decorator with async function and float parameters.""" + + @trace_function() + async def calculate_area_async(width: float, height: float) -> float: + return width * height + + result = await calculate_area_async(12.5, 8.3) + assert abs(result - 103.75) < 0.01 + + spans = self.exporter.get_spans_by_name("calculate_area_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.width", 12.5), + ("code.function.parameter.height", 8.3), + ("code.function.return.value", result), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_tuple_parameter(self, setup_telemetry): + """Test decorator with async function and tuple parameters.""" + + @trace_function() + async def get_coordinates_async(point: tuple) -> str: + return f"Position: ({point[0]}, {point[1]}, {point[2]})" + + result = await get_coordinates_async((10, 20, 30)) + assert result == "Position: (10, 20, 30)" + + spans = self.exporter.get_spans_by_name("get_coordinates_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.point", (10, 20, 30)), + ("code.function.return.value", "Position: (10, 20, 30)"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_set_parameter(self, setup_telemetry): + """Test decorator with async function and set parameters.""" + + @trace_function() + async def count_unique_async(items: set) -> int: + return len(items) + + result = await count_unique_async({10, 20, 30, 40, 50}) + assert result == 5 + + spans = self.exporter.get_spans_by_name("count_unique_async") + assert len(spans) == 1 + span = spans[0] + + # Sets are converted to strings, but we need to compare the actual set values + # since set string representation order is non-deterministic + assert span.attributes is not None + assert "code.function.parameter.items" in span.attributes + assert "code.function.return.value" in span.attributes + + # Convert the string back to a set for comparison + import ast + + items_str = span.attributes["code.function.parameter.items"] + assert isinstance(items_str, str) + items_value = ast.literal_eval(items_str) + assert items_value == {10, 20, 30, 40, 50} + assert span.attributes["code.function.return.value"] == 5 + + @pytest.mark.asyncio + async def test_async_function_with_exception(self, setup_telemetry): + """Test decorator records exception information in async functions.""" + + @trace_function() + async def divide_async(a: int, b: int) -> float: + return a / b + + with pytest.raises(ZeroDivisionError): + await divide_async(100, 0) + + spans = self.exporter.get_spans_by_name("divide_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.a", 100), + ("code.function.parameter.b", 0), + ("error.type", "ZeroDivisionError"), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + # Verify exception was recorded as an event + assert len(span.events) > 0 + exception_event = None + for event in span.events: + if event.name == "exception": + exception_event = event + break + assert exception_event is not None + + @pytest.mark.asyncio + async def test_async_function_with_mixed_parameters(self, setup_telemetry): + """Test decorator with async function and mixed parameter types.""" + + @trace_function() + async def process_data_async(name: str, count: int, active: bool, scores: list) -> dict: + return { + "name": name.upper(), + "count": count * 2, + "active": active, + "total": sum(scores), + } + + result = await process_data_async("async_test", 3, False, [100, 200, 300]) + assert result["name"] == "ASYNC_TEST" + assert result["count"] == 6 + assert result["total"] == 600 + + spans = self.exporter.get_spans_by_name("process_data_async") + assert len(spans) == 1 + span = spans[0] + + expected_result_str = str(result) + expected_attributes = [ + ("code.function.parameter.name", "async_test"), + ("code.function.parameter.count", 3), + ("code.function.parameter.active", False), + ("code.function.parameter.scores", [100, 200, 300]), + ("code.function.return.value", expected_result_str), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_with_default_parameters(self, setup_telemetry): + """Test decorator with async function using default parameters.""" + + @trace_function() + async def create_user_async(name: str, role: str = "user", active: bool = True) -> dict: + return {"name": name, "role": role, "active": active} + + result = await create_user_async("Charlie") + assert result["name"] == "Charlie" + assert result["role"] == "user" + assert result["active"] is True + + spans = self.exporter.get_spans_by_name("create_user_async") + assert len(spans) == 1 + span = spans[0] + + expected_result_str = str(result) + expected_attributes = [ + ("code.function.parameter.name", "Charlie"), + ("code.function.parameter.role", "user"), + ("code.function.parameter.active", True), + ("code.function.return.value", expected_result_str), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True + + @pytest.mark.asyncio + async def test_async_function_list_return_value(self, setup_telemetry): + """Test decorator with async function returning a list.""" + + @trace_function() + async def get_range_async(start: int, end: int) -> list: + return list(range(start, end)) + + result = await get_range_async(1, 6) + assert result == [1, 2, 3, 4, 5] + + spans = self.exporter.get_spans_by_name("get_range_async") + assert len(spans) == 1 + span = spans[0] + + expected_attributes = [ + ("code.function.parameter.start", 1), + ("code.function.parameter.end", 6), + ("code.function.return.value", [1, 2, 3, 4, 5]), + ] + attributes_match = GenAiTraceVerifier().check_decorator_span_attributes(span, expected_attributes) + assert attributes_match is True From 112c0be6f09edb24a19e7a25f733db3420435d6c Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 15:17:56 -0800 Subject: [PATCH 71/84] Increment package version after release of azure-ai-transcription (#45009) Co-authored-by: amber-yujueWang --- .../azure-ai-transcription/CHANGELOG.md | 12 +++++++++++- .../azure/ai/transcription/_version.py | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md b/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md index 8cfa85875e9e..db81944faddd 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md +++ b/sdk/cognitiveservices/azure-ai-transcription/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.0.0b4 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.0.0b3 (2026-02-04) ### Features Added @@ -20,4 +30,4 @@ ### Other Changes -- Initial version \ No newline at end of file +- Initial version diff --git a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py index c43fdbc2e239..22553b18fb7e 100644 --- a/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py +++ b/sdk/cognitiveservices/azure-ai-transcription/azure/ai/transcription/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b3" +VERSION = "1.0.0b4" From ca7840c9d5275b1ea301e4b374836f61a0bd5d62 Mon Sep 17 00:00:00 2001 From: Scott Beddall <45376673+scbedd@users.noreply.github.com> Date: Thu, 5 Feb 2026 15:38:34 -0800 Subject: [PATCH 72/84] filter out Versions that don't match the specifier type. if initial requirement is GA, then only include GA. Otherwise include all (#45043) --- eng/tox/install_depend_packages.py | 34 ++++++++++++++---------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/eng/tox/install_depend_packages.py b/eng/tox/install_depend_packages.py index 13303000dc43..1f5247280833 100644 --- a/eng/tox/install_depend_packages.py +++ b/eng/tox/install_depend_packages.py @@ -62,7 +62,7 @@ "azure-storage-file-datalake": {"azure-storage-blob": "12.22.0"}, "azure-cosmos": {"azure-core": "1.30.0"}, "azure-appconfiguration-provider": {"azure-appconfiguration": "1.7.2"}, - "azure-ai-evaluation": {"aiohttp": "3.8.6"} + "azure-ai-evaluation": {"aiohttp": "3.8.6"}, } MAXIMUM_VERSION_SPECIFIC_OVERRIDES = {} @@ -73,16 +73,8 @@ ">=3.14.0": { "typing-extensions": "4.15.0", }, - ">=3.12.0": { - "azure-core": "1.23.1", - "aiohttp": "3.9.0", - "six": "1.16.0", - "requests": "2.30.0" - }, - ">=3.13.0": { - "typing-extensions": "4.13.0", - "aiohttp": "3.10.6" - } + ">=3.12.0": {"azure-core": "1.23.1", "aiohttp": "3.9.0", "six": "1.16.0", "requests": "2.30.0"}, + ">=3.13.0": {"typing-extensions": "4.13.0", "aiohttp": "3.10.6"}, } PLATFORM_SPECIFIC_MAXIMUM_OVERRIDES = {} @@ -188,9 +180,7 @@ def process_bounded_versions(originating_pkg_name: str, pkg_name: str, versions: # lower bound general if pkg_name in MINIMUM_VERSION_GENERIC_OVERRIDES: - versions = [ - v for v in versions if Version(v) >= Version(MINIMUM_VERSION_GENERIC_OVERRIDES[pkg_name]) - ] + versions = [v for v in versions if Version(v) >= Version(MINIMUM_VERSION_GENERIC_OVERRIDES[pkg_name])] # lower bound platform-specific for platform_bound in PLATFORM_SPECIFIC_MINIMUM_OVERRIDES.keys(): @@ -213,9 +203,7 @@ def process_bounded_versions(originating_pkg_name: str, pkg_name: str, versions: # upper bound general if pkg_name in MAXIMUM_VERSION_GENERIC_OVERRIDES: - versions = [ - v for v in versions if Version(v) <= Version(MAXIMUM_VERSION_GENERIC_OVERRIDES[pkg_name]) - ] + versions = [v for v in versions if Version(v) <= Version(MAXIMUM_VERSION_GENERIC_OVERRIDES[pkg_name])] # upper bound platform for platform_bound in PLATFORM_SPECIFIC_MAXIMUM_OVERRIDES.keys(): @@ -256,11 +244,22 @@ def process_requirement(req, dependency_type, orig_pkg_name): ) return "" + # if the specifier includes preview versions, then we can resolve preview versions + # otherwise, we should filter them out + allows_prereleases = spec is not None and spec.prereleases is True + # get available versions on PyPI client = PyPIClient() versions = [str(v) for v in client.get_ordered_versions(pkg_name, True)] logging.info("Versions available on PyPI for %s: %s", pkg_name, versions) + # prepass filter before choosing a latest or minimum, eliminate prerelease versions if they are not allowed based on the specifier + if not allows_prereleases: + versions = [v for v in versions if not Version(v).is_prerelease] + logging.info( + "Filtered out pre-release versions for %s based on specifier. Remaining versions: %s", pkg_name, versions + ) + # think of the various versions that come back from pypi as the top of a funnel # We apply generic overrides -> platform specific overrides -> package specific overrides versions = process_bounded_versions(orig_pkg_name, pkg_name, versions) @@ -418,5 +417,4 @@ def install_packages(packages, req_file): logging.error("Invalid arguments. Please make sure target directory and working directory are valid path") sys.exit(1) - install_dependent_packages(setup_path, args.dependency_type, args.work_dir) From e9c7451cc627e283db461e128d02bc094fb71c93 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 5 Feb 2026 18:58:59 -0500 Subject: [PATCH 73/84] [Cosmos] Port None handling fix for database_account parameter (#44987) * Initial plan * Port None handling changes from PR #44939 to main branch Co-authored-by: simorenoh <30335873+simorenoh@users.noreply.github.com> * Update sdk/cosmos/azure-cosmos/CHANGELOG.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Apply suggestion from @simorenoh --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: simorenoh <30335873+simorenoh@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos/CHANGELOG.md | 1 + .../azure/cosmos/_global_endpoint_manager.py | 4 + .../aio/_global_endpoint_manager_async.py | 4 +- .../azure-cosmos/tests/test_health_check.py | 63 ++++++++++ .../tests/test_health_check_async.py | 112 +++++++++++++++++- .../azure-cosmos/tests/test_multimaster.py | 38 +++--- 6 files changed, 198 insertions(+), 24 deletions(-) diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 5dea0816d2fa..87330e0f8567 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -8,6 +8,7 @@ #### Bugs Fixed * Fixed bug where sdk was encountering a timeout issue caused by infinite recursion during the 410 (Gone) error. See [PR 44770](https://github.com/Azure/azure-sdk-for-python/pull/44770) +* Fixed crash in sync and async clients when `force_refresh_on_startup` was set to `None`, which could surface as `AttributeError: 'NoneType' object has no attribute '_WritableLocations'` during region discovery when `database_account` was `None`. See [PR 44987](https://github.com/Azure/azure-sdk-for-python/pull/44987) #### Other Changes * Added tests for multi-language support for full text search. See [PR 44254](https://github.com/Azure/azure-sdk-for-python/pull/44254) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py index e00872206d13..546d75194a33 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py @@ -174,6 +174,10 @@ def _refresh_endpoint_list_private(self, database_account=None, **kwargs): # background full refresh (database account + health checks) self._start_background_refresh(self._refresh_database_account_and_health, kwargs) else: + # Fetch database account if not provided or explicitly None + # This ensures callers can pass None and still get correct behavior + if database_account is None: + database_account = self._GetDatabaseAccount(**kwargs) self.location_cache.perform_on_database_account_read(database_account) self._start_background_refresh(self._endpoints_health_check, kwargs) self.startup = False diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py index 5d22a947e1b3..dc989df69cd3 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py @@ -178,7 +178,9 @@ async def _refresh_endpoint_list_private(self, database_account=None, **kwargs): # in background self.refresh_task = asyncio.create_task(self._refresh_database_account_and_health()) else: - if not self._aenter_used: + # Fetch database account if not provided via async with pattern OR if explicitly None + # This ensures callers can pass None and still get correct behavior + if not self._aenter_used or database_account is None: database_account = await self._GetDatabaseAccount(**kwargs) self.location_cache.perform_on_database_account_read(database_account) # this will perform only calls to check endpoint health diff --git a/sdk/cosmos/azure-cosmos/tests/test_health_check.py b/sdk/cosmos/azure-cosmos/tests/test_health_check.py index 584db862e76a..6f31c621cf66 100644 --- a/sdk/cosmos/azure-cosmos/tests/test_health_check.py +++ b/sdk/cosmos/azure-cosmos/tests/test_health_check.py @@ -155,5 +155,68 @@ def __call__(self, endpoint): db_acc.ConsistencyPolicy = {"defaultConsistencyLevel": "Session"} return db_acc + + def test_force_refresh_on_startup_with_none_should_fetch_database_account(self, setup): + """Verifies that calling force_refresh_on_startup(None) fetches the database account + instead of crashing with AttributeError on NoneType._WritableLocations. + """ + self.original_getDatabaseAccountStub = _global_endpoint_manager._GlobalEndpointManager._GetDatabaseAccountStub + mock_get_db_account = self.MockGetDatabaseAccount(REGIONS) + _global_endpoint_manager._GlobalEndpointManager._GetDatabaseAccountStub = mock_get_db_account + + try: + client = CosmosClient(self.host, self.masterKey, preferred_locations=REGIONS) + gem = client.client_connection._global_endpoint_manager + + # Simulate the startup state + gem.startup = True + gem.refresh_needed = True + + # This should NOT crash - it should fetch the database account + gem.force_refresh_on_startup(None) + + # Verify the location cache was properly populated + read_contexts = gem.location_cache.read_regional_routing_contexts + assert len(read_contexts) > 0, "Location cache should have read endpoints after startup refresh" + + finally: + _global_endpoint_manager._GlobalEndpointManager._GetDatabaseAccountStub = self.original_getDatabaseAccountStub + + def test_force_refresh_on_startup_with_valid_account_uses_provided_account(self, setup): + """Verifies that when a valid database account is provided to force_refresh_on_startup, + it uses that account directly without making another network call. + """ + self.original_getDatabaseAccountStub = _global_endpoint_manager._GlobalEndpointManager._GetDatabaseAccountStub + call_counter = {'count': 0} + + def counting_mock(self_gem, endpoint, **kwargs): + call_counter['count'] += 1 + return self.MockGetDatabaseAccount(REGIONS)(endpoint) + + _global_endpoint_manager._GlobalEndpointManager._GetDatabaseAccountStub = counting_mock + + try: + client = CosmosClient(self.host, self.masterKey, preferred_locations=REGIONS) + gem = client.client_connection._global_endpoint_manager + + # Get a valid database account first + db_account = gem._GetDatabaseAccount() + initial_call_count = call_counter['count'] + + # Reset startup state + gem.startup = True + gem.refresh_needed = True + + # Call with valid account - should NOT make another network call + gem.force_refresh_on_startup(db_account) + + # Since we provided a valid account, no additional GetDatabaseAccount call should be made + assert call_counter['count'] == initial_call_count, \ + "Should not call _GetDatabaseAccount when valid account is provided" + + finally: + _global_endpoint_manager._GlobalEndpointManager._GetDatabaseAccountStub = self.original_getDatabaseAccountStub + + if __name__ == '__main__': unittest.main() diff --git a/sdk/cosmos/azure-cosmos/tests/test_health_check_async.py b/sdk/cosmos/azure-cosmos/tests/test_health_check_async.py index 716556b0fda2..87aa65b06694 100644 --- a/sdk/cosmos/azure-cosmos/tests/test_health_check_async.py +++ b/sdk/cosmos/azure-cosmos/tests/test_health_check_async.py @@ -89,7 +89,11 @@ async def test_health_check_failure_startup_async(self, setup): client = CosmosClient(self.host, self.masterKey, preferred_locations=REGIONS) # this will setup the location cache await client.__aenter__() - await asyncio.sleep(10) # give some time for the background health check to complete + # Poll until the background health check marks endpoints as unavailable + start_time = time.time() + while (len(client.client_connection._global_endpoint_manager.location_cache.location_unavailability_info_by_endpoint) < len(REGIONS) + and time.time() - start_time < 10): + await asyncio.sleep(0.1) finally: _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = self.original_getDatabaseAccountStub expected_endpoints = [] @@ -277,5 +281,111 @@ async def __call__(self, endpoint): db_acc.ConsistencyPolicy = {"defaultConsistencyLevel": "Session"} return db_acc + + async def test_force_refresh_on_startup_with_none_should_fetch_database_account(self, setup): + """Verifies that calling force_refresh_on_startup(None) fetches the database account + instead of crashing with AttributeError on NoneType._WritableLocations. + """ + self.original_getDatabaseAccountStub = _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub + mock_get_db_account = self.MockGetDatabaseAccount(REGIONS) + _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = mock_get_db_account + + try: + client = CosmosClient(self.host, self.masterKey, preferred_locations=REGIONS) + await client.__aenter__() + gem = client.client_connection._global_endpoint_manager + + # Simulate the startup state + gem.startup = True + gem.refresh_needed = True + gem._aenter_used = True # Simulate that __aenter__ was used + + # This should NOT crash - it should fetch the database account + await gem.force_refresh_on_startup(None) + + # Verify the location cache was properly populated + read_contexts = gem.location_cache.read_regional_routing_contexts + assert len(read_contexts) > 0, "Location cache should have read endpoints after startup refresh" + + await client.close() + finally: + _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = self.original_getDatabaseAccountStub + + async def test_force_refresh_on_startup_with_valid_account_uses_provided_account(self, setup): + """Verifies that when a valid database account is provided to force_refresh_on_startup, + it uses that account directly without making another network call. + """ + self.original_getDatabaseAccountStub = _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub + call_counter = {'count': 0} + + async def counting_mock(self_gem, endpoint, **kwargs): + call_counter['count'] += 1 + return await self.MockGetDatabaseAccount(REGIONS)(endpoint) + + _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = counting_mock + + try: + client = CosmosClient(self.host, self.masterKey, preferred_locations=REGIONS) + await client.__aenter__() + gem = client.client_connection._global_endpoint_manager + + # Get a valid database account first + db_account = await gem._GetDatabaseAccount() + initial_call_count = call_counter['count'] + + # Reset startup state + gem.startup = True + gem.refresh_needed = True + gem._aenter_used = True + + # Call with valid account - should NOT make another network call + await gem.force_refresh_on_startup(db_account) + + # Since we provided a valid account, no additional GetDatabaseAccount call should be made + + assert call_counter['count'] == initial_call_count, \ + "Should not call _GetDatabaseAccount when valid account is provided" + + await client.close() + finally: + _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = self.original_getDatabaseAccountStub + + async def test_aenter_used_flag_with_none_still_fetches_account(self, setup): + """Verifies that even when _aenter_used=True, passing None to force_refresh_on_startup + still fetches the database account. + """ + self.original_getDatabaseAccountStub = _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub + fetch_was_called = {'called': False} + + async def tracking_mock(self_gem, endpoint, **kwargs): + fetch_was_called['called'] = True + return await self.MockGetDatabaseAccount(REGIONS)(endpoint) + + _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = tracking_mock + + try: + client = CosmosClient(self.host, self.masterKey, preferred_locations=REGIONS) + await client.__aenter__() + gem = client.client_connection._global_endpoint_manager + + # Reset state to simulate the buggy scenario + gem.startup = True + gem.refresh_needed = True + gem._aenter_used = True # This was causing the bug to skip fetching + fetch_was_called['called'] = False # Reset tracking + + # Call with None - should still fetch database account (this is the fix) + await gem.force_refresh_on_startup(None) + + # This ensures that even with _aenter_used=True, if database_account is None, + # it fetches the database account + assert fetch_was_called['called'], \ + "With _aenter_used=True and database_account=None, should still fetch database account" + + await client.close() + finally: + _global_endpoint_manager_async._GlobalEndpointManager._GetDatabaseAccountStub = self.original_getDatabaseAccountStub + + if __name__ == '__main__': unittest.main() diff --git a/sdk/cosmos/azure-cosmos/tests/test_multimaster.py b/sdk/cosmos/azure-cosmos/tests/test_multimaster.py index 94cd70e2982b..10da5c8bb63e 100644 --- a/sdk/cosmos/azure-cosmos/tests/test_multimaster.py +++ b/sdk/cosmos/azure-cosmos/tests/test_multimaster.py @@ -34,6 +34,7 @@ def test_tentative_writes_header_not_present(self): TestMultiMaster.connectionPolicy.UseMultipleWriteLocations = False def _validate_tentative_write_headers(self): + self.counter = 0 # Reset counter for each test run self.OriginalExecuteFunction = _retry_utility.ExecuteFunction _retry_utility.ExecuteFunction = self._MockExecuteFunction try: @@ -83,30 +84,23 @@ def _validate_tentative_write_headers(self): partition_key='pk' ) - print(len(self.last_headers)) is_allow_tentative_writes_set = self.EnableMultipleWritableLocations is True - # Create Document - Makes one initial call to fetch collection - self.assertEqual(self.last_headers[0], is_allow_tentative_writes_set) - self.assertEqual(self.last_headers[1], is_allow_tentative_writes_set) - - # Create Stored procedure - self.assertEqual(self.last_headers[2], is_allow_tentative_writes_set) - - # Execute Stored procedure - self.assertEqual(self.last_headers[3], is_allow_tentative_writes_set) - - # Read Document - self.assertEqual(self.last_headers[4], is_allow_tentative_writes_set) - - # Replace Document - self.assertEqual(self.last_headers[5], is_allow_tentative_writes_set) - - # Upsert Document - self.assertEqual(self.last_headers[6], is_allow_tentative_writes_set) - - # Delete Document - self.assertEqual(self.last_headers[7], is_allow_tentative_writes_set) + # Count operations with the tentative writes header + headers_with_tentative_writes = sum(1 for h in self.last_headers if h) + + if is_allow_tentative_writes_set: + # When multi-write is enabled, at least 6 write operations should have the header: + # create_item, create_stored_procedure, execute_stored_procedure, + # replace_item, upsert_item, delete_item + self.assertGreaterEqual(headers_with_tentative_writes, 6, + f"Expected at least 6 write operations with tentative writes header, " + f"got {headers_with_tentative_writes}") + else: + # When multi-write is disabled, no operations should have the header + self.assertEqual(headers_with_tentative_writes, 0, + f"Expected 0 operations with tentative writes header, " + f"got {headers_with_tentative_writes}") finally: _retry_utility.ExecuteFunction = self.OriginalExecuteFunction From e7baa6cb4bafbb8c3d5039c230359ed7e5f2a315 Mon Sep 17 00:00:00 2001 From: Jayesh Tanna Date: Fri, 6 Feb 2026 06:22:39 +0530 Subject: [PATCH 74/84] parameterize the finetuning test cases (#44996) * Parametrizing the finetuning test cases * removed extra decorator * applying black * updating assetjson file * updating test cases * using liveandrecording fun * adding new env * updating msg --------- Co-authored-by: Jayesh Tanna --- sdk/ai/azure-ai-projects/.env.template | 5 +- sdk/ai/azure-ai-projects/assets.json | 2 +- .../tests/finetuning/test_finetuning.py | 454 ++++++++-------- .../tests/finetuning/test_finetuning_async.py | 484 ++++++++++-------- sdk/ai/azure-ai-projects/tests/test_base.py | 9 + 5 files changed, 530 insertions(+), 424 deletions(-) diff --git a/sdk/ai/azure-ai-projects/.env.template b/sdk/ai/azure-ai-projects/.env.template index 023b15d3bb74..ca5a9a9beb85 100644 --- a/sdk/ai/azure-ai-projects/.env.template +++ b/sdk/ai/azure-ai-projects/.env.template @@ -64,4 +64,7 @@ COMPLETED_OSS_MODEL_SFT_FINE_TUNING_JOB_ID= RUNNING_FINE_TUNING_JOB_ID= PAUSED_FINE_TUNING_JOB_ID= AZURE_SUBSCRIPTION_ID= -AZURE_RESOURCE_GROUP= \ No newline at end of file +AZURE_RESOURCE_GROUP= + +# Set to true to run extended finetuning live tests +RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=false \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/assets.json b/sdk/ai/azure-ai-projects/assets.json index af8c0b06a8c4..b16ab096305e 100644 --- a/sdk/ai/azure-ai-projects/assets.json +++ b/sdk/ai/azure-ai-projects/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/ai/azure-ai-projects", - "Tag": "python/ai/azure-ai-projects_92b666ecb8" + "Tag": "python/ai/azure-ai-projects_8d150306ae" } diff --git a/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning.py b/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning.py index 88dfd1c265b4..6a265f3ada48 100644 --- a/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning.py +++ b/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning.py @@ -4,8 +4,8 @@ # Licensed under the MIT License. # ------------------------------------ -import pytest import os +import pytest import time from pathlib import Path from test_base import ( @@ -17,12 +17,49 @@ STANDARD_TRAINING_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, DEVELOPER_TIER_TRAINING_TYPE, + SUPERVISED_METHOD_TYPE, + DPO_METHOD_TYPE, + REINFORCEMENT_METHOD_TYPE, + OPENAI_MODEL_TYPE, + OSS_MODEL_TYPE, ) -from devtools_testutils import recorded_by_proxy, RecordedTransport, is_live +from devtools_testutils import recorded_by_proxy, RecordedTransport, is_live, is_live_and_not_recording from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient from azure.mgmt.cognitiveservices.models import Deployment, DeploymentProperties, DeploymentModel, Sku +# Intermediate decorators required for pytest.mark.parametrize with recorded_by_proxy +# See: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/test_proxy_troubleshooting.md#special-case-using-pytestmarkparametrize-with-recorded-tests +def _pass_cancel_args(fn): + def _wrapper(test_class, job_type, model_type, training_type, expected_method_type, **kwargs): + fn(test_class, job_type, model_type, training_type, expected_method_type, **kwargs) + + return _wrapper + + +def _pass_create_args(fn): + def _wrapper(test_class, job_type, model_type, training_type, **kwargs): + fn(test_class, job_type, model_type, training_type, **kwargs) + + return _wrapper + + +def _pass_deploy_args(fn): + def _wrapper( + test_class, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ): + fn(test_class, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs) + + return _wrapper + + +def _pass_retrieve_args(fn): + def _wrapper(test_class, job_type, expected_method_type, **kwargs): + fn(test_class, job_type, expected_method_type, **kwargs) + + return _wrapper + + class TestFineTuning(TestBase): def _create_sft_finetuning_job(self, openai_client, train_file_id, validation_file_id, training_type, model_type): @@ -31,7 +68,7 @@ def _create_sft_finetuning_job(self, openai_client, train_file_id, validation_fi validation_file=validation_file_id, model=self.test_finetuning_params["sft"][model_type]["model_name"], method={ - "type": "supervised", + "type": SUPERVISED_METHOD_TYPE, "supervised": { "hyperparameters": { "n_epochs": self.test_finetuning_params["n_epochs"], @@ -49,7 +86,7 @@ def _create_dpo_finetuning_job(self, openai_client, train_file_id, validation_fi validation_file=validation_file_id, model=self.test_finetuning_params["dpo"][model_type]["model_name"], method={ - "type": "dpo", + "type": DPO_METHOD_TYPE, "dpo": { "hyperparameters": { "n_epochs": self.test_finetuning_params["n_epochs"], @@ -80,7 +117,7 @@ def _create_rft_finetuning_job(self, openai_client, train_file_id, validation_fi validation_file=validation_file_id, model=self.test_finetuning_params["rft"][model_type]["model_name"], method={ - "type": "reinforcement", + "type": REINFORCEMENT_METHOD_TYPE, "reinforcement": { "grader": grader, "hyperparameters": { @@ -367,148 +404,155 @@ def _test_deploy_and_infer_helper( f"[{test_prefix}] Successfully completed deployment and inference test for job: {completed_job_id}" ) - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_finetuning_create_job_openai_standard(self, **kwargs): - self._test_sft_create_job_helper("openai", STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_finetuning_create_job_openai_developer(self, **kwargs): - self._test_sft_create_job_helper("openai", DEVELOPER_TIER_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_finetuning_create_job_openai_globalstandard(self, **kwargs): - self._test_sft_create_job_helper("openai", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_finetuning_create_job_oss_globalstandard(self, **kwargs): - self._test_sft_create_job_helper("oss", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_dpo_finetuning_create_job_openai_standard(self, **kwargs): - self._test_dpo_create_job_helper("openai", STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_dpo_finetuning_create_job_openai__developer(self, **kwargs): - self._test_dpo_create_job_helper("openai", DEVELOPER_TIER_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_dpo_finetuning_create_job_openai_globalstandard(self, **kwargs): - self._test_dpo_create_job_helper("openai", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_rft_finetuning_create_job_openai_standard(self, **kwargs): - self._test_rft_create_job_helper("openai", STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_rft_finetuning_create_job_openai_globalstandard(self, **kwargs): - self._test_rft_create_job_helper("openai", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_rft_finetuning_create_job_openai_developer(self, **kwargs): - self._test_rft_create_job_helper("openai", DEVELOPER_TIER_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_retrieve_sft_job(self, **kwargs): + @pytest.mark.parametrize( + "job_type,model_type,training_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE), + ], + ) + @servicePreparer() + @_pass_create_args + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_create_job(self, job_type, model_type, training_type, **kwargs): + if job_type == SFT_JOB_TYPE: + self._test_sft_create_job_helper(model_type, training_type, **kwargs) + elif job_type == DPO_JOB_TYPE: + self._test_dpo_create_job_helper(model_type, training_type, **kwargs) + elif job_type == RFT_JOB_TYPE: + self._test_rft_create_job_helper(model_type, training_type, **kwargs) + else: + raise ValueError(f"Unsupported job type: {job_type}") + + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_type,model_type,training_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE), + (SFT_JOB_TYPE, OSS_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE), + ], + ) + @servicePreparer() + @_pass_create_args + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_create_job_live_extended(self, job_type, model_type, training_type, **kwargs): + if job_type == SFT_JOB_TYPE: + self._test_sft_create_job_helper(model_type, training_type, **kwargs) + elif job_type == DPO_JOB_TYPE: + self._test_dpo_create_job_helper(model_type, training_type, **kwargs) + elif job_type == RFT_JOB_TYPE: + self._test_rft_create_job_helper(model_type, training_type, **kwargs) + else: + raise ValueError(f"Unsupported job type: {job_type}") + + @servicePreparer() + @pytest.mark.parametrize( + "job_type,expected_method_type", + [ + (SFT_JOB_TYPE, SUPERVISED_METHOD_TYPE), + ], + ) + @_pass_retrieve_args + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_retrieve_job(self, job_type, expected_method_type, **kwargs): with self.create_client(**kwargs) as project_client: with project_client.get_openai_client() as openai_client: - train_file, validation_file = self._upload_test_files(openai_client, SFT_JOB_TYPE) - - fine_tuning_job = self._create_sft_finetuning_job( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" - ) - print(f"[test_finetuning_retrieve_sft] Created job: {fine_tuning_job.id}") - - retrieved_job = openai_client.fine_tuning.jobs.retrieve(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_sft] Retrieved job: {retrieved_job.id}") - - TestBase.validate_fine_tuning_job(retrieved_job, expected_job_id=fine_tuning_job.id) - TestBase.assert_equal_or_not_none(retrieved_job.training_file, train_file.id) - TestBase.assert_equal_or_not_none(retrieved_job.validation_file, validation_file.id) - TestBase.assert_equal_or_not_none(retrieved_job.trainingType.lower(), STANDARD_TRAINING_TYPE.lower()) - assert retrieved_job.method is not None, "Method should not be None for SFT job" - TestBase.assert_equal_or_not_none(retrieved_job.method.type, "supervised") - assert ( - self.test_finetuning_params["sft"]["openai"]["model_name"] in retrieved_job.model - ), f"Expected model name {self.test_finetuning_params['sft']['openai']['model_name']} not found in {retrieved_job.model}" - - openai_client.fine_tuning.jobs.cancel(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_sft] Cancelled job: {fine_tuning_job.id}") - - self._cleanup_test_file(openai_client, train_file.id) - self._cleanup_test_file(openai_client, validation_file.id) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_retrieve_dpo_job(self, **kwargs): - with self.create_client(**kwargs) as project_client: - with project_client.get_openai_client() as openai_client: + train_file, validation_file = self._upload_test_files(openai_client, job_type) - train_file, validation_file = self._upload_test_files(openai_client, DPO_JOB_TYPE) + if job_type == SFT_JOB_TYPE: + fine_tuning_job = self._create_sft_finetuning_job( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == DPO_JOB_TYPE: + fine_tuning_job = self._create_dpo_finetuning_job( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == RFT_JOB_TYPE: + fine_tuning_job = self._create_rft_finetuning_job( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) - fine_tuning_job = self._create_dpo_finetuning_job( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" - ) - print(f"[test_finetuning_retrieve_dpo] Created job: {fine_tuning_job.id}") + print(f"[test_finetuning_retrieve_{job_type}] Created job: {fine_tuning_job.id}") retrieved_job = openai_client.fine_tuning.jobs.retrieve(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_dpo] Retrieved job: {retrieved_job.id}") + print(f"[test_finetuning_retrieve_{job_type}] Retrieved job: {retrieved_job.id}") TestBase.validate_fine_tuning_job(retrieved_job, expected_job_id=fine_tuning_job.id) TestBase.assert_equal_or_not_none(retrieved_job.training_file, train_file.id) TestBase.assert_equal_or_not_none(retrieved_job.validation_file, validation_file.id) TestBase.assert_equal_or_not_none(retrieved_job.trainingType.lower(), STANDARD_TRAINING_TYPE.lower()) - assert retrieved_job.method is not None, "Method should not be None for DPO job" - TestBase.assert_equal_or_not_none(retrieved_job.method.type, "dpo") + assert retrieved_job.method is not None, f"Method should not be None for {job_type} job" + TestBase.assert_equal_or_not_none(retrieved_job.method.type, expected_method_type) assert ( - self.test_finetuning_params["dpo"]["openai"]["model_name"] in retrieved_job.model - ), f"Expected model name {self.test_finetuning_params['dpo']['openai']['model_name']} not found in {retrieved_job.model}" + self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]["model_name"] in retrieved_job.model + ), f"Expected model name {self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]['model_name']} not found in {retrieved_job.model}" openai_client.fine_tuning.jobs.cancel(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_dpo] Cancelled job: {fine_tuning_job.id}") + print(f"[test_finetuning_retrieve_{job_type}] Cancelled job: {fine_tuning_job.id}") self._cleanup_test_file(openai_client, train_file.id) self._cleanup_test_file(openai_client, validation_file.id) - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_retrieve_rft_job(self, **kwargs): + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @servicePreparer() + @pytest.mark.parametrize( + "job_type,expected_method_type", + [ + (DPO_JOB_TYPE, DPO_METHOD_TYPE), + (RFT_JOB_TYPE, REINFORCEMENT_METHOD_TYPE), + ], + ) + @_pass_retrieve_args + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_retrieve_job_live_extended(self, job_type, expected_method_type, **kwargs): with self.create_client(**kwargs) as project_client: with project_client.get_openai_client() as openai_client: - train_file, validation_file = self._upload_test_files(openai_client, RFT_JOB_TYPE) + train_file, validation_file = self._upload_test_files(openai_client, job_type) - fine_tuning_job = self._create_rft_finetuning_job( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" - ) - print(f"[test_finetuning_retrieve_rft] Created job: {fine_tuning_job.id}") + if job_type == SFT_JOB_TYPE: + fine_tuning_job = self._create_sft_finetuning_job( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == DPO_JOB_TYPE: + fine_tuning_job = self._create_dpo_finetuning_job( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == RFT_JOB_TYPE: + fine_tuning_job = self._create_rft_finetuning_job( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + + print(f"[test_finetuning_retrieve_{job_type}_live] Created job: {fine_tuning_job.id}") retrieved_job = openai_client.fine_tuning.jobs.retrieve(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_rft] Retrieved job: {retrieved_job.id}") + print(f"[test_finetuning_retrieve_{job_type}_live] Retrieved job: {retrieved_job.id}") TestBase.validate_fine_tuning_job(retrieved_job, expected_job_id=fine_tuning_job.id) TestBase.assert_equal_or_not_none(retrieved_job.training_file, train_file.id) TestBase.assert_equal_or_not_none(retrieved_job.validation_file, validation_file.id) TestBase.assert_equal_or_not_none(retrieved_job.trainingType.lower(), STANDARD_TRAINING_TYPE.lower()) - assert retrieved_job.method is not None, "Method should not be None for RFT job" - TestBase.assert_equal_or_not_none(retrieved_job.method.type, "reinforcement") + assert retrieved_job.method is not None, f"Method should not be None for {job_type} job" + TestBase.assert_equal_or_not_none(retrieved_job.method.type, expected_method_type) assert ( - self.test_finetuning_params["rft"]["openai"]["model_name"] in retrieved_job.model - ), f"Expected model name {self.test_finetuning_params['rft']['openai']['model_name']} not found in {retrieved_job.model}" + self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]["model_name"] in retrieved_job.model + ), f"Expected model name {self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]['model_name']} not found in {retrieved_job.model}" openai_client.fine_tuning.jobs.cancel(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_rft] Cancelled job: {fine_tuning_job.id}") + print(f"[test_finetuning_retrieve_{job_type}_live] Cancelled job: {fine_tuning_job.id}") self._cleanup_test_file(openai_client, train_file.id) self._cleanup_test_file(openai_client, validation_file.id) @@ -531,55 +575,41 @@ def test_finetuning_list_jobs(self, **kwargs): print(f"[test_finetuning_list] Validated job {job.id} with status {job.status}") print(f"[test_finetuning_list] Successfully validated list functionality with {len(jobs_list)} jobs") + @pytest.mark.parametrize( + "job_type,model_type,training_type,expected_method_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + ], + ) @servicePreparer() + @_pass_cancel_args @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_cancel_job_openai_standard(self, **kwargs): - self._test_cancel_job_helper(SFT_JOB_TYPE, "openai", STANDARD_TRAINING_TYPE, "supervised", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_cancel_job_openai_globalstandard(self, **kwargs): - self._test_cancel_job_helper(SFT_JOB_TYPE, "openai", GLOBAL_STANDARD_TRAINING_TYPE, "supervised", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_cancel_job_openai_developer(self, **kwargs): - self._test_cancel_job_helper(SFT_JOB_TYPE, "openai", DEVELOPER_TIER_TRAINING_TYPE, "supervised", **kwargs) + def test_cancel_job(self, job_type, model_type, training_type, expected_method_type, **kwargs): + self._test_cancel_job_helper(job_type, model_type, training_type, expected_method_type, **kwargs) + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_type,model_type,training_type,expected_method_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + (SFT_JOB_TYPE, OSS_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE, DPO_METHOD_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, DPO_METHOD_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE, DPO_METHOD_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE, REINFORCEMENT_METHOD_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, REINFORCEMENT_METHOD_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE, REINFORCEMENT_METHOD_TYPE), + ], + ) @servicePreparer() + @_pass_cancel_args @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_sft_cancel_job_oss_globalstandard(self, **kwargs): - self._test_cancel_job_helper(SFT_JOB_TYPE, "oss", GLOBAL_STANDARD_TRAINING_TYPE, "supervised", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_dpo_cancel_job_openai_standard(self, **kwargs): - self._test_cancel_job_helper(DPO_JOB_TYPE, "openai", STANDARD_TRAINING_TYPE, "dpo", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_dpo_cancel_job_openai_globalstandard(self, **kwargs): - self._test_cancel_job_helper(DPO_JOB_TYPE, "openai", GLOBAL_STANDARD_TRAINING_TYPE, "dpo", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_dpo_cancel_job_openai_developer(self, **kwargs): - self._test_cancel_job_helper(DPO_JOB_TYPE, "openai", DEVELOPER_TIER_TRAINING_TYPE, "dpo", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_rft_cancel_job_openai_standard(self, **kwargs): - self._test_cancel_job_helper(RFT_JOB_TYPE, "openai", STANDARD_TRAINING_TYPE, "reinforcement", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_rft_cancel_job_openai_globalstandard(self, **kwargs): - self._test_cancel_job_helper(RFT_JOB_TYPE, "openai", GLOBAL_STANDARD_TRAINING_TYPE, "reinforcement", **kwargs) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_rft_cancel_job_openai_developer(self, **kwargs): - self._test_cancel_job_helper(RFT_JOB_TYPE, "openai", DEVELOPER_TIER_TRAINING_TYPE, "reinforcement", **kwargs) + def test_cancel_job_live_extended(self, job_type, model_type, training_type, expected_method_type, **kwargs): + self._test_cancel_job_helper(job_type, model_type, training_type, expected_method_type, **kwargs) @servicePreparer() @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) @@ -592,7 +622,7 @@ def test_finetuning_list_events(self, **kwargs): train_file, validation_file = self._upload_test_files(openai_client, SFT_JOB_TYPE) fine_tuning_job = self._create_sft_finetuning_job( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE ) print(f"[test_finetuning_list_events] Created job: {fine_tuning_job.id}") @@ -719,54 +749,76 @@ def test_finetuning_list_checkpoints(self, **kwargs): f"[test_finetuning_list_checkpoints] Successfully validated {len(checkpoints_list)} checkpoints for job: {completed_job_id}" ) - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_deploy_and_infer_oai_model_sft_job(self, **kwargs): - completed_job_id = kwargs.get("completed_oai_model_sft_fine_tuning_job_id") - self._test_deploy_and_infer_helper( - completed_job_id, - "OpenAI", - 50, - "test_finetuning_deploy_and_infer_oai_model_sft_job", - "Who invented the telephone?", - **kwargs, - ) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_deploy_and_infer_oai_model_rft_job(self, **kwargs): - completed_job_id = kwargs.get("completed_oai_model_rft_fine_tuning_job_id") - self._test_deploy_and_infer_helper( - completed_job_id, - "OpenAI", - 50, - "test_finetuning_deploy_and_infer_oai_model_rft_job", - "Target: 85 Numbers: [20, 4, 15, 10]. Find a mathematical expression using all numbers exactly once to reach the target.", - **kwargs, - ) - - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_deploy_and_infer_oai_model_dpo_job(self, **kwargs): - completed_job_id = kwargs.get("completed_oai_model_dpo_fine_tuning_job_id") + @pytest.mark.parametrize( + "job_id_env_var,deployment_format,deployment_capacity,test_prefix,inference_content", + [ + ( + "completed_oai_model_sft_fine_tuning_job_id", + "OpenAI", + 50, + "test_deploy_infer_oai_sft", + "Who invented the telephone?", + ), + ], + ) + @servicePreparer() + @_pass_deploy_args + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_deploy_and_infer_job( + self, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ): + completed_job_id = kwargs.get(job_id_env_var) self._test_deploy_and_infer_helper( completed_job_id, - "OpenAI", - 50, - "test_finetuning_deploy_and_infer_oai_model_dpo_job", - "What is the largest desert in the world?", + deployment_format, + deployment_capacity, + test_prefix, + inference_content, **kwargs, ) - @servicePreparer() - @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - def test_finetuning_deploy_and_infer_oss_model_sft_job(self, **kwargs): - completed_job_id = kwargs.get("completed_oss_model_sft_fine_tuning_job_id") + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_id_env_var,deployment_format,deployment_capacity,test_prefix,inference_content", + [ + ( + "completed_oai_model_rft_fine_tuning_job_id", + "OpenAI", + 50, + "test_deploy_infer_oai_rft", + "Target: 85 Numbers: [20, 4, 15, 10]. Find a mathematical expression using all numbers exactly once to reach the target.", + ), + ( + "completed_oai_model_dpo_fine_tuning_job_id", + "OpenAI", + 50, + "test_deploy_infer_oai_dpo", + "Explain machine learning in simple terms.", + ), + ( + "completed_oss_model_sft_fine_tuning_job_id", + "Mistral AI", + 50, + "test_deploy_infer_oss_sft", + "Who invented the telephone?", + ), + ], + ) + @servicePreparer() + @_pass_deploy_args + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_deploy_and_infer_job_live_extended( + self, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ): + completed_job_id = kwargs.get(job_id_env_var) self._test_deploy_and_infer_helper( completed_job_id, - "Mistral AI", - 50, - "test_finetuning_deploy_and_infer_oss_model_sft_job", - "Who invented the telephone?", + deployment_format, + deployment_capacity, + test_prefix, + inference_content, **kwargs, ) diff --git a/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning_async.py b/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning_async.py index b609c15eaf2a..06838474a2c9 100644 --- a/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning_async.py +++ b/sdk/ai/azure-ai-projects/tests/finetuning/test_finetuning_async.py @@ -4,8 +4,8 @@ # Licensed under the MIT License. # ------------------------------------ -import pytest import os +import pytest import asyncio from pathlib import Path from test_base import ( @@ -17,13 +17,52 @@ STANDARD_TRAINING_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, DEVELOPER_TIER_TRAINING_TYPE, + SUPERVISED_METHOD_TYPE, + DPO_METHOD_TYPE, + REINFORCEMENT_METHOD_TYPE, + OPENAI_MODEL_TYPE, + OSS_MODEL_TYPE, ) from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import is_live, RecordedTransport +from devtools_testutils import is_live, RecordedTransport, is_live_and_not_recording from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient as CognitiveServicesManagementClientAsync from azure.mgmt.cognitiveservices.models import Deployment, DeploymentProperties, DeploymentModel, Sku +# Intermediate decorator required for pytest.mark.parametrize with recorded_by_proxy_async +# See: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/test_proxy_troubleshooting.md#special-case-using-pytestmarkparametrize-with-recorded-tests +def _pass_create_args_async(fn): + async def _wrapper(test_class, job_type, model_type, training_type, **kwargs): + await fn(test_class, job_type, model_type, training_type, **kwargs) + + return _wrapper + + +def _pass_cancel_args_async(fn): + async def _wrapper(test_class, job_type, model_type, training_type, expected_method_type, **kwargs): + await fn(test_class, job_type, model_type, training_type, expected_method_type, **kwargs) + + return _wrapper + + +def _pass_deploy_args_async(fn): + async def _wrapper( + test_class, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ): + await fn( + test_class, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ) + + return _wrapper + + +def _pass_retrieve_args_async(fn): + async def _wrapper(test_class, job_type, expected_method_type, **kwargs): + await fn(test_class, job_type, expected_method_type, **kwargs) + + return _wrapper + + class TestFineTuningAsync(TestBase): async def _create_sft_finetuning_job_async( @@ -34,7 +73,7 @@ async def _create_sft_finetuning_job_async( validation_file=validation_file_id, model=self.test_finetuning_params["sft"][model_type]["model_name"], method={ - "type": "supervised", + "type": SUPERVISED_METHOD_TYPE, "supervised": { "hyperparameters": { "n_epochs": self.test_finetuning_params["n_epochs"], @@ -54,7 +93,7 @@ async def _create_dpo_finetuning_job_async( validation_file=validation_file_id, model=self.test_finetuning_params["dpo"][model_type]["model_name"], method={ - "type": "dpo", + "type": DPO_METHOD_TYPE, "dpo": { "hyperparameters": { "n_epochs": self.test_finetuning_params["n_epochs"], @@ -87,7 +126,7 @@ async def _create_rft_finetuning_job_async( validation_file=validation_file_id, model=self.test_finetuning_params["rft"][model_type]["model_name"], method={ - "type": "reinforcement", + "type": REINFORCEMENT_METHOD_TYPE, "reinforcement": { "grader": grader, "hyperparameters": { @@ -209,7 +248,7 @@ async def _test_sft_create_job_helper_async(self, model_type, training_type, **k ) # For OSS models, validate the specific model name - if model_type == "oss": + if model_type == OSS_MODEL_TYPE: TestBase.validate_fine_tuning_job( fine_tuning_job, expected_model=self.test_finetuning_params["sft"]["oss"]["model_name"] ) @@ -376,154 +415,159 @@ async def _test_deploy_and_infer_helper_async( f"[{test_prefix}] Successfully completed deployment and inference test for job: {completed_job_id}" ) - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_finetuning_create_job_openai_standard_async(self, **kwargs): - await self._test_sft_create_job_helper_async("openai", STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_finetuning_create_job_openai_globalstandard_async(self, **kwargs): - await self._test_sft_create_job_helper_async("openai", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_finetuning_create_job_openai_developer_async(self, **kwargs): - await self._test_sft_create_job_helper_async("openai", DEVELOPER_TIER_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_finetuning_create_job_oss_globalstandard_async(self, **kwargs): - await self._test_sft_create_job_helper_async("oss", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_dpo_finetuning_create_job_openai_standard_async(self, **kwargs): - await self._test_dpo_create_job_helper_async("openai", STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_dpo_finetuning_create_job_openai_globalstandard_async(self, **kwargs): - await self._test_dpo_create_job_helper_async("openai", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_dpo_finetuning_create_job_openai_developer_async(self, **kwargs): - await self._test_dpo_create_job_helper_async("openai", DEVELOPER_TIER_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_rft_finetuning_create_job_openai_standard_async(self, **kwargs): - await self._test_rft_create_job_helper_async("openai", STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_rft_finetuning_create_job_openai_globalstandard_async(self, **kwargs): - await self._test_rft_create_job_helper_async("openai", GLOBAL_STANDARD_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_rft_finetuning_create_job_openai_developer_async(self, **kwargs): - await self._test_rft_create_job_helper_async("openai", DEVELOPER_TIER_TRAINING_TYPE, **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_retrieve_sft_job_async(self, **kwargs): + @pytest.mark.parametrize( + "job_type,model_type,training_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE), + ], + ) + @servicePreparer() + @_pass_create_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_create_job_async(self, job_type, model_type, training_type, **kwargs): + if job_type == SFT_JOB_TYPE: + await self._test_sft_create_job_helper_async(model_type, training_type, **kwargs) + elif job_type == DPO_JOB_TYPE: + await self._test_dpo_create_job_helper_async(model_type, training_type, **kwargs) + elif job_type == RFT_JOB_TYPE: + await self._test_rft_create_job_helper_async(model_type, training_type, **kwargs) + else: + raise ValueError(f"Unsupported job type: {job_type}") + + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_type,model_type,training_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE), + (SFT_JOB_TYPE, OSS_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE), + ], + ) + @servicePreparer() + @_pass_create_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_create_job_async_live_extended(self, job_type, model_type, training_type, **kwargs): + if job_type == SFT_JOB_TYPE: + await self._test_sft_create_job_helper_async(model_type, training_type, **kwargs) + elif job_type == DPO_JOB_TYPE: + await self._test_dpo_create_job_helper_async(model_type, training_type, **kwargs) + elif job_type == RFT_JOB_TYPE: + await self._test_rft_create_job_helper_async(model_type, training_type, **kwargs) + else: + raise ValueError(f"Unsupported job type: {job_type}") + + @pytest.mark.parametrize( + "job_type,expected_method_type", + [ + (SFT_JOB_TYPE, SUPERVISED_METHOD_TYPE), + ], + ) + @servicePreparer() + @_pass_retrieve_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_retrieve_job_async(self, job_type, expected_method_type, **kwargs): project_client = self.create_async_client(**kwargs) openai_client = project_client.get_openai_client() async with project_client: - train_file, validation_file = await self._upload_test_files_async(openai_client, SFT_JOB_TYPE) - - fine_tuning_job = await self._create_sft_finetuning_job_async( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" - ) - print(f"[test_finetuning_retrieve_sft] Created job: {fine_tuning_job.id}") - - retrieved_job = await openai_client.fine_tuning.jobs.retrieve(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_sft] Retrieved job: {retrieved_job.id}") - - TestBase.validate_fine_tuning_job(retrieved_job, expected_job_id=fine_tuning_job.id) - TestBase.assert_equal_or_not_none(retrieved_job.training_file, train_file.id) - TestBase.assert_equal_or_not_none(retrieved_job.validation_file, validation_file.id) - TestBase.assert_equal_or_not_none(retrieved_job.trainingType.lower(), STANDARD_TRAINING_TYPE.lower()) - assert retrieved_job.method is not None, "Method should not be None for SFT job" - TestBase.assert_equal_or_not_none(retrieved_job.method.type, "supervised") - assert ( - self.test_finetuning_params["sft"]["openai"]["model_name"] in retrieved_job.model - ), f"Expected model name {self.test_finetuning_params['sft']['openai']['model_name']} not found in {retrieved_job.model}" - - await openai_client.fine_tuning.jobs.cancel(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_sft] Cancelled job: {fine_tuning_job.id}") - - await self._cleanup_test_file_async(openai_client, train_file.id) - await self._cleanup_test_file_async(openai_client, validation_file.id) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_retrieve_dpo_job_async(self, **kwargs): - project_client = self.create_async_client(**kwargs) - openai_client = project_client.get_openai_client() - - async with project_client: + train_file, validation_file = await self._upload_test_files_async(openai_client, job_type) - train_file, validation_file = await self._upload_test_files_async(openai_client, DPO_JOB_TYPE) + if job_type == SFT_JOB_TYPE: + fine_tuning_job = await self._create_sft_finetuning_job_async( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == DPO_JOB_TYPE: + fine_tuning_job = await self._create_dpo_finetuning_job_async( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == RFT_JOB_TYPE: + fine_tuning_job = await self._create_rft_finetuning_job_async( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) - fine_tuning_job = await self._create_dpo_finetuning_job_async( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" - ) - print(f"[test_finetuning_retrieve_dpo] Created job: {fine_tuning_job.id}") + print(f"[test_finetuning_retrieve_{job_type}] Created job: {fine_tuning_job.id}") retrieved_job = await openai_client.fine_tuning.jobs.retrieve(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_dpo] Retrieved job: {retrieved_job.id}") + print(f"[test_finetuning_retrieve_{job_type}] Retrieved job: {retrieved_job.id}") TestBase.validate_fine_tuning_job(retrieved_job, expected_job_id=fine_tuning_job.id) TestBase.assert_equal_or_not_none(retrieved_job.training_file, train_file.id) TestBase.assert_equal_or_not_none(retrieved_job.validation_file, validation_file.id) TestBase.assert_equal_or_not_none(retrieved_job.trainingType.lower(), STANDARD_TRAINING_TYPE.lower()) - assert retrieved_job.method is not None, "Method should not be None for DPO job" - TestBase.assert_equal_or_not_none(retrieved_job.method.type, "dpo") + assert retrieved_job.method is not None, f"Method should not be None for {job_type} job" + TestBase.assert_equal_or_not_none(retrieved_job.method.type, expected_method_type) assert ( - self.test_finetuning_params["dpo"]["openai"]["model_name"] in retrieved_job.model - ), f"Expected model name {self.test_finetuning_params['dpo']['openai']['model_name']} not found in {retrieved_job.model}" + self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]["model_name"] in retrieved_job.model + ), f"Expected model name {self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]['model_name']} not found in {retrieved_job.model}" await openai_client.fine_tuning.jobs.cancel(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_dpo] Cancelled job: {fine_tuning_job.id}") + print(f"[test_finetuning_retrieve_{job_type}] Cancelled job: {fine_tuning_job.id}") await self._cleanup_test_file_async(openai_client, train_file.id) await self._cleanup_test_file_async(openai_client, validation_file.id) - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_retrieve_rft_job_async(self, **kwargs): + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_type,expected_method_type", + [ + (DPO_JOB_TYPE, DPO_METHOD_TYPE), + (RFT_JOB_TYPE, REINFORCEMENT_METHOD_TYPE), + ], + ) + @servicePreparer() + @_pass_retrieve_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_retrieve_job_async_live_extended(self, job_type, expected_method_type, **kwargs): project_client = self.create_async_client(**kwargs) openai_client = project_client.get_openai_client() async with project_client: - train_file, validation_file = await self._upload_test_files_async(openai_client, RFT_JOB_TYPE) + train_file, validation_file = await self._upload_test_files_async(openai_client, job_type) - fine_tuning_job = await self._create_rft_finetuning_job_async( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" - ) - print(f"[test_finetuning_retrieve_rft] Created job: {fine_tuning_job.id}") + if job_type == SFT_JOB_TYPE: + fine_tuning_job = await self._create_sft_finetuning_job_async( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == DPO_JOB_TYPE: + fine_tuning_job = await self._create_dpo_finetuning_job_async( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + elif job_type == RFT_JOB_TYPE: + fine_tuning_job = await self._create_rft_finetuning_job_async( + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE + ) + + print(f"[test_finetuning_retrieve_{job_type}_live] Created job: {fine_tuning_job.id}") retrieved_job = await openai_client.fine_tuning.jobs.retrieve(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_rft] Retrieved job: {retrieved_job.id}") + print(f"[test_finetuning_retrieve_{job_type}_live] Retrieved job: {retrieved_job.id}") TestBase.validate_fine_tuning_job(retrieved_job, expected_job_id=fine_tuning_job.id) TestBase.assert_equal_or_not_none(retrieved_job.training_file, train_file.id) TestBase.assert_equal_or_not_none(retrieved_job.validation_file, validation_file.id) TestBase.assert_equal_or_not_none(retrieved_job.trainingType.lower(), STANDARD_TRAINING_TYPE.lower()) - assert retrieved_job.method is not None, "Method should not be None for RFT job" - TestBase.assert_equal_or_not_none(retrieved_job.method.type, "reinforcement") + assert retrieved_job.method is not None, f"Method should not be None for {job_type} job" + TestBase.assert_equal_or_not_none(retrieved_job.method.type, expected_method_type) assert ( - self.test_finetuning_params["rft"]["openai"]["model_name"] in retrieved_job.model - ), f"Expected model name {self.test_finetuning_params['rft']['openai']['model_name']} not found in {retrieved_job.model}" + self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]["model_name"] in retrieved_job.model + ), f"Expected model name {self.test_finetuning_params[job_type][OPENAI_MODEL_TYPE]['model_name']} not found in {retrieved_job.model}" await openai_client.fine_tuning.jobs.cancel(fine_tuning_job.id) - print(f"[test_finetuning_retrieve_rft] Cancelled job: {fine_tuning_job.id}") + print(f"[test_finetuning_retrieve_{job_type}_live] Cancelled job: {fine_tuning_job.id}") await self._cleanup_test_file_async(openai_client, train_file.id) await self._cleanup_test_file_async(openai_client, validation_file.id) @@ -551,67 +595,43 @@ async def test_finetuning_list_jobs_async(self, **kwargs): print(f"[test_finetuning_list] Validated job {job.id} with status {job.status}") print(f"[test_finetuning_list] Successfully validated list functionality with {len(jobs_list)} jobs") - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_cancel_job_openai_standard_async(self, **kwargs): - await self._test_cancel_job_helper_async(SFT_JOB_TYPE, "openai", STANDARD_TRAINING_TYPE, "supervised", **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_cancel_job_openai_developer_async(self, **kwargs): - await self._test_cancel_job_helper_async( - SFT_JOB_TYPE, "openai", DEVELOPER_TIER_TRAINING_TYPE, "supervised", **kwargs - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_cancel_job_openai_globalstandard_async(self, **kwargs): - await self._test_cancel_job_helper_async( - SFT_JOB_TYPE, "openai", GLOBAL_STANDARD_TRAINING_TYPE, "supervised", **kwargs - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_sft_cancel_job_oss_globalstandard_async(self, **kwargs): - await self._test_cancel_job_helper_async( - SFT_JOB_TYPE, "oss", GLOBAL_STANDARD_TRAINING_TYPE, "supervised", **kwargs - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_dpo_cancel_job_openai_standard_async(self, **kwargs): - await self._test_cancel_job_helper_async(DPO_JOB_TYPE, "openai", STANDARD_TRAINING_TYPE, "dpo", **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_dpo_cancel_job_openai_developer_async(self, **kwargs): - await self._test_cancel_job_helper_async(DPO_JOB_TYPE, "openai", DEVELOPER_TIER_TRAINING_TYPE, "dpo", **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_dpo_cancel_job_openai_globalstandard_async(self, **kwargs): - await self._test_cancel_job_helper_async(DPO_JOB_TYPE, "openai", GLOBAL_STANDARD_TRAINING_TYPE, "dpo", **kwargs) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_rft_cancel_job_openai_standard_async(self, **kwargs): - await self._test_cancel_job_helper_async( - RFT_JOB_TYPE, "openai", STANDARD_TRAINING_TYPE, "reinforcement", **kwargs - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_rft_cancel_job_openai_developer_async(self, **kwargs): - await self._test_cancel_job_helper_async( - RFT_JOB_TYPE, "openai", DEVELOPER_TIER_TRAINING_TYPE, "reinforcement", **kwargs - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_rft_cancel_job_openai_globalstandard_async(self, **kwargs): - await self._test_cancel_job_helper_async( - RFT_JOB_TYPE, "openai", GLOBAL_STANDARD_TRAINING_TYPE, "reinforcement", **kwargs - ) + @pytest.mark.parametrize( + "job_type,model_type,training_type,expected_method_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + ], + ) + @servicePreparer() + @_pass_cancel_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_cancel_job_async(self, job_type, model_type, training_type, expected_method_type, **kwargs): + await self._test_cancel_job_helper_async(job_type, model_type, training_type, expected_method_type, **kwargs) + + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_type,model_type,training_type,expected_method_type", + [ + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + (SFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + (SFT_JOB_TYPE, OSS_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, SUPERVISED_METHOD_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE, DPO_METHOD_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, DPO_METHOD_TYPE), + (DPO_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE, DPO_METHOD_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, STANDARD_TRAINING_TYPE, REINFORCEMENT_METHOD_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, GLOBAL_STANDARD_TRAINING_TYPE, REINFORCEMENT_METHOD_TYPE), + (RFT_JOB_TYPE, OPENAI_MODEL_TYPE, DEVELOPER_TIER_TRAINING_TYPE, REINFORCEMENT_METHOD_TYPE), + ], + ) + @servicePreparer() + @_pass_cancel_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_cancel_job_async_live_extended( + self, job_type, model_type, training_type, expected_method_type, **kwargs + ): + await self._test_cancel_job_helper_async(job_type, model_type, training_type, expected_method_type, **kwargs) @servicePreparer() @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) @@ -625,7 +645,7 @@ async def test_finetuning_list_events_async(self, **kwargs): train_file, validation_file = await self._upload_test_files_async(openai_client, SFT_JOB_TYPE) fine_tuning_job = await self._create_sft_finetuning_job_async( - openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, "openai" + openai_client, train_file.id, validation_file.id, STANDARD_TRAINING_TYPE, OPENAI_MODEL_TYPE ) print(f"[test_finetuning_list_events] Created job: {fine_tuning_job.id}") @@ -761,54 +781,76 @@ async def test_finetuning_list_checkpoints_async(self, **kwargs): f"[test_finetuning_list_checkpoints] Successfully validated {len(checkpoints_list)} checkpoints for job: {completed_job_id}" ) - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_deploy_and_infer_oai_model_sft_job_async(self, **kwargs): - completed_job_id = kwargs.get("completed_oai_model_sft_fine_tuning_job_id") - await self._test_deploy_and_infer_helper_async( - completed_job_id, - "OpenAI", - 50, - "test_finetuning_deploy_and_infer_oai_model_sft_job", - "Who invented the telephone?", - **kwargs, - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_deploy_and_infer_oai_model_rft_job_async(self, **kwargs): - completed_job_id = kwargs.get("completed_oai_model_rft_fine_tuning_job_id") - await self._test_deploy_and_infer_helper_async( - completed_job_id, - "OpenAI", - 50, - "test_finetuning_deploy_and_infer_oai_model_rft_job", - "Target: 85 Numbers: [20, 4, 15, 10]. Find a mathematical expression using all numbers exactly once to reach the target.", - **kwargs, - ) - - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_deploy_and_infer_oai_model_dpo_job_async(self, **kwargs): - completed_job_id = kwargs.get("completed_oai_model_dpo_fine_tuning_job_id") + @pytest.mark.parametrize( + "job_id_env_var,deployment_format,deployment_capacity,test_prefix,inference_content", + [ + ( + "completed_oai_model_sft_fine_tuning_job_id", + "OpenAI", + 50, + "test_deploy_infer_oai_sft", + "Who invented the telephone?", + ), + ], + ) + @servicePreparer() + @_pass_deploy_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_deploy_and_infer_job_async( + self, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ): + completed_job_id = kwargs.get(job_id_env_var) await self._test_deploy_and_infer_helper_async( completed_job_id, - "OpenAI", - 50, - "test_finetuning_deploy_and_infer_oai_model_dpo_job", - "What is the largest desert in the world?", + deployment_format, + deployment_capacity, + test_prefix, + inference_content, **kwargs, ) - @servicePreparer() - @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) - async def test_finetuning_deploy_and_infer_oss_model_sft_job_async(self, **kwargs): - completed_job_id = kwargs.get("completed_oss_model_sft_fine_tuning_job_id") + @pytest.mark.skipif( + not is_live_and_not_recording() or os.getenv("RUN_EXTENDED_FINE_TUNING_LIVE_TESTS", "false").lower() != "true", + reason="Skipped extended FT live tests. Those only run live, without recordings, when RUN_EXTENDED_FINE_TUNING_LIVE_TESTS=true", + ) + @pytest.mark.parametrize( + "job_id_env_var,deployment_format,deployment_capacity,test_prefix,inference_content", + [ + ( + "completed_oai_model_rft_fine_tuning_job_id", + "OpenAI", + 50, + "test_deploy_infer_oai_rft", + "Target: 85 Numbers: [20, 4, 15, 10]. Find a mathematical expression using all numbers exactly once to reach the target.", + ), + ( + "completed_oai_model_dpo_fine_tuning_job_id", + "OpenAI", + 50, + "test_deploy_infer_oai_dpo", + "Explain machine learning in simple terms.", + ), + ( + "completed_oss_model_sft_fine_tuning_job_id", + "Mistral AI", + 50, + "test_deploy_infer_oss_sft", + "Who invented the telephone?", + ), + ], + ) + @servicePreparer() + @_pass_deploy_args_async + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_deploy_and_infer_job_async_live_extended( + self, job_id_env_var, deployment_format, deployment_capacity, test_prefix, inference_content, **kwargs + ): + completed_job_id = kwargs.get(job_id_env_var) await self._test_deploy_and_infer_helper_async( completed_job_id, - "Mistral AI", - 50, - "test_finetuning_deploy_and_infer_oss_model_sft_job", - "Who invented the telephone?", + deployment_format, + deployment_capacity, + test_prefix, + inference_content, **kwargs, ) diff --git a/sdk/ai/azure-ai-projects/tests/test_base.py b/sdk/ai/azure-ai-projects/tests/test_base.py index 15cc8f131aae..b1b7e0e1d668 100644 --- a/sdk/ai/azure-ai-projects/tests/test_base.py +++ b/sdk/ai/azure-ai-projects/tests/test_base.py @@ -82,6 +82,15 @@ GLOBAL_STANDARD_TRAINING_TYPE: Final[str] = "GlobalStandard" DEVELOPER_TIER_TRAINING_TYPE: Final[str] = "developerTier" +# Method type constants +SUPERVISED_METHOD_TYPE: Final[str] = "supervised" +DPO_METHOD_TYPE: Final[str] = "dpo" +REINFORCEMENT_METHOD_TYPE: Final[str] = "reinforcement" + +# Model type constants +OPENAI_MODEL_TYPE: Final[str] = "openai" +OSS_MODEL_TYPE: Final[str] = "oss" + def patched_open_crlf_to_lf(*args, **kwargs): """ From b8707c30bd5576db3dcb42f84c4a4948e33a9f7f Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 18:39:48 -0800 Subject: [PATCH 75/84] [AutoRelease] t2-resource-2026-02-05-10067(can only be merged by SDK owner) (#45034) * remove folders that are split * regenerate locally * code and test * remove outdated files * Update CHANGELOG.md and bump version to 25.0.0 * Fix typos in CHANGELOG.md * Consolidate module separation changelog entries for clarity --------- Co-authored-by: Yuchao Yan Co-authored-by: azure-sdk --- .../azure-mgmt-resource/CHANGELOG.md | 11 +- .../azure-mgmt-resource/_metadata.json | 6 +- .../apiview-properties.json | 156 +- .../azure/mgmt/resource/__init__.py | 14 - .../azure/mgmt/resource/_version.py | 2 +- .../azure/mgmt/resource/changes/__init__.py | 32 - .../mgmt/resource/changes/_changes_client.py | 128 - .../mgmt/resource/changes/_configuration.py | 76 - .../azure/mgmt/resource/changes/_patch.py | 21 - .../mgmt/resource/changes/_utils/__init__.py | 6 - .../resource/changes/_utils/serialization.py | 2041 ---- .../azure/mgmt/resource/changes/_version.py | 8 - .../mgmt/resource/changes/aio/__init__.py | 29 - .../resource/changes/aio/_changes_client.py | 132 - .../resource/changes/aio/_configuration.py | 76 - .../azure/mgmt/resource/changes/aio/_patch.py | 21 - .../changes/aio/operations/__init__.py | 25 - .../changes/aio/operations/_operations.py | 238 - .../resource/changes/aio/operations/_patch.py | 21 - .../mgmt/resource/changes/models/__init__.py | 52 - .../changes/models/_changes_client_enums.py | 41 - .../resource/changes/models/_models_py3.py | 352 - .../mgmt/resource/changes/models/_patch.py | 21 - .../resource/changes/operations/__init__.py | 25 - .../changes/operations/_operations.py | 324 - .../resource/changes/operations/_patch.py | 21 - .../azure/mgmt/resource/changes/py.typed | 1 - .../mgmt/resource/databoundaries/__init__.py | 32 - .../resource/databoundaries/_configuration.py | 66 - .../_data_boundary_mgmt_client.py | 121 - .../mgmt/resource/databoundaries/_patch.py | 21 - .../databoundaries/_utils/__init__.py | 6 - .../databoundaries/_utils/serialization.py | 2041 ---- .../mgmt/resource/databoundaries/_version.py | 8 - .../resource/databoundaries/aio/__init__.py | 29 - .../databoundaries/aio/_configuration.py | 66 - .../aio/_data_boundary_mgmt_client.py | 125 - .../resource/databoundaries/aio/_patch.py | 21 - .../databoundaries/aio/operations/__init__.py | 25 - .../aio/operations/_operations.py | 299 - .../databoundaries/aio/operations/_patch.py | 21 - .../databoundaries/models/__init__.py | 52 - .../_data_boundary_mgmt_client_enums.py | 46 - .../databoundaries/models/_models_py3.py | 314 - .../resource/databoundaries/models/_patch.py | 21 - .../databoundaries/operations/__init__.py | 25 - .../databoundaries/operations/_operations.py | 373 - .../databoundaries/operations/_patch.py | 21 - .../mgmt/resource/databoundaries/py.typed | 1 - .../azure/mgmt/resource/features/__init__.py | 32 - .../mgmt/resource/features/_configuration.py | 75 - .../mgmt/resource/features/_feature_client.py | 136 - .../azure/mgmt/resource/features/_patch.py | 21 - .../mgmt/resource/features/_utils/__init__.py | 6 - .../resource/features/_utils/serialization.py | 2041 ---- .../mgmt/resource/features/_utils/utils.py | 25 - .../azure/mgmt/resource/features/_version.py | 8 - .../mgmt/resource/features/aio/__init__.py | 29 - .../resource/features/aio/_configuration.py | 75 - .../resource/features/aio/_feature_client.py | 140 - .../mgmt/resource/features/aio/_patch.py | 21 - .../features/aio/operations/__init__.py | 28 - .../features/aio/operations/_operations.py | 934 -- .../features/aio/operations/_patch.py | 21 - .../mgmt/resource/features/models/__init__.py | 58 - .../features/models/_feature_client_enums.py | 32 - .../resource/features/models/_models_py3.py | 522 - .../mgmt/resource/features/models/_patch.py | 21 - .../resource/features/operations/__init__.py | 28 - .../features/operations/_operations.py | 1235 -- .../resource/features/operations/_patch.py | 21 - .../azure/mgmt/resource/features/py.typed | 1 - .../azure/mgmt/resource/links/__init__.py | 32 - .../mgmt/resource/links/_configuration.py | 75 - .../resource/links/_management_link_client.py | 133 - .../azure/mgmt/resource/links/_patch.py | 21 - .../mgmt/resource/links/_utils/__init__.py | 6 - .../resource/links/_utils/serialization.py | 2041 ---- .../azure/mgmt/resource/links/_version.py | 8 - .../azure/mgmt/resource/links/aio/__init__.py | 29 - .../mgmt/resource/links/aio/_configuration.py | 75 - .../links/aio/_management_link_client.py | 137 - .../azure/mgmt/resource/links/aio/_patch.py | 21 - .../resource/links/aio/operations/__init__.py | 27 - .../links/aio/operations/_operations.py | 541 - .../resource/links/aio/operations/_patch.py | 21 - .../mgmt/resource/links/models/__init__.py | 39 - .../mgmt/resource/links/models/_models_py3.py | 257 - .../mgmt/resource/links/models/_patch.py | 21 - .../resource/links/operations/__init__.py | 27 - .../resource/links/operations/_operations.py | 679 -- .../mgmt/resource/links/operations/_patch.py | 21 - .../azure/mgmt/resource/links/py.typed | 1 - .../azure/mgmt/resource/locks/__init__.py | 32 - .../mgmt/resource/locks/_configuration.py | 75 - .../resource/locks/_management_lock_client.py | 136 - .../azure/mgmt/resource/locks/_patch.py | 21 - .../mgmt/resource/locks/_utils/__init__.py | 6 - .../resource/locks/_utils/serialization.py | 2041 ---- .../azure/mgmt/resource/locks/_version.py | 8 - .../azure/mgmt/resource/locks/aio/__init__.py | 29 - .../mgmt/resource/locks/aio/_configuration.py | 75 - .../locks/aio/_management_lock_client.py | 140 - .../azure/mgmt/resource/locks/aio/_patch.py | 21 - .../resource/locks/aio/operations/__init__.py | 27 - .../locks/aio/operations/_operations.py | 1590 --- .../resource/locks/aio/operations/_patch.py | 21 - .../mgmt/resource/locks/models/__init__.py | 42 - .../models/_management_lock_client_enums.py | 21 - .../mgmt/resource/locks/models/_models_py3.py | 231 - .../mgmt/resource/locks/models/_patch.py | 21 - .../resource/locks/operations/__init__.py | 27 - .../resource/locks/operations/_operations.py | 2117 ---- .../mgmt/resource/locks/operations/_patch.py | 21 - .../azure/mgmt/resource/locks/py.typed | 1 - .../resource/managedapplications/__init__.py | 32 - .../_application_client.py | 144 - .../managedapplications/_configuration.py | 75 - .../resource/managedapplications/_patch.py | 21 - .../managedapplications/_utils/__init__.py | 6 - .../_utils/serialization.py | 2041 ---- .../managedapplications/_utils/utils.py | 25 - .../resource/managedapplications/_version.py | 8 - .../managedapplications/aio/__init__.py | 29 - .../aio/_application_client.py | 149 - .../managedapplications/aio/_configuration.py | 75 - .../managedapplications/aio/_patch.py | 21 - .../aio/operations/__init__.py | 30 - .../aio/operations/_operations.py | 2856 ----- .../aio/operations/_patch.py | 21 - .../managedapplications/models/__init__.py | 138 - .../models/_application_client_enums.py | 138 - .../managedapplications/models/_models_py3.py | 2141 ---- .../managedapplications/models/_patch.py | 21 - .../operations/__init__.py | 30 - .../operations/_operations.py | 3622 ------ .../managedapplications/operations/_patch.py | 21 - .../resource/managedapplications/py.typed | 1 - .../azure/mgmt/resource/policy/__init__.py | 32 - .../mgmt/resource/policy/_configuration.py | 69 - .../azure/mgmt/resource/policy/_patch.py | 21 - .../mgmt/resource/policy/_policy_client.py | 177 - .../mgmt/resource/policy/_utils/__init__.py | 6 - .../resource/policy/_utils/serialization.py | 2041 ---- .../azure/mgmt/resource/policy/_version.py | 8 - .../mgmt/resource/policy/aio/__init__.py | 29 - .../resource/policy/aio/_configuration.py | 69 - .../azure/mgmt/resource/policy/aio/_patch.py | 21 - .../resource/policy/aio/_policy_client.py | 184 - .../policy/aio/operations/__init__.py | 41 - .../policy/aio/operations/_operations.py | 7433 ----------- .../resource/policy/aio/operations/_patch.py | 21 - .../mgmt/resource/policy/models/__init__.py | 140 - .../resource/policy/models/_models_py3.py | 2333 ---- .../mgmt/resource/policy/models/_patch.py | 21 - .../policy/models/_policy_client_enums.py | 153 - .../resource/policy/operations/__init__.py | 41 - .../resource/policy/operations/_operations.py | 10155 ---------------- .../mgmt/resource/policy/operations/_patch.py | 21 - .../azure/mgmt/resource/policy/py.typed | 1 - .../mgmt/resource/privatelinks/__init__.py | 32 - .../resource/privatelinks/_configuration.py | 75 - .../mgmt/resource/privatelinks/_patch.py | 21 - .../_resource_private_link_client.py | 136 - .../resource/privatelinks/_utils/__init__.py | 6 - .../privatelinks/_utils/serialization.py | 2041 ---- .../mgmt/resource/privatelinks/_version.py | 8 - .../resource/privatelinks/aio/__init__.py | 29 - .../privatelinks/aio/_configuration.py | 75 - .../mgmt/resource/privatelinks/aio/_patch.py | 21 - .../aio/_resource_private_link_client.py | 140 - .../privatelinks/aio/operations/__init__.py | 27 - .../aio/operations/_operations.py | 705 -- .../privatelinks/aio/operations/_patch.py | 21 - .../resource/privatelinks/models/__init__.py | 52 - .../privatelinks/models/_models_py3.py | 371 - .../resource/privatelinks/models/_patch.py | 21 - .../_resource_private_link_client_enums.py | 17 - .../privatelinks/operations/__init__.py | 27 - .../privatelinks/operations/_operations.py | 985 -- .../privatelinks/operations/_patch.py | 21 - .../azure/mgmt/resource/privatelinks/py.typed | 1 - .../azure/mgmt/resource/resources/_patch.py | 1 + .../resources/_resource_management_client.py | 2 +- .../azure/mgmt/resource/resources/_version.py | 3 +- .../mgmt/resource/resources/aio/_patch.py | 1 + .../aio/_resource_management_client.py | 2 +- .../resources/aio/operations/_patch.py | 1 + .../mgmt/resource/resources/models/_patch.py | 1 + .../resource/resources/operations/_patch.py | 1 + .../mgmt/resource/subscriptions/__init__.py | 32 - .../resource/subscriptions/_configuration.py | 66 - .../mgmt/resource/subscriptions/_patch.py | 21 - .../subscriptions/_subscription_client.py | 128 - .../resource/subscriptions/_utils/__init__.py | 6 - .../subscriptions/_utils/serialization.py | 2041 ---- .../resource/subscriptions/_utils/utils.py | 25 - .../mgmt/resource/subscriptions/_version.py | 8 - .../resource/subscriptions/aio/__init__.py | 29 - .../subscriptions/aio/_configuration.py | 66 - .../mgmt/resource/subscriptions/aio/_patch.py | 21 - .../subscriptions/aio/_subscription_client.py | 133 - .../subscriptions/aio/operations/__init__.py | 30 - .../aio/operations/_operations.py | 702 -- .../subscriptions/aio/operations/_patch.py | 21 - .../resource/subscriptions/models/__init__.py | 100 - .../subscriptions/models/_models_py3.py | 1112 -- .../resource/subscriptions/models/_patch.py | 21 - .../models/_subscription_client_enums.py | 81 - .../subscriptions/operations/__init__.py | 30 - .../subscriptions/operations/_operations.py | 853 -- .../subscriptions/operations/_patch.py | 21 - .../mgmt/resource/subscriptions/py.typed | 1 - .../generated_samples/changes/get_change.py | 46 - .../generated_samples/changes/list_changes.py | 46 - .../get_scoped_data_boundary.py | 42 - .../get_tenant_data_boundary.py | 41 - .../databoundaries/put_data_boundary.py | 42 - ...ubscription_feature_registration_delete.py | 42 - .../subscription_feature_registration_get.py | 43 - .../subscription_feature_registration_list.py | 43 - ...bscription_feature_registration_listall.py | 41 - .../subscription_feature_registration_put.py | 43 - .../generated_samples/features/get_feature.py | 43 - .../features/list_features_operations.py | 41 - .../features/list_provider_features.py | 43 - .../features/list_subscription_features.py | 41 - .../features/register_feature.py | 43 - .../features/unregister_feature.py | 43 - .../locks/list_provider_operations.py | 41 - ...reate_or_update_at_resource_group_level.py | 44 - ...ocks_create_or_update_at_resource_level.py | 48 - ...agement_locks_create_or_update_at_scope.py | 44 - ..._create_or_update_at_subscription_level.py | 43 - ...nt_locks_delete_at_resource_group_level.py | 42 - ...nagement_locks_delete_at_resource_level.py | 46 - .../locks/management_locks_delete_at_scope.py | 42 - ...ment_locks_delete_at_subscription_level.py | 41 - ...ement_locks_get_at_resource_group_level.py | 43 - .../management_locks_get_at_resource_level.py | 47 - .../locks/management_locks_get_at_scope.py | 43 - ...agement_locks_get_at_subscription_level.py | 42 - ...ment_locks_list_at_resource_group_level.py | 43 - ...management_locks_list_at_resource_level.py | 47 - .../locks/management_locks_list_at_scope.py | 43 - ...gement_locks_list_at_subscription_level.py | 41 - .../create_or_update_application.py | 51 - ...create_or_update_application_definition.py | 53 - .../delete_application_definition.py | 42 - .../managedapplications/get_application.py | 43 - .../get_application_definition.py | 43 - ...plication_definitions_by_resource_group.py | 43 - .../list_applications_by_resource_group.py | 43 - .../list_solutions_operations.py | 41 - .../managedapplications/update_application.py | 43 - .../create_or_update_policy_definition.py | 66 - ...pdate_policy_definition_advanced_params.py | 82 - ...e_policy_definition_at_management_group.py | 67 - ...ate_or_update_policy_definition_version.py | 68 - ..._definition_version_at_management_group.py | 69 - .../create_or_update_policy_exemption.py | 53 - ...olicy_exemption_with_resource_selectors.py | 60 - .../create_or_update_policy_set_definition.py | 68 - ...licy_set_definition_at_management_group.py | 62 - ...or_update_policy_set_definition_version.py | 70 - ..._definition_version_at_management_group.py | 64 - ...pdate_policy_set_definition_with_groups.py | 77 - ...inition_with_groups_at_management_group.py | 76 - .../policy/create_or_update_variable.py | 43 - ..._or_update_variable_at_management_group.py | 44 - .../policy/create_or_update_variable_value.py | 51 - ...date_variable_value_at_management_group.py | 52 - .../policy/create_policy_assignment.py | 53 - .../policy/create_policy_assignment_by_id.py | 53 - ...licy_assignment_non_compliance_messages.py | 62 - .../create_policy_assignment_with_identity.py | 55 - ...e_policy_assignment_with_identity_by_id.py | 55 - ...create_policy_assignment_with_overrides.py | 58 - ...licy_assignment_with_resource_selectors.py | 57 - ..._assignment_with_user_assigned_identity.py | 60 - ...e_policy_assignment_without_enforcement.py | 53 - .../policy/delete_policy_assignment.py | 43 - .../policy/delete_policy_assignment_by_id.py | 42 - .../policy/delete_policy_definition.py | 41 - ...e_policy_definition_at_management_group.py | 42 - .../delete_policy_definition_version.py | 42 - ..._definition_version_at_management_group.py | 43 - .../policy/delete_policy_exemption.py | 42 - .../policy/delete_policy_set_definition.py | 41 - ...licy_set_definition_at_management_group.py | 42 - .../delete_policy_set_definition_version.py | 42 - ..._definition_version_at_management_group.py | 43 - .../policy/delete_variable.py | 41 - .../delete_variable_at_management_group.py | 42 - .../policy/delete_variable_value.py | 42 - ...lete_variable_value_at_management_group.py | 43 - .../get_built_in_policy_set_definition.py | 42 - ..._built_in_policy_set_definition_version.py | 43 - .../policy/get_builtin_policy_definition.py | 42 - .../get_builtin_policy_definition_version.py | 43 - .../policy/get_data_policy_manifest.py | 42 - .../policy/get_policy_assignment.py | 43 - .../policy/get_policy_assignment_by_id.py | 42 - .../get_policy_assignment_with_identity.py | 43 - ...t_policy_assignment_with_identity_by_id.py | 42 - .../get_policy_assignment_with_overrides.py | 43 - ...licy_assignment_with_resource_selectors.py | 43 - ..._assignment_with_user_assigned_identity.py | 43 - .../policy/get_policy_definition.py | 42 - ...t_policy_definition_at_management_group.py | 43 - .../policy/get_policy_definition_version.py | 43 - ..._definition_version_at_management_group.py | 44 - .../policy/get_policy_exemption.py | 43 - ...olicy_exemption_with_resource_selectors.py | 43 - .../policy/get_policy_set_definition.py | 42 - ...licy_set_definition_at_management_group.py | 43 - .../get_policy_set_definition_version.py | 43 - ..._definition_version_at_management_group.py | 44 - .../generated_samples/policy/get_variable.py | 42 - .../get_variable_at_management_group.py | 43 - .../policy/get_variable_value.py | 43 - .../get_variable_value_at_management_group.py | 44 - ...all_built_in_policy_definition_versions.py | 40 - ...built_in_policy_set_definition_versions.py | 40 - .../list_all_policy_definition_versions.py | 40 - ...definition_versions_by_management_group.py | 42 - ...list_all_policy_set_definition_versions.py | 40 - ...definition_versions_by_management_group.py | 42 - ...ist_built_in_policy_definition_versions.py | 43 - .../list_built_in_policy_definitions.py | 41 - ...built_in_policy_set_definition_versions.py | 43 - .../list_built_in_policy_set_definitions.py | 41 - .../policy/list_data_policy_manifests.py | 41 - ..._data_policy_manifests_namespace_filter.py | 41 - .../policy/list_policy_assignments.py | 41 - ...policy_assignments_for_management_group.py | 43 - .../list_policy_assignments_for_resource.py | 47 - ...t_policy_assignments_for_resource_group.py | 43 - .../policy/list_policy_definition_versions.py | 43 - ...definition_versions_by_management_group.py | 44 - .../policy/list_policy_definitions.py | 41 - ..._policy_definitions_by_management_group.py | 43 - ..._policy_exemptions_for_management_group.py | 43 - .../list_policy_exemptions_for_resource.py | 47 - ...st_policy_exemptions_for_resource_group.py | 43 - ...list_policy_exemptions_for_subscription.py | 41 - .../list_policy_set_definition_versions.py | 43 - ...definition_versions_by_management_group.py | 44 - .../policy/list_policy_set_definitions.py | 41 - ...icy_set_definitions_by_management_group.py | 43 - ...st_variable_values_for_management_group.py | 44 - .../list_variable_values_for_subscription.py | 43 - .../list_variables_for_management_group.py | 43 - .../policy/list_variables_for_subscription.py | 41 - .../update_policy_assignment_with_identity.py | 44 - ...e_policy_assignment_with_identity_by_id.py | 43 - ...update_policy_assignment_with_overrides.py | 54 - ...licy_assignment_with_resource_selectors.py | 53 - ..._assignment_with_user_assigned_identity.py | 52 - ...olicy_exemption_with_resource_selectors.py | 54 - .../delete_private_link_association.py | 42 - ...delete_resource_management_private_link.py | 42 - .../get_private_link_association.py | 43 - .../get_resource_management_private_link.py | 43 - .../list_private_link_association.py | 42 - ..._group_resource_management_private_link.py | 42 - ...iption_resource_management_private_link.py | 40 - .../put_private_link_association.py | 46 - .../put_resource_management_private_link.py | 44 - .../resources/create_resource_group.py | 2 +- .../resources/delete_tags_resource.py | 2 +- .../resources/delete_tags_subscription.py | 2 +- .../resources/export_resource_group.py | 2 +- .../export_resource_group_as_bicep.py | 2 +- .../export_resource_group_with_filtering.py | 2 +- ...e_delete_vms_and_vmss_in_resource_group.py | 2 +- .../force_delete_vms_in_resource_group.py | 2 +- .../resources/get_named_provider_at_tenant.py | 2 +- .../resources/get_provider.py | 2 +- .../resources/get_provider_permissions.py | 2 +- .../resources/get_provider_resource_types.py | 2 +- .../resources/get_providers.py | 2 +- .../resources/get_tags_resource.py | 2 +- .../resources/get_tags_subscription.py | 2 +- .../resources/patch_tags_resource.py | 2 +- .../resources/patch_tags_subscription.py | 2 +- .../resources/put_tags_resource.py | 2 +- .../resources/put_tags_subscription.py | 2 +- .../subscriptions/check_resource_name.py | 39 - .../subscriptions/get_locations.py | 42 - .../get_locations_with_extended_locations.py | 42 - .../subscriptions/get_subscription.py | 41 - .../subscriptions/get_subscriptions.py | 40 - .../subscriptions/get_tenants.py | 40 - .../subscriptions/post_check_zone_peers.py | 42 - .../generated_tests/conftest.py | 16 +- .../generated_tests/test_application.py | 29 - ...tion_application_definitions_operations.py | 148 - ...pplication_definitions_operations_async.py | 171 - ...est_application_applications_operations.py | 218 - ...plication_applications_operations_async.py | 255 - .../generated_tests/test_application_async.py | 30 - ...est_application_jit_requests_operations.py | 108 - ...plication_jit_requests_operations_async.py | 111 - .../test_changes_changes_operations.py | 48 - .../test_changes_changes_operations_async.py | 49 - ...ata_boundary_data_boundaries_operations.py | 67 - ...undary_data_boundaries_operations_async.py | 68 - ...oundary_mgmt_data_boundaries_operations.py | 67 - ...y_mgmt_data_boundaries_operations_async.py | 68 - .../generated_tests/test_feature.py | 29 - .../generated_tests/test_feature_async.py | 30 - .../test_feature_features_operations.py | 76 - .../test_feature_features_operations_async.py | 77 - ...iption_feature_registrations_operations.py | 76 - ..._feature_registrations_operations_async.py | 77 - .../test_management_link_operations.py | 29 - .../test_management_link_operations_async.py | 30 - ...nagement_link_resource_links_operations.py | 79 - ...nt_link_resource_links_operations_async.py | 80 - ...ock_authorization_operations_operations.py | 29 - ...thorization_operations_operations_async.py | 30 - ...gement_lock_management_locks_operations.py | 251 - ..._lock_management_locks_operations_async.py | 252 - ...policy_data_policy_manifests_operations.py | 40 - ..._data_policy_manifests_operations_async.py | 41 - ...st_policy_policy_assignments_operations.py | 256 - ...icy_policy_assignments_operations_async.py | 257 - ...y_policy_definition_versions_operations.py | 239 - ...cy_definition_versions_operations_async.py | 240 - ...st_policy_policy_definitions_operations.py | 200 - ...icy_policy_definitions_operations_async.py | 201 - ...est_policy_policy_exemptions_operations.py | 140 - ...licy_policy_exemptions_operations_async.py | 141 - ...licy_set_definition_versions_operations.py | 275 - ...et_definition_versions_operations_async.py | 276 - ...olicy_policy_set_definitions_operations.py | 236 - ...policy_set_definitions_operations_async.py | 237 - .../test_policy_variable_values_operations.py | 145 - ...policy_variable_values_operations_async.py | 146 - .../test_policy_variables_operations.py | 137 - .../test_policy_variables_operations_async.py | 138 - ...gement_deployment_operations_operations.py | 140 - ..._deployment_operations_operations_async.py | 141 - ...ource_management_deployments_operations.py | 885 -- ...management_deployments_operations_async.py | 924 -- ...ink_private_link_association_operations.py | 67 - ...ivate_link_association_operations_async.py | 68 - ...urce_management_private_link_operations.py | 77 - ...anagement_private_link_operations_async.py | 78 - .../generated_tests/test_subscription.py | 29 - .../test_subscription_async.py | 30 - .../test_subscription_operations.py | 29 - .../test_subscription_operations_async.py | 30 - ...t_subscription_subscriptions_operations.py | 63 - ...cription_subscriptions_operations_async.py | 64 - .../test_subscription_tenants_operations.py | 29 - ...t_subscription_tenants_operations_async.py | 30 - .../azure-mgmt-resource/pyproject.toml | 4 +- ...t_data_boundaries_operations_async_test.py | 40 - ...ry_mgmt_data_boundaries_operations_test.py | 39 - .../tests/test_mgmt_resource_changes_test.py | 55 - ...t_mgmt_resource_deployment_scripts_test.py | 109 - .../tests/test_mgmt_resource_feature_test.py | 23 - .../tests/test_mgmt_resource_links_test.py | 23 - .../tests/test_mgmt_resource_locks_test.py | 169 - ..._mgmt_resource_managed_application_test.py | 22 - .../tests/test_mgmt_resource_policy_test.py | 23 - .../test_mgmt_resource_private_link_test.py | 22 - .../test_mgmt_resource_subscriptions_test.py | 60 - ...olicy_assignments_operations_async_test.py | 36 - ...licy_policy_assignments_operations_test.py | 35 - ...olicy_definitions_operations_async_test.py | 34 - ...licy_policy_definitions_operations_test.py | 33 - ...ment_private_link_operations_async_test.py | 36 - ...management_private_link_operations_test.py | 35 - ...ion_subscriptions_operations_async_test.py | 27 - ...scription_subscriptions_operations_test.py | 26 - 478 files changed, 190 insertions(+), 85891 deletions(-) delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_changes_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_changes_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_changes_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_feature_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/utils.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_feature_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_feature_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_management_link_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_management_link_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_management_lock_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_management_lock_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_management_lock_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_application_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/utils.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_application_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_application_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_policy_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_policy_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_policy_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_resource_private_link_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_subscription_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/serialization.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/utils.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_configuration.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_subscription_client.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_models_py3.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/__init__.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_patch.py delete mode 100644 sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/py.typed delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/changes/get_change.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/changes/list_changes.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_scoped_data_boundary.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_tenant_data_boundary.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/put_data_boundary.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_delete.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_get.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_list.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_listall.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_put.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/get_feature.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/list_features_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/list_provider_features.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/list_subscription_features.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/register_feature.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/features/unregister_feature.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/list_provider_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_group_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_scope.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_subscription_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_group_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_scope.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_subscription_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_group_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_scope.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_subscription_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_group_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_scope.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_subscription_level.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/delete_application_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_application_definitions_by_resource_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_applications_by_resource_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_solutions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/update_application.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_advanced_params.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption_with_resource_selectors.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_by_id.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_non_compliance_messages.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity_by_id.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_overrides.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_resource_selectors.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_user_assigned_identity.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_without_enforcement.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment_by_id.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_exemption.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_data_policy_manifest.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_by_id.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity_by_id.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_overrides.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_resource_selectors.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_user_assigned_identity.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption_with_resource_selectors.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value_at_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_set_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions_by_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions_by_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definitions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definitions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests_namespace_filter.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions_by_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions_by_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_subscription.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions_by_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions_by_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_subscription.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_management_group.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_subscription.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity_by_id.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_overrides.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_resource_selectors.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_user_assigned_identity.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_exemption_with_resource_selectors.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_private_link_association.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_resource_management_private_link.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_private_link_association.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_resource_management_private_link.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_private_link_association.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_resource_group_resource_management_private_link.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_subscription_resource_management_private_link.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_private_link_association.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_resource_management_private_link.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/check_resource_name.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations_with_extended_locations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscription.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscriptions.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_tenants.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/post_check_zone_peers.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_feature.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_feature_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations.py delete mode 100644 sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations_async.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_changes_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_deployment_scripts_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_feature_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_links_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_locks_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_managed_application_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_policy_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_private_link_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_subscriptions_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_async_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_async_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_async_test.py delete mode 100644 sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_test.py diff --git a/sdk/resources/azure-mgmt-resource/CHANGELOG.md b/sdk/resources/azure-mgmt-resource/CHANGELOG.md index 7c734d097f01..520c3c659038 100644 --- a/sdk/resources/azure-mgmt-resource/CHANGELOG.md +++ b/sdk/resources/azure-mgmt-resource/CHANGELOG.md @@ -1,11 +1,20 @@ # Release History +## 25.0.0 (2026-02-04) + +### Breaking Changes + + - This package now only targets the latest Api-Version available on Azure and removes APIs of other Api-Version. After this change, the package can have much smaller size. If your application requires a specific and non-latest Api-Version, it's recommended to pin this package to the previous released version; If your application always only use latest Api-Version, please ignore this change. + - Operation Group `Deployments` and `DeploymentOperations` of `ResourceManagementClient` are moved to `DeploymentsMgmtClient` of independent package `azure-mgmt-resource-deployments`. If you called `ResourceManagementClient(...).deployments.xx(...)` before, just need to change to `DeploymentsMgmtClient(...).deployments.xx(...)`. And same for `DeploymentOperations`. + - The following modules have been separated from `azure-mgmt-resource` into independent packages: `subscriptions`, `features`, `links`, `locks`, `policy`, `managedapplications`, `databoundaries`, `changes`, and `privatelinks`. Each module is now available as `azure-mgmt-resource-{module}`. + - For separated modules, if you previously imported them using statements like `from azure.mgmt.resource import SubscriptionClient`, you'll need to update your code to `from azure.mgmt.resource.subscriptions import SubscriptionClient`. If you were already using the fully qualified import path, no changes are required. + ## 25.0.0b1 (2025-07-16) ### Breaking Changes - This package now only targets the latest Api-Version available on Azure and removes APIs of other Api-Version. After this change, the package can have much smaller size. If your application requires a specific and non-latest Api-Version, it's recommended to pin this package to the previous released version; If your application always only use latest Api-Version, please ignore this change. - - Operation Group `Deployments` and `DeploymentOperations` of `ResourceManagementClient` are moved to `DeploymentsMgmtClient` of independent package `azure-mgmt-resource-deployments`. If you called `ResourceManagementClient(...).deployments.xx(...)` before, just need change to `DeploymentsMgmtClient(...).deployments.xx(...)`. And same for `DeploymentOperations`. + - Operation Group `Deployments` and `DeploymentOperations` of `ResourceManagementClient` are moved to `DeploymentsMgmtClient` of independent package `azure-mgmt-resource-deployments`. If you called `ResourceManagementClient(...).deployments.xx(...)` before, just need to change to `DeploymentsMgmtClient(...).deployments.xx(...)`. And same for `DeploymentOperations`. ## 24.0.0 (2025-06-16) diff --git a/sdk/resources/azure-mgmt-resource/_metadata.json b/sdk/resources/azure-mgmt-resource/_metadata.json index 1420df25c315..9606fb861fb7 100644 --- a/sdk/resources/azure-mgmt-resource/_metadata.json +++ b/sdk/resources/azure-mgmt-resource/_metadata.json @@ -1,11 +1,11 @@ { - "commit": "07b9f3536b0cbcdbe18a4f7037af272b1df5bbc1", + "commit": "bd379a19745963b51c41b0928bac7cab7803d92a", "repository_url": "https://github.com/Azure/azure-rest-api-specs", "autorest": "3.10.2", "use": [ "@autorest/python@6.48.0", "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/resources/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", - "readme": "specification/resources/resource-manager/readme.md" + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Resources/resources/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-resources-2025-04 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Resources/resources/readme.md" } \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/apiview-properties.json b/sdk/resources/azure-mgmt-resource/apiview-properties.json index 18a218e36297..120c22a51e8a 100644 --- a/sdk/resources/azure-mgmt-resource/apiview-properties.json +++ b/sdk/resources/azure-mgmt-resource/apiview-properties.json @@ -1,23 +1,143 @@ { "CrossLanguagePackageId": null, "CrossLanguageDefinitionId": { - "azure.mgmt.resource.databoundaries.models.Resource": null, - "azure.mgmt.resource.databoundaries.models.ProxyResource": null, - "azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition": null, - "azure.mgmt.resource.databoundaries.models.DataBoundaryProperties": null, - "azure.mgmt.resource.databoundaries.models.ErrorAdditionalInfo": null, - "azure.mgmt.resource.databoundaries.models.ErrorDetail": null, - "azure.mgmt.resource.databoundaries.models.ErrorResponse": null, - "azure.mgmt.resource.databoundaries.models.SystemData": null, - "azure.mgmt.resource.databoundaries.models.DefaultName": null, - "azure.mgmt.resource.databoundaries.models.DataBoundary": null, - "azure.mgmt.resource.databoundaries.models.ProvisioningState": null, - "azure.mgmt.resource.databoundaries.models.CreatedByType": null, - "azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations.put": null, - "azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations.put": null, - "azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations.get_tenant": null, - "azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations.get_tenant": null, - "azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations.get_scope": null, - "azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations.get_scope": null + "azure.mgmt.resource.resources.models.Alias": null, + "azure.mgmt.resource.resources.models.AliasPath": null, + "azure.mgmt.resource.resources.models.AliasPathMetadata": null, + "azure.mgmt.resource.resources.models.AliasPattern": null, + "azure.mgmt.resource.resources.models.ApiProfile": null, + "azure.mgmt.resource.resources.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.resources.models.ErrorResponse": null, + "azure.mgmt.resource.resources.models.ExportTemplateRequest": null, + "azure.mgmt.resource.resources.models.ExtendedLocation": null, + "azure.mgmt.resource.resources.models.Resource": null, + "azure.mgmt.resource.resources.models.GenericResource": null, + "azure.mgmt.resource.resources.models.GenericResourceExpanded": null, + "azure.mgmt.resource.resources.models.GenericResourceFilter": null, + "azure.mgmt.resource.resources.models.Identity": null, + "azure.mgmt.resource.resources.models.IdentityUserAssignedIdentitiesValue": null, + "azure.mgmt.resource.resources.models.Operation": null, + "azure.mgmt.resource.resources.models.OperationDisplay": null, + "azure.mgmt.resource.resources.models.OperationListResult": null, + "azure.mgmt.resource.resources.models.Permission": null, + "azure.mgmt.resource.resources.models.Plan": null, + "azure.mgmt.resource.resources.models.Provider": null, + "azure.mgmt.resource.resources.models.ProviderConsentDefinition": null, + "azure.mgmt.resource.resources.models.ProviderExtendedLocation": null, + "azure.mgmt.resource.resources.models.ProviderListResult": null, + "azure.mgmt.resource.resources.models.ProviderPermission": null, + "azure.mgmt.resource.resources.models.ProviderPermissionListResult": null, + "azure.mgmt.resource.resources.models.ProviderRegistrationRequest": null, + "azure.mgmt.resource.resources.models.ProviderResourceType": null, + "azure.mgmt.resource.resources.models.ProviderResourceTypeListResult": null, + "azure.mgmt.resource.resources.models.ResourceGroup": null, + "azure.mgmt.resource.resources.models.ResourceGroupExportResult": null, + "azure.mgmt.resource.resources.models.ResourceGroupFilter": null, + "azure.mgmt.resource.resources.models.ResourceGroupListResult": null, + "azure.mgmt.resource.resources.models.ResourceGroupPatchable": null, + "azure.mgmt.resource.resources.models.ResourceGroupProperties": null, + "azure.mgmt.resource.resources.models.ResourceListResult": null, + "azure.mgmt.resource.resources.models.ResourceProviderOperationDisplayProperties": null, + "azure.mgmt.resource.resources.models.ResourcesMoveInfo": null, + "azure.mgmt.resource.resources.models.RoleDefinition": null, + "azure.mgmt.resource.resources.models.Sku": null, + "azure.mgmt.resource.resources.models.SubResource": null, + "azure.mgmt.resource.resources.models.TagCount": null, + "azure.mgmt.resource.resources.models.TagDetails": null, + "azure.mgmt.resource.resources.models.Tags": null, + "azure.mgmt.resource.resources.models.TagsListResult": null, + "azure.mgmt.resource.resources.models.TagsPatchResource": null, + "azure.mgmt.resource.resources.models.TagsResource": null, + "azure.mgmt.resource.resources.models.TagValue": null, + "azure.mgmt.resource.resources.models.ZoneMapping": null, + "azure.mgmt.resource.resources.models.AliasPatternType": null, + "azure.mgmt.resource.resources.models.AliasPathTokenType": null, + "azure.mgmt.resource.resources.models.AliasPathAttributes": null, + "azure.mgmt.resource.resources.models.AliasType": null, + "azure.mgmt.resource.resources.models.ProviderAuthorizationConsentState": null, + "azure.mgmt.resource.resources.models.ExtendedLocationType": null, + "azure.mgmt.resource.resources.models.ResourceIdentityType": null, + "azure.mgmt.resource.resources.models.ExportTemplateOutputFormat": null, + "azure.mgmt.resource.resources.models.TagsPatchOperation": null, + "azure.mgmt.resource.resources.operations.Operations.list": null, + "azure.mgmt.resource.resources.aio.operations.Operations.list": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.unregister": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.unregister": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.register_at_management_group_scope": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.register_at_management_group_scope": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.provider_permissions": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.provider_permissions": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.register": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.register": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.list": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.list": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.list_at_tenant_scope": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.list_at_tenant_scope": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.get": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.get": null, + "azure.mgmt.resource.resources.operations.ProvidersOperations.get_at_tenant_scope": null, + "azure.mgmt.resource.resources.aio.operations.ProvidersOperations.get_at_tenant_scope": null, + "azure.mgmt.resource.resources.operations.ProviderResourceTypesOperations.list": null, + "azure.mgmt.resource.resources.aio.operations.ProviderResourceTypesOperations.list": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.list_by_resource_group": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.list_by_resource_group": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_move_resources": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_move_resources": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_validate_move_resources": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_validate_move_resources": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.list": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.list": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.check_existence": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.check_existence": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_delete": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_delete": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_create_or_update": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_create_or_update": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_update": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_update": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.get": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.get": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.check_existence_by_id": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.check_existence_by_id": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_delete_by_id": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_delete_by_id": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_create_or_update_by_id": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_create_or_update_by_id": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.begin_update_by_id": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.begin_update_by_id": null, + "azure.mgmt.resource.resources.operations.ResourcesOperations.get_by_id": null, + "azure.mgmt.resource.resources.aio.operations.ResourcesOperations.get_by_id": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.check_existence": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.check_existence": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.create_or_update": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.create_or_update": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.begin_delete": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.begin_delete": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.get": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.get": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.update": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.update": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.begin_export_template": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.begin_export_template": null, + "azure.mgmt.resource.resources.operations.ResourceGroupsOperations.list": null, + "azure.mgmt.resource.resources.aio.operations.ResourceGroupsOperations.list": null, + "azure.mgmt.resource.resources.operations.TagsOperations.delete_value": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.delete_value": null, + "azure.mgmt.resource.resources.operations.TagsOperations.create_or_update_value": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.create_or_update_value": null, + "azure.mgmt.resource.resources.operations.TagsOperations.create_or_update": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.create_or_update": null, + "azure.mgmt.resource.resources.operations.TagsOperations.delete": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.delete": null, + "azure.mgmt.resource.resources.operations.TagsOperations.list": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.list": null, + "azure.mgmt.resource.resources.operations.TagsOperations.begin_create_or_update_at_scope": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.begin_create_or_update_at_scope": null, + "azure.mgmt.resource.resources.operations.TagsOperations.begin_update_at_scope": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.begin_update_at_scope": null, + "azure.mgmt.resource.resources.operations.TagsOperations.get_at_scope": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.get_at_scope": null, + "azure.mgmt.resource.resources.operations.TagsOperations.begin_delete_at_scope": null, + "azure.mgmt.resource.resources.aio.operations.TagsOperations.begin_delete_at_scope": null } } \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/__init__.py index 6a43ac7841ad..cf83175351e9 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/__init__.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/__init__.py @@ -6,22 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from .managedapplications import ApplicationClient -from .features import FeatureClient -from .links import ManagementLinkClient -from .locks import ManagementLockClient -from .policy import PolicyClient from .resources import ResourceManagementClient -from .subscriptions import SubscriptionClient -from .databoundaries import DataBoundaryMgmtClient __all__ = [ - "ApplicationClient", - "FeatureClient", - "PolicyClient", - "ManagementLinkClient", - "ManagementLockClient", "ResourceManagementClient", - "SubscriptionClient", - "DataBoundaryMgmtClient", ] diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/_version.py index fe295d036e47..268d9f9e1fac 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/_version.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/_version.py @@ -5,4 +5,4 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "25.0.0b1" +VERSION = "25.0.0" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/__init__.py deleted file mode 100644 index 885ce76f7c57..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._changes_client import ChangesClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChangesClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_changes_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_changes_client.py deleted file mode 100644 index e853f9805420..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_changes_client.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import ChangesClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import ChangesOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ChangesClient: - """The Resource Changes Client. - - :ivar changes: ChangesOperations operations - :vartype changes: azure.mgmt.resource.changes.operations.ChangesOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. - 00000000-0000-0000-0000-000000000000). Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ChangesClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.changes = ChangesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_configuration.py deleted file mode 100644 index b6e4009cf1ea..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_configuration.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ChangesClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ChangesClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. - 00000000-0000-0000-0000-000000000000). Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2022-05-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node
is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/__init__.py deleted file mode 100644 index acead607168e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._changes_client import ChangesClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChangesClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_changes_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_changes_client.py deleted file mode 100644 index b3f2b9d29a40..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_changes_client.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import ChangesClientConfiguration -from .operations import ChangesOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ChangesClient: - """The Resource Changes Client. - - :ivar changes: ChangesOperations operations - :vartype changes: azure.mgmt.resource.changes.aio.operations.ChangesOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. - 00000000-0000-0000-0000-000000000000). Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ChangesClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.changes = ChangesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_configuration.py deleted file mode 100644 index 9b5069518e5e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_configuration.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ChangesClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ChangesClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. - 00000000-0000-0000-0000-000000000000). Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2022-05-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/__init__.py deleted file mode 100644 index 8fe881f6b809..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import ChangesOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChangesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_operations.py deleted file mode 100644 index 6dafb9831593..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_operations.py +++ /dev/null @@ -1,238 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import build_changes_get_request, build_changes_list_request -from .._configuration import ChangesClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class ChangesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.changes.aio.ChangesClient`'s - :attr:`changes` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ChangesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - resource_group_name: str, - resource_provider_namespace: str, - resource_type: str, - resource_name: str, - top: int = 100, - skip_token: Optional[str] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.ChangeResourceResult"]: - """Obtains a list of change resources from the past 14 days for the target resource. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param resource_provider_namespace: The name of the resource provider namespace. Required. - :type resource_provider_namespace: str - :param resource_type: The name of the resource type. Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param top: (Optional) Set the maximum number of results per response. Default value is 100. - :type top: int - :param skip_token: (Optional) The page-continuation token. Default value is None. - :type skip_token: str - :return: An iterator like instance of either ChangeResourceResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.changes.models.ChangeResourceResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChangeResourceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_changes_list_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - top=top, - skip_token=skip_token, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ChangeResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, - resource_group_name: str, - resource_provider_namespace: str, - resource_type: str, - resource_name: str, - change_resource_id: str, - **kwargs: Any - ) -> _models.ChangeResourceResult: - """Obtains the specified change resource for the target resource. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param resource_provider_namespace: The name of the resource provider namespace. Required. - :type resource_provider_namespace: str - :param resource_type: The name of the resource type. Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param change_resource_id: The ID of the change resource. Required. - :type change_resource_id: str - :return: ChangeResourceResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.changes.models.ChangeResourceResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChangeResourceResult] = kwargs.pop("cls", None) - - _request = build_changes_get_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - resource_type=resource_type, - resource_name=resource_name, - change_resource_id=change_resource_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChangeResourceResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/__init__.py deleted file mode 100644 index 402dae6f0312..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - ChangeAttributes, - ChangeBase, - ChangeProperties, - ChangeResourceListResult, - ChangeResourceResult, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - Resource, -) - -from ._changes_client_enums import ( # type: ignore - ChangeCategory, - ChangeType, - PropertyChangeType, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChangeAttributes", - "ChangeBase", - "ChangeProperties", - "ChangeResourceListResult", - "ChangeResourceResult", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "Resource", - "ChangeCategory", - "ChangeType", - "PropertyChangeType", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_changes_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_changes_client_enums.py deleted file mode 100644 index 996871a4dc8d..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_changes_client_enums.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ChangeCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The entity that made the change.""" - - USER = "User" - """User initiated change""" - SYSTEM = "System" - """System initiated change""" - - -class ChangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of change that was captured in the resource.""" - - UPDATE = "Update" - """An existing resource underwent a change""" - DELETE = "Delete" - """An existing resource was deleted""" - CREATE = "Create" - """A newly created resource""" - - -class PropertyChangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of change that occurred.""" - - UPDATE = "Update" - """An existing property underwent a change""" - INSERT = "Insert" - """A property was newly created""" - REMOVE = "Remove" - """An existing property was deleted""" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_models_py3.py deleted file mode 100644 index 544c6786afef..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_models_py3.py +++ /dev/null @@ -1,352 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class ChangeAttributes(_serialization.Model): - """Details about the change resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar correlation_id: The ARM correlation ID of the change resource. - :vartype correlation_id: str - :ivar timestamp: The time the change(s) on the target resource ocurred. - :vartype timestamp: str - :ivar changes_count: The number of changes this resource captures. - :vartype changes_count: int - :ivar previous_resource_snapshot_id: The GUID of the previous snapshot. - :vartype previous_resource_snapshot_id: str - :ivar new_resource_snapshot_id: The GUID of the new snapshot. - :vartype new_resource_snapshot_id: str - """ - - _validation = { - "correlation_id": {"readonly": True}, - "timestamp": {"readonly": True}, - "changes_count": {"readonly": True}, - "previous_resource_snapshot_id": {"readonly": True}, - "new_resource_snapshot_id": {"readonly": True}, - } - - _attribute_map = { - "correlation_id": {"key": "correlationId", "type": "str"}, - "timestamp": {"key": "timestamp", "type": "str"}, - "changes_count": {"key": "changesCount", "type": "int"}, - "previous_resource_snapshot_id": {"key": "previousResourceSnapshotId", "type": "str"}, - "new_resource_snapshot_id": {"key": "newResourceSnapshotId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.correlation_id: Optional[str] = None - self.timestamp: Optional[str] = None - self.changes_count: Optional[int] = None - self.previous_resource_snapshot_id: Optional[str] = None - self.new_resource_snapshot_id: Optional[str] = None - - -class ChangeBase(_serialization.Model): - """An individual change on the target resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar property_change_type: The type of change that occurred. Known values are: "Update", - "Insert", and "Remove". - :vartype property_change_type: str or ~azure.mgmt.resource.changes.models.PropertyChangeType - :ivar change_category: The entity that made the change. Known values are: "User" and "System". - :vartype change_category: str or ~azure.mgmt.resource.changes.models.ChangeCategory - :ivar previous_value: The target resource property value before the change. - :vartype previous_value: str - :ivar new_value: The target resource property value after the change. - :vartype new_value: str - """ - - _validation = { - "property_change_type": {"readonly": True}, - "change_category": {"readonly": True}, - "previous_value": {"readonly": True}, - "new_value": {"readonly": True}, - } - - _attribute_map = { - "property_change_type": {"key": "propertyChangeType", "type": "str"}, - "change_category": {"key": "changeCategory", "type": "str"}, - "previous_value": {"key": "previousValue", "type": "str"}, - "new_value": {"key": "newValue", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.property_change_type: Optional[Union[str, "_models.PropertyChangeType"]] = None - self.change_category: Optional[Union[str, "_models.ChangeCategory"]] = None - self.previous_value: Optional[str] = None - self.new_value: Optional[str] = None - - -class ChangeProperties(_serialization.Model): - """The properties of a change. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar target_resource_id: The fully qualified ID of the target resource that was changed. - :vartype target_resource_id: str - :ivar target_resource_type: The namespace and type of the resource. - :vartype target_resource_type: str - :ivar change_type: The type of change that was captured in the resource. Known values are: - "Update", "Delete", and "Create". - :vartype change_type: str or ~azure.mgmt.resource.changes.models.ChangeType - :ivar change_attributes: Details about the change resource. - :vartype change_attributes: ~azure.mgmt.resource.changes.models.ChangeAttributes - :ivar changes: A dictionary with changed property name as a key and the change details as the - value. - :vartype changes: dict[str, ~azure.mgmt.resource.changes.models.ChangeBase] - """ - - _validation = { - "target_resource_id": {"readonly": True}, - "target_resource_type": {"readonly": True}, - "change_type": {"readonly": True}, - } - - _attribute_map = { - "target_resource_id": {"key": "targetResourceId", "type": "str"}, - "target_resource_type": {"key": "targetResourceType", "type": "str"}, - "change_type": {"key": "changeType", "type": "str"}, - "change_attributes": {"key": "changeAttributes", "type": "ChangeAttributes"}, - "changes": {"key": "changes", "type": "{ChangeBase}"}, - } - - def __init__( - self, - *, - change_attributes: Optional["_models.ChangeAttributes"] = None, - changes: Optional[dict[str, "_models.ChangeBase"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword change_attributes: Details about the change resource. - :paramtype change_attributes: ~azure.mgmt.resource.changes.models.ChangeAttributes - :keyword changes: A dictionary with changed property name as a key and the change details as - the value. - :paramtype changes: dict[str, ~azure.mgmt.resource.changes.models.ChangeBase] - """ - super().__init__(**kwargs) - self.target_resource_id: Optional[str] = None - self.target_resource_type: Optional[str] = None - self.change_type: Optional[Union[str, "_models.ChangeType"]] = None - self.change_attributes = change_attributes - self.changes = changes - - -class ChangeResourceListResult(_serialization.Model): - """The list of resources. - - :ivar next_link: The link used to get the next page of Change Resources. - :vartype next_link: str - :ivar value: The list of resources. - :vartype value: list[~azure.mgmt.resource.changes.models.ChangeResourceResult] - """ - - _attribute_map = { - "next_link": {"key": "nextLink", "type": "str"}, - "value": {"key": "value", "type": "[ChangeResourceResult]"}, - } - - def __init__( - self, - *, - next_link: Optional[str] = None, - value: Optional[list["_models.ChangeResourceResult"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword next_link: The link used to get the next page of Change Resources. - :paramtype next_link: str - :keyword value: The list of resources. - :paramtype value: list[~azure.mgmt.resource.changes.models.ChangeResourceResult] - """ - super().__init__(**kwargs) - self.next_link = next_link - self.value = value - - -class Resource(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - - -class ChangeResourceResult(Resource): - """Change Resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar properties: The properties of a change. - :vartype properties: ~azure.mgmt.resource.changes.models.ChangeProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "ChangeProperties"}, - } - - def __init__(self, *, properties: Optional["_models.ChangeProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: The properties of a change. - :paramtype properties: ~azure.mgmt.resource.changes.models.ChangeProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.changes.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.resource.changes.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.resource.changes.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.resource.changes.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/__init__.py deleted file mode 100644 index 8fe881f6b809..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import ChangesOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChangesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_operations.py deleted file mode 100644 index e430f1cef8ab..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_operations.py +++ /dev/null @@ -1,324 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import ChangesClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_changes_list_request( - resource_group_name: str, - resource_provider_namespace: str, - resource_type: str, - resource_name: str, - subscription_id: str, - *, - top: int = 100, - skip_token: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str"), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=100, minimum=1) - if skip_token is not None: - _params["$skipToken"] = _SERIALIZER.query("skip_token", skip_token, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_changes_get_request( - resource_group_name: str, - resource_provider_namespace: str, - resource_type: str, - resource_name: str, - change_resource_id: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes/{changeResourceId}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str"), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - "changeResourceId": _SERIALIZER.url("change_resource_id", change_resource_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ChangesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.changes.ChangesClient`'s - :attr:`changes` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ChangesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - resource_group_name: str, - resource_provider_namespace: str, - resource_type: str, - resource_name: str, - top: int = 100, - skip_token: Optional[str] = None, - **kwargs: Any - ) -> ItemPaged["_models.ChangeResourceResult"]: - """Obtains a list of change resources from the past 14 days for the target resource. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param resource_provider_namespace: The name of the resource provider namespace. Required. - :type resource_provider_namespace: str - :param resource_type: The name of the resource type. Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param top: (Optional) Set the maximum number of results per response. Default value is 100. - :type top: int - :param skip_token: (Optional) The page-continuation token. Default value is None. - :type skip_token: str - :return: An iterator like instance of either ChangeResourceResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.changes.models.ChangeResourceResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChangeResourceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_changes_list_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - top=top, - skip_token=skip_token, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ChangeResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, - resource_group_name: str, - resource_provider_namespace: str, - resource_type: str, - resource_name: str, - change_resource_id: str, - **kwargs: Any - ) -> _models.ChangeResourceResult: - """Obtains the specified change resource for the target resource. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param resource_provider_namespace: The name of the resource provider namespace. Required. - :type resource_provider_namespace: str - :param resource_type: The name of the resource type. Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param change_resource_id: The ID of the change resource. Required. - :type change_resource_id: str - :return: ChangeResourceResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.changes.models.ChangeResourceResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChangeResourceResult] = kwargs.pop("cls", None) - - _request = build_changes_get_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - resource_type=resource_type, - resource_name=resource_name, - change_resource_id=change_resource_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChangeResourceResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/changes/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/__init__.py deleted file mode 100644 index bdb7fb5d678b..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._data_boundary_mgmt_client import DataBoundaryMgmtClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataBoundaryMgmtClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_configuration.py deleted file mode 100644 index d90639450fa8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_configuration.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class DataBoundaryMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for DataBoundaryMgmtClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, credential: "TokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2024-08-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py deleted file mode 100644 index 19fde6f99b58..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_data_boundary_mgmt_client.py +++ /dev/null @@ -1,121 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import DataBoundaryMgmtClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import DataBoundariesOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class DataBoundaryMgmtClient: - """Provides APIs for data boundary operations. - - :ivar data_boundaries: DataBoundariesOperations operations - :vartype data_boundaries: - azure.mgmt.resource.databoundaries.operations.DataBoundariesOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = DataBoundaryMgmtClientConfiguration( - credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.data_boundaries = DataBoundariesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/__init__.py deleted file mode 100644 index 232f214e1b14..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._data_boundary_mgmt_client import DataBoundaryMgmtClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataBoundaryMgmtClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_configuration.py deleted file mode 100644 index fa5c0d3e38de..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_configuration.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class DataBoundaryMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for DataBoundaryMgmtClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, credential: "AsyncTokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2024-08-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py deleted file mode 100644 index 5eae326eca62..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_data_boundary_mgmt_client.py +++ /dev/null @@ -1,125 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import DataBoundaryMgmtClientConfiguration -from .operations import DataBoundariesOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class DataBoundaryMgmtClient: - """Provides APIs for data boundary operations. - - :ivar data_boundaries: DataBoundariesOperations operations - :vartype data_boundaries: - azure.mgmt.resource.databoundaries.aio.operations.DataBoundariesOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2024-08-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = DataBoundaryMgmtClientConfiguration( - credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.data_boundaries = DataBoundariesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/__init__.py deleted file mode 100644 index 3cd0a7f40599..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import DataBoundariesOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataBoundariesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_operations.py deleted file mode 100644 index 1fd666cbbdbe..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_operations.py +++ /dev/null @@ -1,299 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import ( - build_data_boundaries_get_scope_request, - build_data_boundaries_get_tenant_request, - build_data_boundaries_put_request, -) -from .._configuration import DataBoundaryMgmtClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class DataBoundariesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.databoundaries.aio.DataBoundaryMgmtClient`'s - :attr:`data_boundaries` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: DataBoundaryMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def put( - self, - default: Union[str, _models.DefaultName], - data_boundary_definition: _models.DataBoundaryDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Opt-in tenant to data boundary. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :param data_boundary_definition: The data boundary to opt the tenant to. Required. - :type data_boundary_definition: - ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def put( - self, - default: Union[str, _models.DefaultName], - data_boundary_definition: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Opt-in tenant to data boundary. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :param data_boundary_definition: The data boundary to opt the tenant to. Required. - :type data_boundary_definition: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def put( - self, - default: Union[str, _models.DefaultName], - data_boundary_definition: Union[_models.DataBoundaryDefinition, IO[bytes]], - **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Opt-in tenant to data boundary. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :param data_boundary_definition: The data boundary to opt the tenant to. Is either a - DataBoundaryDefinition type or a IO[bytes] type. Required. - :type data_boundary_definition: - ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition or IO[bytes] - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_boundary_definition, (IOBase, bytes)): - _content = data_boundary_definition - else: - _json = self._serialize.body(data_boundary_definition, "DataBoundaryDefinition") - - _request = build_data_boundaries_put_request( - default=default, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_tenant( - self, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Get data boundary of tenant. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) - - _request = build_data_boundaries_get_tenant_request( - default=default, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_scope( - self, scope: str, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Get data boundary at specified scope. - - :param scope: The scope at which the operation is performed. Required. - :type scope: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) - - _request = build_data_boundaries_get_scope_request( - scope=scope, - default=default, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/__init__.py deleted file mode 100644 index 5a86d6a8b2c5..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - DataBoundaryDefinition, - DataBoundaryProperties, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - ProxyResource, - Resource, - SystemData, -) - -from ._data_boundary_mgmt_client_enums import ( # type: ignore - CreatedByType, - DataBoundary, - DefaultName, - ProvisioningState, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataBoundaryDefinition", - "DataBoundaryProperties", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "ProxyResource", - "Resource", - "SystemData", - "CreatedByType", - "DataBoundary", - "DefaultName", - "ProvisioningState", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py deleted file mode 100644 index 0c06bfddfbf2..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_data_boundary_mgmt_client_enums.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity that created the resource.""" - - USER = "User" - APPLICATION = "Application" - MANAGED_IDENTITY = "ManagedIdentity" - KEY = "Key" - - -class DataBoundary(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The data boundary definition.""" - - NOT_DEFINED = "NotDefined" - GLOBAL = "Global" - EU = "EU" - GLOBAL_ENUM = "Global" - - -class DefaultName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """DefaultName.""" - - DEFAULT = "default" - - -class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Denotes the state of provisioning.""" - - ACCEPTED = "Accepted" - RUNNING = "Running" - CREATING = "Creating" - CANCELED = "Canceled" - FAILED = "Failed" - SUCCEEDED = "Succeeded" - UPDATING = "Updating" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_models_py3.py deleted file mode 100644 index 99b131976286..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_models_py3.py +++ /dev/null @@ -1,314 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class Resource(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.resource.databoundaries.models.SystemData - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.system_data: Optional["_models.SystemData"] = None - - -class ProxyResource(Resource): - """The resource model definition for a Azure Resource Manager proxy resource. It will not have - tags and a location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.resource.databoundaries.models.SystemData - """ - - -class DataBoundaryDefinition(ProxyResource): - """A data boundary definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.resource.databoundaries.models.SystemData - :ivar properties: Data boundary properties. - :vartype properties: ~azure.mgmt.resource.databoundaries.models.DataBoundaryProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "properties": {"key": "properties", "type": "DataBoundaryProperties"}, - } - - def __init__(self, *, properties: Optional["_models.DataBoundaryProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Data boundary properties. - :paramtype properties: ~azure.mgmt.resource.databoundaries.models.DataBoundaryProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class DataBoundaryProperties(_serialization.Model): - """Data boundary properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar data_boundary: The data boundary definition. Known values are: "NotDefined", "Global", - "EU", and "Global". - :vartype data_boundary: str or ~azure.mgmt.resource.databoundaries.models.DataBoundary - :ivar provisioning_state: Denotes the state of provisioning. Known values are: "Accepted", - "Running", "Creating", "Canceled", "Failed", "Succeeded", and "Updating". - :vartype provisioning_state: str or - ~azure.mgmt.resource.databoundaries.models.ProvisioningState - """ - - _validation = { - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "data_boundary": {"key": "dataBoundary", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__(self, *, data_boundary: Optional[Union[str, "_models.DataBoundary"]] = None, **kwargs: Any) -> None: - """ - :keyword data_boundary: The data boundary definition. Known values are: "NotDefined", "Global", - "EU", and "Global". - :paramtype data_boundary: str or ~azure.mgmt.resource.databoundaries.models.DataBoundary - """ - super().__init__(**kwargs) - self.data_boundary = data_boundary - self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.databoundaries.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.resource.databoundaries.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.resource.databoundaries.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.resource.databoundaries.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class SystemData(_serialization.Model): - """Metadata pertaining to creation and last modification of the resource. - - :ivar created_by: The identity that created the resource. - :vartype created_by: str - :ivar created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.mgmt.resource.databoundaries.models.CreatedByType - :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime - :ivar last_modified_by: The identity that last modified the resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Known values - are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or ~azure.mgmt.resource.databoundaries.models.CreatedByType - :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime - """ - - _attribute_map = { - "created_by": {"key": "createdBy", "type": "str"}, - "created_by_type": {"key": "createdByType", "type": "str"}, - "created_at": {"key": "createdAt", "type": "iso-8601"}, - "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, - "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, - "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, - } - - def __init__( - self, - *, - created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - created_at: Optional[datetime.datetime] = None, - last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - last_modified_at: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword created_by: The identity that created the resource. - :paramtype created_by: str - :keyword created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :paramtype created_by_type: str or ~azure.mgmt.resource.databoundaries.models.CreatedByType - :keyword created_at: The timestamp of resource creation (UTC). - :paramtype created_at: ~datetime.datetime - :keyword last_modified_by: The identity that last modified the resource. - :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Known - values are: "User", "Application", "ManagedIdentity", and "Key". - :paramtype last_modified_by_type: str or - ~azure.mgmt.resource.databoundaries.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__(**kwargs) - self.created_by = created_by - self.created_by_type = created_by_type - self.created_at = created_at - self.last_modified_by = last_modified_by - self.last_modified_by_type = last_modified_by_type - self.last_modified_at = last_modified_at diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/__init__.py deleted file mode 100644 index 3cd0a7f40599..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import DataBoundariesOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataBoundariesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_operations.py deleted file mode 100644 index 02f1208a4b58..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_operations.py +++ /dev/null @@ -1,373 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import DataBoundaryMgmtClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_data_boundaries_put_request(default: Union[str, _models.DefaultName], **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/dataBoundaries/{default}") - path_format_arguments = { - "default": _SERIALIZER.url("default", default, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_data_boundaries_get_tenant_request(default: Union[str, _models.DefaultName], **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/dataBoundaries/{default}") - path_format_arguments = { - "default": _SERIALIZER.url("default", default, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_data_boundaries_get_scope_request( - scope: str, default: Union[str, _models.DefaultName], **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}") - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True, min_length=1), - "default": _SERIALIZER.url("default", default, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class DataBoundariesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.databoundaries.DataBoundaryMgmtClient`'s - :attr:`data_boundaries` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: DataBoundaryMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def put( - self, - default: Union[str, _models.DefaultName], - data_boundary_definition: _models.DataBoundaryDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Opt-in tenant to data boundary. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :param data_boundary_definition: The data boundary to opt the tenant to. Required. - :type data_boundary_definition: - ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def put( - self, - default: Union[str, _models.DefaultName], - data_boundary_definition: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Opt-in tenant to data boundary. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :param data_boundary_definition: The data boundary to opt the tenant to. Required. - :type data_boundary_definition: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def put( - self, - default: Union[str, _models.DefaultName], - data_boundary_definition: Union[_models.DataBoundaryDefinition, IO[bytes]], - **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Opt-in tenant to data boundary. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :param data_boundary_definition: The data boundary to opt the tenant to. Is either a - DataBoundaryDefinition type or a IO[bytes] type. Required. - :type data_boundary_definition: - ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition or IO[bytes] - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_boundary_definition, (IOBase, bytes)): - _content = data_boundary_definition - else: - _json = self._serialize.body(data_boundary_definition, "DataBoundaryDefinition") - - _request = build_data_boundaries_put_request( - default=default, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_tenant(self, default: Union[str, _models.DefaultName], **kwargs: Any) -> _models.DataBoundaryDefinition: - """Get data boundary of tenant. - - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) - - _request = build_data_boundaries_get_tenant_request( - default=default, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_scope( - self, scope: str, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> _models.DataBoundaryDefinition: - """Get data boundary at specified scope. - - :param scope: The scope at which the operation is performed. Required. - :type scope: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.resource.databoundaries.models.DefaultName - :return: DataBoundaryDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.databoundaries.models.DataBoundaryDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataBoundaryDefinition] = kwargs.pop("cls", None) - - _request = build_data_boundaries_get_scope_request( - scope=scope, - default=default, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataBoundaryDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/databoundaries/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/__init__.py deleted file mode 100644 index 5f396af91593..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._feature_client import FeatureClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "FeatureClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_configuration.py deleted file mode 100644 index 200d7adb617b..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class FeatureClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for FeatureClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2021-07-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_feature_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_feature_client.py deleted file mode 100644 index 08e4eff3cafa..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_feature_client.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import FeatureClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import FeaturesOperations, SubscriptionFeatureRegistrationsOperations, _FeatureClientOperationsMixin - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class FeatureClient(_FeatureClientOperationsMixin): - """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to - control feature exposure to users. Resource providers typically use this mechanism to provide - public/private preview for new features prior to making them generally available. Users need to - explicitly register for AFEC features to get access to such functionality. - - :ivar features: FeaturesOperations operations - :vartype features: azure.mgmt.resource.features.operations.FeaturesOperations - :ivar subscription_feature_registrations: SubscriptionFeatureRegistrationsOperations operations - :vartype subscription_feature_registrations: - azure.mgmt.resource.features.operations.SubscriptionFeatureRegistrationsOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = FeatureClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) - self.subscription_feature_registrations = SubscriptionFeatureRegistrationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/utils.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/utils.py deleted file mode 100644 index 39b612f39a9b..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_utils/utils.py +++ /dev/null @@ -1,25 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Generic, TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .serialization import Deserializer, Serializer - - -TClient = TypeVar("TClient") -TConfig = TypeVar("TConfig") - - -class ClientMixinABC(ABC, Generic[TClient, TConfig]): - """DO NOT use this class. It is for internal typing use only.""" - - _client: TClient - _config: TConfig - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/__init__.py deleted file mode 100644 index 3b17bd37a7b6..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._feature_client import FeatureClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "FeatureClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_configuration.py deleted file mode 100644 index 917a13148c2d..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class FeatureClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for FeatureClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2021-07-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_feature_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_feature_client.py deleted file mode 100644 index bb8d6152d724..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_feature_client.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import FeatureClientConfiguration -from .operations import FeaturesOperations, SubscriptionFeatureRegistrationsOperations, _FeatureClientOperationsMixin - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class FeatureClient(_FeatureClientOperationsMixin): - """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to - control feature exposure to users. Resource providers typically use this mechanism to provide - public/private preview for new features prior to making them generally available. Users need to - explicitly register for AFEC features to get access to such functionality. - - :ivar features: FeaturesOperations operations - :vartype features: azure.mgmt.resource.features.aio.operations.FeaturesOperations - :ivar subscription_feature_registrations: SubscriptionFeatureRegistrationsOperations operations - :vartype subscription_feature_registrations: - azure.mgmt.resource.features.aio.operations.SubscriptionFeatureRegistrationsOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = FeatureClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) - self.subscription_feature_registrations = SubscriptionFeatureRegistrationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/__init__.py deleted file mode 100644 index 89e139cf2f4f..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _FeatureClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import FeaturesOperations # type: ignore -from ._operations import SubscriptionFeatureRegistrationsOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "FeaturesOperations", - "SubscriptionFeatureRegistrationsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_operations.py deleted file mode 100644 index dd4bd59216cb..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_operations.py +++ /dev/null @@ -1,934 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ..._utils.utils import ClientMixinABC -from ...operations._operations import ( - build_feature_list_operations_request, - build_features_get_request, - build_features_list_all_request, - build_features_list_request, - build_features_register_request, - build_features_unregister_request, - build_subscription_feature_registrations_create_or_update_request, - build_subscription_feature_registrations_delete_request, - build_subscription_feature_registrations_get_request, - build_subscription_feature_registrations_list_all_by_subscription_request, - build_subscription_feature_registrations_list_by_subscription_request, -) -from .._configuration import FeatureClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class _FeatureClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], FeatureClientConfiguration] -): - - @distributed_trace - def list_operations(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Features REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_feature_list_operations_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class FeaturesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.features.aio.FeatureClient`'s - :attr:`features` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_all(self, **kwargs: Any) -> AsyncItemPaged["_models.FeatureResult"]: - """Gets all the preview features that are available through AFEC for the subscription. - - :return: An iterator like instance of either FeatureResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.FeatureResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_features_list_all_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list(self, resource_provider_namespace: str, **kwargs: Any) -> AsyncItemPaged["_models.FeatureResult"]: - """Gets all the preview features in a provider namespace that are available through AFEC for the - subscription. - - :param resource_provider_namespace: The namespace of the resource provider for getting - features. Required. - :type resource_provider_namespace: str - :return: An iterator like instance of either FeatureResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.FeatureResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_features_list_request( - resource_provider_namespace=resource_provider_namespace, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: - """Gets the preview feature with the specified name. - - :param resource_provider_namespace: The resource provider namespace for the feature. Required. - :type resource_provider_namespace: str - :param feature_name: The name of the feature to get. Required. - :type feature_name: str - :return: FeatureResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.FeatureResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) - - _request = build_features_get_request( - resource_provider_namespace=resource_provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def register( - self, resource_provider_namespace: str, feature_name: str, **kwargs: Any - ) -> _models.FeatureResult: - """Registers the preview feature for the subscription. - - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param feature_name: The name of the feature to register. Required. - :type feature_name: str - :return: FeatureResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.FeatureResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) - - _request = build_features_register_request( - resource_provider_namespace=resource_provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def unregister( - self, resource_provider_namespace: str, feature_name: str, **kwargs: Any - ) -> _models.FeatureResult: - """Unregisters the preview feature for the subscription. - - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param feature_name: The name of the feature to unregister. Required. - :type feature_name: str - :return: FeatureResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.FeatureResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) - - _request = build_features_unregister_request( - resource_provider_namespace=resource_provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class SubscriptionFeatureRegistrationsOperations: # pylint: disable=name-too-long - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.features.aio.FeatureClient`'s - :attr:`subscription_feature_registrations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, provider_namespace: str, feature_name: str, **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Returns a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) - - _request = build_subscription_feature_registrations_get_request( - provider_namespace=provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - provider_namespace: str, - feature_name: str, - subscription_feature_registration_type: Optional[_models.SubscriptionFeatureRegistration] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Create or update a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :param subscription_feature_registration_type: Subscription Feature Registration Type details. - Default value is None. - :type subscription_feature_registration_type: - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - provider_namespace: str, - feature_name: str, - subscription_feature_registration_type: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Create or update a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :param subscription_feature_registration_type: Subscription Feature Registration Type details. - Default value is None. - :type subscription_feature_registration_type: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - provider_namespace: str, - feature_name: str, - subscription_feature_registration_type: Optional[ - Union[_models.SubscriptionFeatureRegistration, IO[bytes]] - ] = None, - **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Create or update a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :param subscription_feature_registration_type: Subscription Feature Registration Type details. - Is either a SubscriptionFeatureRegistration type or a IO[bytes] type. Default value is None. - :type subscription_feature_registration_type: - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration or IO[bytes] - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if subscription_feature_registration_type else None - cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if subscription_feature_registration_type else None - _json = None - _content = None - if isinstance(subscription_feature_registration_type, (IOBase, bytes)): - _content = subscription_feature_registration_type - else: - if subscription_feature_registration_type is not None: - _json = self._serialize.body(subscription_feature_registration_type, "SubscriptionFeatureRegistration") - else: - _json = None - - _request = build_subscription_feature_registrations_create_or_update_request( - provider_namespace=provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, provider_namespace: str, feature_name: str, **kwargs: Any) -> None: - """Deletes a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_subscription_feature_registrations_delete_request( - provider_namespace=provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list_by_subscription( - self, provider_namespace: str, **kwargs: Any - ) -> AsyncItemPaged["_models.SubscriptionFeatureRegistration"]: - """Returns subscription feature registrations for given subscription and provider namespace. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscription_feature_registrations_list_by_subscription_request( - provider_namespace=provider_namespace, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_all_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.SubscriptionFeatureRegistration"]: - """Returns subscription feature registrations for given subscription. - - :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscription_feature_registrations_list_all_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/__init__.py deleted file mode 100644 index 2c526158845f..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AuthorizationProfile, - ErrorDefinition, - ErrorResponse, - FeatureOperationsListResult, - FeatureProperties, - FeatureResult, - Operation, - OperationDisplay, - OperationListResult, - ProxyResource, - SubscriptionFeatureRegistration, - SubscriptionFeatureRegistrationList, - SubscriptionFeatureRegistrationProperties, -) - -from ._feature_client_enums import ( # type: ignore - SubscriptionFeatureRegistrationApprovalType, - SubscriptionFeatureRegistrationState, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AuthorizationProfile", - "ErrorDefinition", - "ErrorResponse", - "FeatureOperationsListResult", - "FeatureProperties", - "FeatureResult", - "Operation", - "OperationDisplay", - "OperationListResult", - "ProxyResource", - "SubscriptionFeatureRegistration", - "SubscriptionFeatureRegistrationList", - "SubscriptionFeatureRegistrationProperties", - "SubscriptionFeatureRegistrationApprovalType", - "SubscriptionFeatureRegistrationState", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_feature_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_feature_client_enums.py deleted file mode 100644 index 4243d86e0f58..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_feature_client_enums.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class SubscriptionFeatureRegistrationApprovalType( # pylint: disable=name-too-long - str, Enum, metaclass=CaseInsensitiveEnumMeta -): - """The feature approval type.""" - - NOT_SPECIFIED = "NotSpecified" - APPROVAL_REQUIRED = "ApprovalRequired" - AUTO_APPROVAL = "AutoApproval" - - -class SubscriptionFeatureRegistrationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The state.""" - - NOT_SPECIFIED = "NotSpecified" - NOT_REGISTERED = "NotRegistered" - PENDING = "Pending" - REGISTERING = "Registering" - REGISTERED = "Registered" - UNREGISTERING = "Unregistering" - UNREGISTERED = "Unregistered" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_models_py3.py deleted file mode 100644 index a7afa258a18f..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_models_py3.py +++ /dev/null @@ -1,522 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models - - -class AuthorizationProfile(_serialization.Model): - """Authorization Profile. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar requested_time: The requested time. - :vartype requested_time: ~datetime.datetime - :ivar requester: The requester. - :vartype requester: str - :ivar requester_object_id: The requester object id. - :vartype requester_object_id: str - :ivar approved_time: The approved time. - :vartype approved_time: ~datetime.datetime - :ivar approver: The approver. - :vartype approver: str - """ - - _validation = { - "requested_time": {"readonly": True}, - "requester": {"readonly": True}, - "requester_object_id": {"readonly": True}, - "approved_time": {"readonly": True}, - "approver": {"readonly": True}, - } - - _attribute_map = { - "requested_time": {"key": "requestedTime", "type": "iso-8601"}, - "requester": {"key": "requester", "type": "str"}, - "requester_object_id": {"key": "requesterObjectId", "type": "str"}, - "approved_time": {"key": "approvedTime", "type": "iso-8601"}, - "approver": {"key": "approver", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.requested_time: Optional[datetime.datetime] = None - self.requester: Optional[str] = None - self.requester_object_id: Optional[str] = None - self.approved_time: Optional[datetime.datetime] = None - self.approver: Optional[str] = None - - -class ErrorDefinition(_serialization.Model): - """Error definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Service specific error code which serves as the substatus for the HTTP error code. - :vartype code: str - :ivar message: Description of the error. - :vartype message: str - :ivar details: Internal error details. - :vartype details: list[~azure.mgmt.resource.features.models.ErrorDefinition] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDefinition]"}, - } - - def __init__(self, *, details: Optional[list["_models.ErrorDefinition"]] = None, **kwargs: Any) -> None: - """ - :keyword details: Internal error details. - :paramtype details: list[~azure.mgmt.resource.features.models.ErrorDefinition] - """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.details = details - - -class ErrorResponse(_serialization.Model): - """Error response indicates that the service is not able to process the incoming request. - - :ivar error: The error details. - :vartype error: ~azure.mgmt.resource.features.models.ErrorDefinition - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDefinition"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error details. - :paramtype error: ~azure.mgmt.resource.features.models.ErrorDefinition - """ - super().__init__(**kwargs) - self.error = error - - -class FeatureOperationsListResult(_serialization.Model): - """List of previewed features. - - :ivar value: The array of features. - :vartype value: list[~azure.mgmt.resource.features.models.FeatureResult] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[FeatureResult]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[list["_models.FeatureResult"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword value: The array of features. - :paramtype value: list[~azure.mgmt.resource.features.models.FeatureResult] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class FeatureProperties(_serialization.Model): - """Information about feature. - - :ivar state: The registration state of the feature for the subscription. - :vartype state: str - """ - - _attribute_map = { - "state": {"key": "state", "type": "str"}, - } - - def __init__(self, *, state: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword state: The registration state of the feature for the subscription. - :paramtype state: str - """ - super().__init__(**kwargs) - self.state = state - - -class FeatureResult(_serialization.Model): - """Previewed feature information. - - :ivar name: The name of the feature. - :vartype name: str - :ivar properties: Properties of the previewed feature. - :vartype properties: ~azure.mgmt.resource.features.models.FeatureProperties - :ivar id: The resource ID of the feature. - :vartype id: str - :ivar type: The resource type of the feature. - :vartype type: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "properties": {"key": "properties", "type": "FeatureProperties"}, - "id": {"key": "id", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - properties: Optional["_models.FeatureProperties"] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - type: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the feature. - :paramtype name: str - :keyword properties: Properties of the previewed feature. - :paramtype properties: ~azure.mgmt.resource.features.models.FeatureProperties - :keyword id: The resource ID of the feature. - :paramtype id: str - :keyword type: The resource type of the feature. - :paramtype type: str - """ - super().__init__(**kwargs) - self.name = name - self.properties = properties - self.id = id - self.type = type - - -class Operation(_serialization.Model): - """Microsoft.Features operation. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that represents the operation. - :vartype display: ~azure.mgmt.resource.features.models.OperationDisplay - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - } - - def __init__( - self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: The object that represents the operation. - :paramtype display: ~azure.mgmt.resource.features.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name = name - self.display = display - - -class OperationDisplay(_serialization.Model): - """The object that represents the operation. - - :ivar provider: Service provider: Microsoft.Features. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - """ - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Service provider: Microsoft.Features. - :paramtype provider: str - :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. - :paramtype resource: str - :keyword operation: Operation type: Read, write, delete, etc. - :paramtype operation: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - - -class OperationListResult(_serialization.Model): - """Result of the request to list Microsoft.Features operations. It contains a list of operations - and a URL link to get the next set of results. - - :ivar value: List of Microsoft.Features operations. - :vartype value: list[~azure.mgmt.resource.features.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword value: List of Microsoft.Features operations. - :paramtype value: list[~azure.mgmt.resource.features.models.Operation] - :keyword next_link: URL to get the next set of operation list results if there are any. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ProxyResource(_serialization.Model): - """An Azure proxy resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Azure resource Id. - :vartype id: str - :ivar name: Azure resource name. - :vartype name: str - :ivar type: Azure resource type. - :vartype type: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - - -class SubscriptionFeatureRegistration(ProxyResource): - """Subscription feature registration details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Azure resource Id. - :vartype id: str - :ivar name: Azure resource name. - :vartype name: str - :ivar type: Azure resource type. - :vartype type: str - :ivar properties: - :vartype properties: - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "SubscriptionFeatureRegistrationProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.SubscriptionFeatureRegistrationProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: - :paramtype properties: - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class SubscriptionFeatureRegistrationList(_serialization.Model): - """The list of subscription feature registrations. - - :ivar next_link: The link used to get the next page of subscription feature registrations list. - :vartype next_link: str - :ivar value: The list of subscription feature registrations. - :vartype value: list[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] - """ - - _attribute_map = { - "next_link": {"key": "nextLink", "type": "str"}, - "value": {"key": "value", "type": "[SubscriptionFeatureRegistration]"}, - } - - def __init__( - self, - *, - next_link: Optional[str] = None, - value: Optional[list["_models.SubscriptionFeatureRegistration"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword next_link: The link used to get the next page of subscription feature registrations - list. - :paramtype next_link: str - :keyword value: The list of subscription feature registrations. - :paramtype value: list[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] - """ - super().__init__(**kwargs) - self.next_link = next_link - self.value = value - - -class SubscriptionFeatureRegistrationProperties(_serialization.Model): # pylint: disable=name-too-long - """SubscriptionFeatureRegistrationProperties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar tenant_id: The tenantId. - :vartype tenant_id: str - :ivar subscription_id: The subscriptionId. - :vartype subscription_id: str - :ivar feature_name: The featureName. - :vartype feature_name: str - :ivar display_name: The featureDisplayName. - :vartype display_name: str - :ivar provider_namespace: The providerNamespace. - :vartype provider_namespace: str - :ivar state: The state. Known values are: "NotSpecified", "NotRegistered", "Pending", - "Registering", "Registered", "Unregistering", and "Unregistered". - :vartype state: str or - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationState - :ivar authorization_profile: Authorization Profile. - :vartype authorization_profile: ~azure.mgmt.resource.features.models.AuthorizationProfile - :ivar metadata: Key-value pairs for meta data. - :vartype metadata: dict[str, str] - :ivar release_date: The feature release date. - :vartype release_date: ~datetime.datetime - :ivar registration_date: The feature registration date. - :vartype registration_date: ~datetime.datetime - :ivar documentation_link: The feature documentation link. - :vartype documentation_link: str - :ivar approval_type: The feature approval type. Known values are: "NotSpecified", - "ApprovalRequired", and "AutoApproval". - :vartype approval_type: str or - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationApprovalType - :ivar should_feature_display_in_portal: Indicates whether feature should be displayed in - Portal. - :vartype should_feature_display_in_portal: bool - :ivar description: The feature description. - :vartype description: str - """ - - _validation = { - "tenant_id": {"readonly": True}, - "subscription_id": {"readonly": True}, - "feature_name": {"readonly": True}, - "display_name": {"readonly": True}, - "provider_namespace": {"readonly": True}, - "release_date": {"readonly": True}, - "registration_date": {"readonly": True}, - "documentation_link": {"readonly": True, "max_length": 1000}, - "approval_type": {"readonly": True}, - "description": {"max_length": 1000}, - } - - _attribute_map = { - "tenant_id": {"key": "tenantId", "type": "str"}, - "subscription_id": {"key": "subscriptionId", "type": "str"}, - "feature_name": {"key": "featureName", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - "provider_namespace": {"key": "providerNamespace", "type": "str"}, - "state": {"key": "state", "type": "str"}, - "authorization_profile": {"key": "authorizationProfile", "type": "AuthorizationProfile"}, - "metadata": {"key": "metadata", "type": "{str}"}, - "release_date": {"key": "releaseDate", "type": "iso-8601"}, - "registration_date": {"key": "registrationDate", "type": "iso-8601"}, - "documentation_link": {"key": "documentationLink", "type": "str"}, - "approval_type": {"key": "approvalType", "type": "str"}, - "should_feature_display_in_portal": {"key": "shouldFeatureDisplayInPortal", "type": "bool"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__( - self, - *, - state: Optional[Union[str, "_models.SubscriptionFeatureRegistrationState"]] = None, - authorization_profile: Optional["_models.AuthorizationProfile"] = None, - metadata: Optional[dict[str, str]] = None, - should_feature_display_in_portal: bool = False, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword state: The state. Known values are: "NotSpecified", "NotRegistered", "Pending", - "Registering", "Registered", "Unregistering", and "Unregistered". - :paramtype state: str or - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistrationState - :keyword authorization_profile: Authorization Profile. - :paramtype authorization_profile: ~azure.mgmt.resource.features.models.AuthorizationProfile - :keyword metadata: Key-value pairs for meta data. - :paramtype metadata: dict[str, str] - :keyword should_feature_display_in_portal: Indicates whether feature should be displayed in - Portal. - :paramtype should_feature_display_in_portal: bool - :keyword description: The feature description. - :paramtype description: str - """ - super().__init__(**kwargs) - self.tenant_id: Optional[str] = None - self.subscription_id: Optional[str] = None - self.feature_name: Optional[str] = None - self.display_name: Optional[str] = None - self.provider_namespace: Optional[str] = None - self.state = state - self.authorization_profile = authorization_profile - self.metadata = metadata - self.release_date: Optional[datetime.datetime] = None - self.registration_date: Optional[datetime.datetime] = None - self.documentation_link: Optional[str] = None - self.approval_type: Optional[Union[str, "_models.SubscriptionFeatureRegistrationApprovalType"]] = None - self.should_feature_display_in_portal = should_feature_display_in_portal - self.description = description diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/__init__.py deleted file mode 100644 index 89e139cf2f4f..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _FeatureClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import FeaturesOperations # type: ignore -from ._operations import SubscriptionFeatureRegistrationsOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "FeaturesOperations", - "SubscriptionFeatureRegistrationsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_operations.py deleted file mode 100644 index 172637c64cad..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_operations.py +++ /dev/null @@ -1,1235 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import FeatureClientConfiguration -from .._utils.serialization import Deserializer, Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_feature_list_operations_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Features/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_features_list_all_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_features_list_request(resource_provider_namespace: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features", - ) - path_format_arguments = { - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_features_get_request( - resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}", - ) - path_format_arguments = { - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_features_register_request( - resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register", - ) - path_format_arguments = { - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_features_unregister_request( - resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister", - ) - path_format_arguments = { - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscription_feature_registrations_get_request( # pylint: disable=name-too-long - provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), - "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscription_feature_registrations_create_or_update_request( # pylint: disable=name-too-long - provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), - "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscription_feature_registrations_delete_request( # pylint: disable=name-too-long - provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), - "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscription_feature_registrations_list_by_subscription_request( # pylint: disable=name-too-long - provider_namespace: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscription_feature_registrations_list_all_by_subscription_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/subscriptionFeatureRegistrations" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class _FeatureClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], FeatureClientConfiguration] -): - - @distributed_trace - def list_operations(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Features REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_feature_list_operations_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class FeaturesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.features.FeatureClient`'s - :attr:`features` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_all(self, **kwargs: Any) -> ItemPaged["_models.FeatureResult"]: - """Gets all the preview features that are available through AFEC for the subscription. - - :return: An iterator like instance of either FeatureResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.FeatureResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_features_list_all_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list(self, resource_provider_namespace: str, **kwargs: Any) -> ItemPaged["_models.FeatureResult"]: - """Gets all the preview features in a provider namespace that are available through AFEC for the - subscription. - - :param resource_provider_namespace: The namespace of the resource provider for getting - features. Required. - :type resource_provider_namespace: str - :return: An iterator like instance of either FeatureResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.FeatureResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_features_list_request( - resource_provider_namespace=resource_provider_namespace, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: - """Gets the preview feature with the specified name. - - :param resource_provider_namespace: The resource provider namespace for the feature. Required. - :type resource_provider_namespace: str - :param feature_name: The name of the feature to get. Required. - :type feature_name: str - :return: FeatureResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.FeatureResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) - - _request = build_features_get_request( - resource_provider_namespace=resource_provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def register(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: - """Registers the preview feature for the subscription. - - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param feature_name: The name of the feature to register. Required. - :type feature_name: str - :return: FeatureResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.FeatureResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) - - _request = build_features_register_request( - resource_provider_namespace=resource_provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def unregister(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: - """Unregisters the preview feature for the subscription. - - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param feature_name: The name of the feature to unregister. Required. - :type feature_name: str - :return: FeatureResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.FeatureResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) - - _request = build_features_unregister_request( - resource_provider_namespace=resource_provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("FeatureResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class SubscriptionFeatureRegistrationsOperations: # pylint: disable=name-too-long - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.features.FeatureClient`'s - :attr:`subscription_feature_registrations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: FeatureClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.SubscriptionFeatureRegistration: - """Returns a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) - - _request = build_subscription_feature_registrations_get_request( - provider_namespace=provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - provider_namespace: str, - feature_name: str, - subscription_feature_registration_type: Optional[_models.SubscriptionFeatureRegistration] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Create or update a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :param subscription_feature_registration_type: Subscription Feature Registration Type details. - Default value is None. - :type subscription_feature_registration_type: - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - provider_namespace: str, - feature_name: str, - subscription_feature_registration_type: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Create or update a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :param subscription_feature_registration_type: Subscription Feature Registration Type details. - Default value is None. - :type subscription_feature_registration_type: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - provider_namespace: str, - feature_name: str, - subscription_feature_registration_type: Optional[ - Union[_models.SubscriptionFeatureRegistration, IO[bytes]] - ] = None, - **kwargs: Any - ) -> _models.SubscriptionFeatureRegistration: - """Create or update a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :param subscription_feature_registration_type: Subscription Feature Registration Type details. - Is either a SubscriptionFeatureRegistration type or a IO[bytes] type. Default value is None. - :type subscription_feature_registration_type: - ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration or IO[bytes] - :return: SubscriptionFeatureRegistration or the result of cls(response) - :rtype: ~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if subscription_feature_registration_type else None - cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if subscription_feature_registration_type else None - _json = None - _content = None - if isinstance(subscription_feature_registration_type, (IOBase, bytes)): - _content = subscription_feature_registration_type - else: - if subscription_feature_registration_type is not None: - _json = self._serialize.body(subscription_feature_registration_type, "SubscriptionFeatureRegistration") - else: - _json = None - - _request = build_subscription_feature_registrations_create_or_update_request( - provider_namespace=provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, provider_namespace: str, feature_name: str, **kwargs: Any - ) -> None: - """Deletes a feature registration. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :param feature_name: The feature name. Required. - :type feature_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_subscription_feature_registrations_delete_request( - provider_namespace=provider_namespace, - feature_name=feature_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list_by_subscription( - self, provider_namespace: str, **kwargs: Any - ) -> ItemPaged["_models.SubscriptionFeatureRegistration"]: - """Returns subscription feature registrations for given subscription and provider namespace. - - :param provider_namespace: The provider namespace. Required. - :type provider_namespace: str - :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscription_feature_registrations_list_by_subscription_request( - provider_namespace=provider_namespace, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_all_by_subscription(self, **kwargs: Any) -> ItemPaged["_models.SubscriptionFeatureRegistration"]: - """Returns subscription feature registrations for given subscription. - - :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.models.SubscriptionFeatureRegistration] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscription_feature_registrations_list_all_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/__init__.py deleted file mode 100644 index 8405b984d233..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._management_link_client import ManagementLinkClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ManagementLinkClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_configuration.py deleted file mode 100644 index 8de2de977740..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ManagementLinkClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ManagementLinkClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2016-09-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_management_link_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_management_link_client.py deleted file mode 100644 index 3ebffe0d0702..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_management_link_client.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import ManagementLinkClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import Operations, ResourceLinksOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ManagementLinkClient: - """Azure resources can be linked together to form logical relationships. You can establish links - between resources belonging to different resource groups. However, all the linked resources - must belong to the same subscription. Each resource can be linked to 50 other resources. If any - of the linked resources are deleted or moved, the link owner must clean up the remaining link. - - :ivar operations: Operations operations - :vartype operations: azure.mgmt.resource.links.operations.Operations - :ivar resource_links: ResourceLinksOperations operations - :vartype resource_links: azure.mgmt.resource.links.operations.ResourceLinksOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ManagementLinkClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.resource_links = ResourceLinksOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/__init__.py deleted file mode 100644 index 2d5efa026a0d..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._management_link_client import ManagementLinkClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ManagementLinkClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_configuration.py deleted file mode 100644 index 2a1a28bb860d..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ManagementLinkClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ManagementLinkClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2016-09-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_management_link_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_management_link_client.py deleted file mode 100644 index 1eb6329dc368..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_management_link_client.py +++ /dev/null @@ -1,137 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import ManagementLinkClientConfiguration -from .operations import Operations, ResourceLinksOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ManagementLinkClient: - """Azure resources can be linked together to form logical relationships. You can establish links - between resources belonging to different resource groups. However, all the linked resources - must belong to the same subscription. Each resource can be linked to 50 other resources. If any - of the linked resources are deleted or moved, the link owner must clean up the remaining link. - - :ivar operations: Operations operations - :vartype operations: azure.mgmt.resource.links.aio.operations.Operations - :ivar resource_links: ResourceLinksOperations operations - :vartype resource_links: azure.mgmt.resource.links.aio.operations.ResourceLinksOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ManagementLinkClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.resource_links = ResourceLinksOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/__init__.py deleted file mode 100644 index f1aa3c6ca1ff..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import Operations # type: ignore -from ._operations import ResourceLinksOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Operations", - "ResourceLinksOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_operations.py deleted file mode 100644 index a36db6347964..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_operations.py +++ /dev/null @@ -1,541 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import ( - build_operations_list_request, - build_resource_links_create_or_update_request, - build_resource_links_delete_request, - build_resource_links_get_request, - build_resource_links_list_at_source_scope_request, - build_resource_links_list_at_subscription_request, -) -from .._configuration import ManagementLinkClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class Operations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.links.aio.ManagementLinkClient`'s - :attr:`operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Resources REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_operations_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class ResourceLinksOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.links.aio.ManagementLinkClient`'s - :attr:`resource_links` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def delete(self, link_id: str, **kwargs: Any) -> None: - """Deletes a resource link with the specified ID. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_resource_links_delete_request( - link_id=link_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update( - self, link_id: str, parameters: _models.ResourceLink, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ResourceLink: - """Creates or updates a resource link between the specified resources. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :param parameters: Parameters for creating or updating a resource link. Required. - :type parameters: ~azure.mgmt.resource.links.models.ResourceLink - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, link_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ResourceLink: - """Creates or updates a resource link between the specified resources. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :param parameters: Parameters for creating or updating a resource link. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, link_id: str, parameters: Union[_models.ResourceLink, IO[bytes]], **kwargs: Any - ) -> _models.ResourceLink: - """Creates or updates a resource link between the specified resources. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :param parameters: Parameters for creating or updating a resource link. Is either a - ResourceLink type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.links.models.ResourceLink or IO[bytes] - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ResourceLink") - - _request = build_resource_links_create_or_update_request( - link_id=link_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, link_id: str, **kwargs: Any) -> _models.ResourceLink: - """Gets a resource link with the specified ID. - - :param link_id: The fully qualified Id of the resource link. For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) - - _request = build_resource_links_get_request( - link_id=link_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_at_subscription( - self, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.ResourceLink"]: - """Gets all the linked resources for the subscription. - - :param filter: The filter to apply on the list resource links operation. The supported filter - for list resource links is targetId. For example, $filter=targetId eq {value}. Default value is - None. - :type filter: str - :return: An iterator like instance of either ResourceLink or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.models.ResourceLink] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_resource_links_list_at_subscription_request( - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ResourceLinkResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_at_source_scope( - self, scope: str, filter: Literal["atScope()"] = "atScope()", **kwargs: Any - ) -> AsyncItemPaged["_models.ResourceLink"]: - """Gets a list of resource links at and below the specified source scope. - - :param scope: The fully qualified ID of the scope for getting the resource links. For example, - to list resource links at and under a resource group, set the scope to - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup. Required. - :type scope: str - :param filter: The filter to apply when getting resource links. To get links only at the - specified scope (not below the scope), use Filter.atScope(). Known values are "atScope()" and - None. Default value is "atScope()". - :type filter: str - :return: An iterator like instance of either ResourceLink or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.models.ResourceLink] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_resource_links_list_at_source_scope_request( - scope=scope, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ResourceLinkResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/__init__.py deleted file mode 100644 index 16e885e96822..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - Operation, - OperationDisplay, - OperationListResult, - ResourceLink, - ResourceLinkFilter, - ResourceLinkProperties, - ResourceLinkResult, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Operation", - "OperationDisplay", - "OperationListResult", - "ResourceLink", - "ResourceLinkFilter", - "ResourceLinkProperties", - "ResourceLinkResult", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_models_py3.py deleted file mode 100644 index 82d2a16c2035..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_models_py3.py +++ /dev/null @@ -1,257 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -from typing import Any, Optional, TYPE_CHECKING - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class Operation(_serialization.Model): - """Microsoft.Resources operation. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that represents the operation. - :vartype display: ~azure.mgmt.resource.links.models.OperationDisplay - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - } - - def __init__( - self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: The object that represents the operation. - :paramtype display: ~azure.mgmt.resource.links.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name = name - self.display = display - - -class OperationDisplay(_serialization.Model): - """The object that represents the operation. - - :ivar provider: Service provider: Microsoft.Resources. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - :ivar description: Description of the operation. - :vartype description: str - """ - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Service provider: Microsoft.Resources. - :paramtype provider: str - :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. - :paramtype resource: str - :keyword operation: Operation type: Read, write, delete, etc. - :paramtype operation: str - :keyword description: Description of the operation. - :paramtype description: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - self.description = description - - -class OperationListResult(_serialization.Model): - """Result of the request to list Microsoft.Resources operations. It contains a list of operations - and a URL link to get the next set of results. - - :ivar value: List of Microsoft.Resources operations. - :vartype value: list[~azure.mgmt.resource.links.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword value: List of Microsoft.Resources operations. - :paramtype value: list[~azure.mgmt.resource.links.models.Operation] - :keyword next_link: URL to get the next set of operation list results if there are any. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ResourceLink(_serialization.Model): - """The resource link. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The fully qualified ID of the resource link. - :vartype id: str - :ivar name: The name of the resource link. - :vartype name: str - :ivar type: The resource link object. - :vartype type: JSON - :ivar properties: Properties for resource link. - :vartype properties: ~azure.mgmt.resource.links.models.ResourceLinkProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "object"}, - "properties": {"key": "properties", "type": "ResourceLinkProperties"}, - } - - def __init__(self, *, properties: Optional["_models.ResourceLinkProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Properties for resource link. - :paramtype properties: ~azure.mgmt.resource.links.models.ResourceLinkProperties - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[JSON] = None - self.properties = properties - - -class ResourceLinkFilter(_serialization.Model): - """Resource link filter. - - All required parameters must be populated in order to send to server. - - :ivar target_id: The ID of the target resource. Required. - :vartype target_id: str - """ - - _validation = { - "target_id": {"required": True}, - } - - _attribute_map = { - "target_id": {"key": "targetId", "type": "str"}, - } - - def __init__(self, *, target_id: str, **kwargs: Any) -> None: - """ - :keyword target_id: The ID of the target resource. Required. - :paramtype target_id: str - """ - super().__init__(**kwargs) - self.target_id = target_id - - -class ResourceLinkProperties(_serialization.Model): - """The resource link properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar source_id: The fully qualified ID of the source resource in the link. - :vartype source_id: str - :ivar target_id: The fully qualified ID of the target resource in the link. Required. - :vartype target_id: str - :ivar notes: Notes about the resource link. - :vartype notes: str - """ - - _validation = { - "source_id": {"readonly": True}, - "target_id": {"required": True}, - } - - _attribute_map = { - "source_id": {"key": "sourceId", "type": "str"}, - "target_id": {"key": "targetId", "type": "str"}, - "notes": {"key": "notes", "type": "str"}, - } - - def __init__(self, *, target_id: str, notes: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword target_id: The fully qualified ID of the target resource in the link. Required. - :paramtype target_id: str - :keyword notes: Notes about the resource link. - :paramtype notes: str - """ - super().__init__(**kwargs) - self.source_id: Optional[str] = None - self.target_id = target_id - self.notes = notes - - -class ResourceLinkResult(_serialization.Model): - """List of resource links. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar value: An array of resource links. Required. - :vartype value: list[~azure.mgmt.resource.links.models.ResourceLink] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - "value": {"required": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ResourceLink]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: list["_models.ResourceLink"], **kwargs: Any) -> None: - """ - :keyword value: An array of resource links. Required. - :paramtype value: list[~azure.mgmt.resource.links.models.ResourceLink] - """ - super().__init__(**kwargs) - self.value = value - self.next_link: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/__init__.py deleted file mode 100644 index f1aa3c6ca1ff..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import Operations # type: ignore -from ._operations import ResourceLinksOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Operations", - "ResourceLinksOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_operations.py deleted file mode 100644 index ed9fb7ab43bb..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_operations.py +++ /dev/null @@ -1,679 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import ManagementLinkClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_operations_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_links_delete_request(link_id: str, **kwargs: Any) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - # Construct URL - _url = kwargs.pop("template_url", "/{linkId}") - path_format_arguments = { - "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_resource_links_create_or_update_request( # pylint: disable=name-too-long - link_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{linkId}") - path_format_arguments = { - "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_links_get_request(link_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{linkId}") - path_format_arguments = { - "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_links_list_at_subscription_request( # pylint: disable=name-too-long - subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/links") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_links_list_at_source_scope_request( # pylint: disable=name-too-long - scope: str, *, filter: Literal["atScope()"] = "atScope()", **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Resources/links") - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class Operations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.links.ManagementLinkClient`'s - :attr:`operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Resources REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_operations_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class ResourceLinksOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.links.ManagementLinkClient`'s - :attr:`resource_links` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def delete(self, link_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Deletes a resource link with the specified ID. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_resource_links_delete_request( - link_id=link_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update( - self, link_id: str, parameters: _models.ResourceLink, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ResourceLink: - """Creates or updates a resource link between the specified resources. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :param parameters: Parameters for creating or updating a resource link. Required. - :type parameters: ~azure.mgmt.resource.links.models.ResourceLink - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, link_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ResourceLink: - """Creates or updates a resource link between the specified resources. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :param parameters: Parameters for creating or updating a resource link. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, link_id: str, parameters: Union[_models.ResourceLink, IO[bytes]], **kwargs: Any - ) -> _models.ResourceLink: - """Creates or updates a resource link between the specified resources. - - :param link_id: The fully qualified ID of the resource link. Use the format, - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. - For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :param parameters: Parameters for creating or updating a resource link. Is either a - ResourceLink type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.links.models.ResourceLink or IO[bytes] - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ResourceLink") - - _request = build_resource_links_create_or_update_request( - link_id=link_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, link_id: str, **kwargs: Any) -> _models.ResourceLink: - """Gets a resource link with the specified ID. - - :param link_id: The fully qualified Id of the resource link. For example, - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. - Required. - :type link_id: str - :return: ResourceLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.links.models.ResourceLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) - - _request = build_resource_links_get_request( - link_id=link_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_at_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.ResourceLink"]: - """Gets all the linked resources for the subscription. - - :param filter: The filter to apply on the list resource links operation. The supported filter - for list resource links is targetId. For example, $filter=targetId eq {value}. Default value is - None. - :type filter: str - :return: An iterator like instance of either ResourceLink or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.models.ResourceLink] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_resource_links_list_at_subscription_request( - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ResourceLinkResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_at_source_scope( - self, scope: str, filter: Literal["atScope()"] = "atScope()", **kwargs: Any - ) -> ItemPaged["_models.ResourceLink"]: - """Gets a list of resource links at and below the specified source scope. - - :param scope: The fully qualified ID of the scope for getting the resource links. For example, - to list resource links at and under a resource group, set the scope to - /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup. Required. - :type scope: str - :param filter: The filter to apply when getting resource links. To get links only at the - specified scope (not below the scope), use Filter.atScope(). Known values are "atScope()" and - None. Default value is "atScope()". - :type filter: str - :return: An iterator like instance of either ResourceLink or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.models.ResourceLink] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_resource_links_list_at_source_scope_request( - scope=scope, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ResourceLinkResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/__init__.py deleted file mode 100644 index 1e35dbc6c246..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._management_lock_client import ManagementLockClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ManagementLockClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_configuration.py deleted file mode 100644 index 2a1a45c85c7e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ManagementLockClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ManagementLockClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2016-09-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_management_lock_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_management_lock_client.py deleted file mode 100644 index c2bee0e424fb..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_management_lock_client.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import ManagementLockClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import AuthorizationOperationsOperations, ManagementLocksOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ManagementLockClient: - """Azure resources can be locked to prevent other users in your organization from deleting or - modifying resources. - - :ivar authorization_operations: AuthorizationOperationsOperations operations - :vartype authorization_operations: - azure.mgmt.resource.locks.operations.AuthorizationOperationsOperations - :ivar management_locks: ManagementLocksOperations operations - :vartype management_locks: azure.mgmt.resource.locks.operations.ManagementLocksOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ManagementLockClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.authorization_operations = AuthorizationOperationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.management_locks = ManagementLocksOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/__init__.py deleted file mode 100644 index fc55901ba15e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._management_lock_client import ManagementLockClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ManagementLockClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_configuration.py deleted file mode 100644 index 15cf439017b4..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ManagementLockClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ManagementLockClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2016-09-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_management_lock_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_management_lock_client.py deleted file mode 100644 index f9b2396bb389..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_management_lock_client.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import ManagementLockClientConfiguration -from .operations import AuthorizationOperationsOperations, ManagementLocksOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ManagementLockClient: - """Azure resources can be locked to prevent other users in your organization from deleting or - modifying resources. - - :ivar authorization_operations: AuthorizationOperationsOperations operations - :vartype authorization_operations: - azure.mgmt.resource.locks.aio.operations.AuthorizationOperationsOperations - :ivar management_locks: ManagementLocksOperations operations - :vartype management_locks: azure.mgmt.resource.locks.aio.operations.ManagementLocksOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ManagementLockClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.authorization_operations = AuthorizationOperationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.management_locks = ManagementLocksOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/__init__.py deleted file mode 100644 index 624473253c54..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import AuthorizationOperationsOperations # type: ignore -from ._operations import ManagementLocksOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AuthorizationOperationsOperations", - "ManagementLocksOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_operations.py deleted file mode 100644 index 557e7ccb2c8c..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_operations.py +++ /dev/null @@ -1,1590 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import ( - build_authorization_operations_list_request, - build_management_locks_create_or_update_at_resource_group_level_request, - build_management_locks_create_or_update_at_resource_level_request, - build_management_locks_create_or_update_at_subscription_level_request, - build_management_locks_create_or_update_by_scope_request, - build_management_locks_delete_at_resource_group_level_request, - build_management_locks_delete_at_resource_level_request, - build_management_locks_delete_at_subscription_level_request, - build_management_locks_delete_by_scope_request, - build_management_locks_get_at_resource_group_level_request, - build_management_locks_get_at_resource_level_request, - build_management_locks_get_at_subscription_level_request, - build_management_locks_get_by_scope_request, - build_management_locks_list_at_resource_group_level_request, - build_management_locks_list_at_resource_level_request, - build_management_locks_list_at_subscription_level_request, - build_management_locks_list_by_scope_request, -) -from .._configuration import ManagementLockClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class AuthorizationOperationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.locks.aio.ManagementLockClient`'s - :attr:`authorization_operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Authorization REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_authorization_operations_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class ManagementLocksOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.locks.aio.ManagementLockClient`'s - :attr:`management_locks` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update_at_resource_group_level( - self, - resource_group_name: str, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource group level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group to lock. Required. - :type resource_group_name: str - :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_resource_group_level( - self, - resource_group_name: str, - lock_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource group level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group to lock. Required. - :type resource_group_name: str - :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_resource_group_level( - self, - resource_group_name: str, - lock_name: str, - parameters: Union[_models.ManagementLockObject, IO[bytes]], - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource group level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group to lock. Required. - :type resource_group_name: str - :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Is either a ManagementLockObject type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_at_resource_group_level_request( - resource_group_name=resource_group_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_resource_group_level(self, resource_group_name: str, lock_name: str, **kwargs: Any) -> None: - """Deletes a management lock at the resource group level. - - To delete management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the lock. Required. - :type resource_group_name: str - :param lock_name: The name of lock to delete. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_at_resource_group_level_request( - resource_group_name=resource_group_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_resource_group_level( - self, resource_group_name: str, lock_name: str, **kwargs: Any - ) -> _models.ManagementLockObject: - """Gets a management lock at the resource group level. - - :param resource_group_name: The name of the locked resource group. Required. - :type resource_group_name: str - :param lock_name: The name of the lock to get. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_at_resource_group_level_request( - resource_group_name=resource_group_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update_by_scope( - self, - scope: str, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Create or update a management lock by scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :param parameters: Create or update management lock parameters. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_by_scope( - self, - scope: str, - lock_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Create or update a management lock by scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :param parameters: Create or update management lock parameters. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_by_scope( - self, scope: str, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any - ) -> _models.ManagementLockObject: - """Create or update a management lock by scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :param parameters: Create or update management lock parameters. Is either a - ManagementLockObject type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_by_scope_request( - scope=scope, - lock_name=lock_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> None: - """Delete a management lock by scope. - - :param scope: The scope for the lock. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_by_scope_request( - scope=scope, - lock_name=lock_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: - """Get a management lock by scope. - - :param scope: The scope for the lock. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_by_scope_request( - scope=scope, - lock_name=lock_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource level or any level below the resource. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource to lock. - Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource to lock. - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource to lock. Required. - :type resource_type: str - :param resource_name: The name of the resource to lock. Required. - :type resource_name: str - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: Parameters for creating or updating a management lock. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource level or any level below the resource. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource to lock. - Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource to lock. - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource to lock. Required. - :type resource_type: str - :param resource_name: The name of the resource to lock. Required. - :type resource_name: str - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: Parameters for creating or updating a management lock. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - parameters: Union[_models.ManagementLockObject, IO[bytes]], - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource level or any level below the resource. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource to lock. - Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource to lock. - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource to lock. Required. - :type resource_type: str - :param resource_name: The name of the resource to lock. Required. - :type resource_name: str - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: Parameters for creating or updating a management lock. Is either a - ManagementLockObject type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - **kwargs: Any - ) -> None: - """Deletes the management lock of a resource or any level below the resource. - - To delete management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource with the - lock to delete. Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource with the - lock to delete. Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource with the lock to delete. Required. - :type resource_type: str - :param resource_name: The name of the resource with the lock to delete. Required. - :type resource_name: str - :param lock_name: The name of the lock to delete. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - **kwargs: Any - ) -> _models.ManagementLockObject: - """Get the management lock of a resource or any level below resource. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param parent_resource_path: An extra path parameter needed in some services, like SQL - Databases. Required. - :type parent_resource_path: str - :param resource_type: The type of the resource. Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update_at_subscription_level( - self, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the subscription level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_subscription_level( - self, lock_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the subscription level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_subscription_level( - self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the subscription level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Is either a ManagementLockObject type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_at_subscription_level_request( - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_subscription_level(self, lock_name: str, **kwargs: Any) -> None: - """Deletes the management lock at the subscription level. - - To delete management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock to delete. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_at_subscription_level_request( - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_subscription_level(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: - """Gets a management lock at the subscription level. - - :param lock_name: The name of the lock to get. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_at_subscription_level_request( - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_at_resource_group_level( - self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a resource group. - - :param resource_group_name: The name of the resource group containing the locks to get. - Required. - :type resource_group_name: str - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_at_resource_group_level_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a resource or any level below resource. - - :param resource_group_name: The name of the resource group containing the locked resource. The - name is case insensitive. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the locked resource. Required. - :type resource_type: str - :param resource_name: The name of the locked resource. Required. - :type resource_name: str - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_at_subscription_level( - self, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a subscription. - - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_at_subscription_level_request( - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_scope( - self, scope: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_by_scope_request( - scope=scope, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/__init__.py deleted file mode 100644 index 635bdfd36740..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - ManagementLockListResult, - ManagementLockObject, - ManagementLockOwner, - Operation, - OperationDisplay, - OperationListResult, -) - -from ._management_lock_client_enums import ( # type: ignore - LockLevel, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ManagementLockListResult", - "ManagementLockObject", - "ManagementLockOwner", - "Operation", - "OperationDisplay", - "OperationListResult", - "LockLevel", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_management_lock_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_management_lock_client_enums.py deleted file mode 100644 index 672293de07fe..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_management_lock_client_enums.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class LockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete - means authorized users are able to read and modify the resources, but not delete. ReadOnly - means authorized users can only read from a resource, but they can't modify or delete it. - """ - - NOT_SPECIFIED = "NotSpecified" - CAN_NOT_DELETE = "CanNotDelete" - READ_ONLY = "ReadOnly" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_models_py3.py deleted file mode 100644 index c930fded0649..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_models_py3.py +++ /dev/null @@ -1,231 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models - - -class ManagementLockListResult(_serialization.Model): - """The list of locks. - - :ivar value: The list of locks. - :vartype value: list[~azure.mgmt.resource.locks.models.ManagementLockObject] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[ManagementLockObject]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.ManagementLockObject"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: The list of locks. - :paramtype value: list[~azure.mgmt.resource.locks.models.ManagementLockObject] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ManagementLockObject(_serialization.Model): - """The lock information. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The resource ID of the lock. - :vartype id: str - :ivar type: The resource type of the lock - Microsoft.Authorization/locks. - :vartype type: str - :ivar name: The name of the lock. - :vartype name: str - :ivar level: The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. - CanNotDelete means authorized users are able to read and modify the resources, but not delete. - ReadOnly means authorized users can only read from a resource, but they can't modify or delete - it. Required. Known values are: "NotSpecified", "CanNotDelete", and "ReadOnly". - :vartype level: str or ~azure.mgmt.resource.locks.models.LockLevel - :ivar notes: Notes about the lock. Maximum of 512 characters. - :vartype notes: str - :ivar owners: The owners of the lock. - :vartype owners: list[~azure.mgmt.resource.locks.models.ManagementLockOwner] - """ - - _validation = { - "id": {"readonly": True}, - "type": {"readonly": True}, - "name": {"readonly": True}, - "level": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "level": {"key": "properties.level", "type": "str"}, - "notes": {"key": "properties.notes", "type": "str"}, - "owners": {"key": "properties.owners", "type": "[ManagementLockOwner]"}, - } - - def __init__( - self, - *, - level: Union[str, "_models.LockLevel"], - notes: Optional[str] = None, - owners: Optional[list["_models.ManagementLockOwner"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword level: The level of the lock. Possible values are: NotSpecified, CanNotDelete, - ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but - not delete. ReadOnly means authorized users can only read from a resource, but they can't - modify or delete it. Required. Known values are: "NotSpecified", "CanNotDelete", and - "ReadOnly". - :paramtype level: str or ~azure.mgmt.resource.locks.models.LockLevel - :keyword notes: Notes about the lock. Maximum of 512 characters. - :paramtype notes: str - :keyword owners: The owners of the lock. - :paramtype owners: list[~azure.mgmt.resource.locks.models.ManagementLockOwner] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.type: Optional[str] = None - self.name: Optional[str] = None - self.level = level - self.notes = notes - self.owners = owners - - -class ManagementLockOwner(_serialization.Model): - """Lock owner properties. - - :ivar application_id: The application ID of the lock owner. - :vartype application_id: str - """ - - _attribute_map = { - "application_id": {"key": "applicationId", "type": "str"}, - } - - def __init__(self, *, application_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword application_id: The application ID of the lock owner. - :paramtype application_id: str - """ - super().__init__(**kwargs) - self.application_id = application_id - - -class Operation(_serialization.Model): - """Microsoft.Authorization operation. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that represents the operation. - :vartype display: ~azure.mgmt.resource.locks.models.OperationDisplay - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - } - - def __init__( - self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: The object that represents the operation. - :paramtype display: ~azure.mgmt.resource.locks.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name = name - self.display = display - - -class OperationDisplay(_serialization.Model): - """The object that represents the operation. - - :ivar provider: Service provider: Microsoft.Authorization. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - """ - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Service provider: Microsoft.Authorization. - :paramtype provider: str - :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. - :paramtype resource: str - :keyword operation: Operation type: Read, write, delete, etc. - :paramtype operation: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - - -class OperationListResult(_serialization.Model): - """Result of the request to list Microsoft.Authorization operations. It contains a list of - operations and a URL link to get the next set of results. - - :ivar value: List of Microsoft.Authorization operations. - :vartype value: list[~azure.mgmt.resource.locks.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword value: List of Microsoft.Authorization operations. - :paramtype value: list[~azure.mgmt.resource.locks.models.Operation] - :keyword next_link: URL to get the next set of operation list results if there are any. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/__init__.py deleted file mode 100644 index 624473253c54..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import AuthorizationOperationsOperations # type: ignore -from ._operations import ManagementLocksOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AuthorizationOperationsOperations", - "ManagementLocksOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_operations.py deleted file mode 100644 index c8aa945ea695..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_operations.py +++ /dev/null @@ -1,2117 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import ManagementLockClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_authorization_operations_list_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_create_or_update_at_resource_group_level_request( # pylint: disable=name-too-long - resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_delete_at_resource_group_level_request( # pylint: disable=name-too-long - resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_management_locks_get_at_resource_group_level_request( # pylint: disable=name-too-long - resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_create_or_update_by_scope_request( # pylint: disable=name-too-long - scope: str, lock_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str"), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_delete_by_scope_request( # pylint: disable=name-too-long - scope: str, lock_name: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - # Construct URL - _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str"), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_management_locks_get_by_scope_request( # pylint: disable=name-too-long - scope: str, lock_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str"), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_create_or_update_at_resource_level_request( # pylint: disable=name-too-long - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_delete_at_resource_level_request( # pylint: disable=name-too-long - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_management_locks_get_at_resource_level_request( # pylint: disable=name-too-long - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_create_or_update_at_subscription_level_request( # pylint: disable=name-too-long - lock_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" - ) - path_format_arguments = { - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_delete_at_subscription_level_request( # pylint: disable=name-too-long - lock_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" - ) - path_format_arguments = { - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_management_locks_get_at_subscription_level_request( # pylint: disable=name-too-long - lock_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" - ) - path_format_arguments = { - "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_list_at_resource_group_level_request( # pylint: disable=name-too-long - resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_list_at_resource_level_request( # pylint: disable=name-too-long - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_list_at_subscription_level_request( # pylint: disable=name-too-long - subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_management_locks_list_by_scope_request( # pylint: disable=name-too-long - scope: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks") - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class AuthorizationOperationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.locks.ManagementLockClient`'s - :attr:`authorization_operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Authorization REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_authorization_operations_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class ManagementLocksOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.locks.ManagementLockClient`'s - :attr:`management_locks` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ManagementLockClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update_at_resource_group_level( - self, - resource_group_name: str, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource group level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group to lock. Required. - :type resource_group_name: str - :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_resource_group_level( - self, - resource_group_name: str, - lock_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource group level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group to lock. Required. - :type resource_group_name: str - :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_resource_group_level( - self, - resource_group_name: str, - lock_name: str, - parameters: Union[_models.ManagementLockObject, IO[bytes]], - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource group level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group to lock. Required. - :type resource_group_name: str - :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Is either a ManagementLockObject type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_at_resource_group_level_request( - resource_group_name=resource_group_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_resource_group_level( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, lock_name: str, **kwargs: Any - ) -> None: - """Deletes a management lock at the resource group level. - - To delete management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the lock. Required. - :type resource_group_name: str - :param lock_name: The name of lock to delete. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_at_resource_group_level_request( - resource_group_name=resource_group_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_resource_group_level( - self, resource_group_name: str, lock_name: str, **kwargs: Any - ) -> _models.ManagementLockObject: - """Gets a management lock at the resource group level. - - :param resource_group_name: The name of the locked resource group. Required. - :type resource_group_name: str - :param lock_name: The name of the lock to get. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_at_resource_group_level_request( - resource_group_name=resource_group_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update_by_scope( - self, - scope: str, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Create or update a management lock by scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :param parameters: Create or update management lock parameters. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_by_scope( - self, - scope: str, - lock_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Create or update a management lock by scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :param parameters: Create or update management lock parameters. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_by_scope( - self, scope: str, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any - ) -> _models.ManagementLockObject: - """Create or update a management lock by scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :param parameters: Create or update management lock parameters. Is either a - ManagementLockObject type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_by_scope_request( - scope=scope, - lock_name=lock_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_by_scope( # pylint: disable=inconsistent-return-statements - self, scope: str, lock_name: str, **kwargs: Any - ) -> None: - """Delete a management lock by scope. - - :param scope: The scope for the lock. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_by_scope_request( - scope=scope, - lock_name=lock_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: - """Get a management lock by scope. - - :param scope: The scope for the lock. Required. - :type scope: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_by_scope_request( - scope=scope, - lock_name=lock_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource level or any level below the resource. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource to lock. - Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource to lock. - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource to lock. Required. - :type resource_type: str - :param resource_name: The name of the resource to lock. Required. - :type resource_name: str - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: Parameters for creating or updating a management lock. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource level or any level below the resource. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource to lock. - Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource to lock. - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource to lock. Required. - :type resource_type: str - :param resource_name: The name of the resource to lock. Required. - :type resource_name: str - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: Parameters for creating or updating a management lock. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - parameters: Union[_models.ManagementLockObject, IO[bytes]], - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the resource level or any level below the resource. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource to lock. - Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource to lock. - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource to lock. Required. - :type resource_type: str - :param resource_name: The name of the resource to lock. Required. - :type resource_name: str - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: Parameters for creating or updating a management lock. Is either a - ManagementLockObject type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_resource_level( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - **kwargs: Any - ) -> None: - """Deletes the management lock of a resource or any level below the resource. - - To delete management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param resource_group_name: The name of the resource group containing the resource with the - lock to delete. Required. - :type resource_group_name: str - :param resource_provider_namespace: The resource provider namespace of the resource with the - lock to delete. Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the resource with the lock to delete. Required. - :type resource_type: str - :param resource_name: The name of the resource with the lock to delete. Required. - :type resource_name: str - :param lock_name: The name of the lock to delete. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - lock_name: str, - **kwargs: Any - ) -> _models.ManagementLockObject: - """Get the management lock of a resource or any level below resource. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param parent_resource_path: An extra path parameter needed in some services, like SQL - Databases. Required. - :type parent_resource_path: str - :param resource_type: The type of the resource. Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param lock_name: The name of lock. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update_at_subscription_level( - self, - lock_name: str, - parameters: _models.ManagementLockObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the subscription level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_subscription_level( - self, lock_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the subscription level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_subscription_level( - self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO[bytes]], **kwargs: Any - ) -> _models.ManagementLockObject: - """Creates or updates a management lock at the subscription level. - - When you apply a lock at a parent scope, all child resources inherit the same lock. To create - management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot - contain <, > %, &, :, \\, ?, /, or any control characters. Required. - :type lock_name: str - :param parameters: The management lock parameters. Is either a ManagementLockObject type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.locks.models.ManagementLockObject or IO[bytes] - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ManagementLockObject") - - _request = build_management_locks_create_or_update_at_subscription_level_request( - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_subscription_level( # pylint: disable=inconsistent-return-statements - self, lock_name: str, **kwargs: Any - ) -> None: - """Deletes the management lock at the subscription level. - - To delete management locks, you must have access to Microsoft.Authorization/\\ * or - Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access - Administrator are granted those actions. - - :param lock_name: The name of lock to delete. Required. - :type lock_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_management_locks_delete_at_subscription_level_request( - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_subscription_level(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: - """Gets a management lock at the subscription level. - - :param lock_name: The name of the lock to get. Required. - :type lock_name: str - :return: ManagementLockObject or the result of cls(response) - :rtype: ~azure.mgmt.resource.locks.models.ManagementLockObject - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) - - _request = build_management_locks_get_at_subscription_level_request( - lock_name=lock_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ManagementLockObject", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_at_resource_group_level( - self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a resource group. - - :param resource_group_name: The name of the resource group containing the locks to get. - Required. - :type resource_group_name: str - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_at_resource_group_level_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_at_resource_level( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> ItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a resource or any level below resource. - - :param resource_group_name: The name of the resource group containing the locked resource. The - name is case insensitive. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. Required. - :type parent_resource_path: str - :param resource_type: The resource type of the locked resource. Required. - :type resource_type: str - :param resource_name: The name of the locked resource. Required. - :type resource_name: str - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_at_resource_level_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_at_subscription_level( - self, filter: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a subscription. - - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_at_subscription_level_request( - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_scope( - self, scope: str, filter: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.ManagementLockObject"]: - """Gets all the management locks for a scope. - - :param scope: The scope for the lock. When providing a scope for the assignment, use - '/subscriptions/{subscriptionId}' for subscriptions, - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and - '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' - for resources. Required. - :type scope: str - :param filter: The filter to apply on the operation. Default value is None. - :type filter: str - :return: An iterator like instance of either ManagementLockObject or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.models.ManagementLockObject] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_management_locks_list_by_scope_request( - scope=scope, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ManagementLockListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/__init__.py deleted file mode 100644 index b5f21c6322ac..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._application_client import ApplicationClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ApplicationClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_application_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_application_client.py deleted file mode 100644 index ec25f6e2da2b..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_application_client.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import ApplicationClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import ( - ApplicationDefinitionsOperations, - ApplicationsOperations, - JitRequestsOperations, - _ApplicationClientOperationsMixin, -) - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ApplicationClient(_ApplicationClientOperationsMixin): - """ARM applications. - - :ivar applications: ApplicationsOperations operations - :vartype applications: - azure.mgmt.resource.managedapplications.operations.ApplicationsOperations - :ivar application_definitions: ApplicationDefinitionsOperations operations - :vartype application_definitions: - azure.mgmt.resource.managedapplications.operations.ApplicationDefinitionsOperations - :ivar jit_requests: JitRequestsOperations operations - :vartype jit_requests: azure.mgmt.resource.managedapplications.operations.JitRequestsOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ApplicationClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.applications = ApplicationsOperations(self._client, self._config, self._serialize, self._deserialize) - self.application_definitions = ApplicationDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.jit_requests = JitRequestsOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_configuration.py deleted file mode 100644 index d1beb01cd27e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ApplicationClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ApplicationClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2019-07-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/utils.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/utils.py deleted file mode 100644 index 39b612f39a9b..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_utils/utils.py +++ /dev/null @@ -1,25 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Generic, TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .serialization import Deserializer, Serializer - - -TClient = TypeVar("TClient") -TConfig = TypeVar("TConfig") - - -class ClientMixinABC(ABC, Generic[TClient, TConfig]): - """DO NOT use this class. It is for internal typing use only.""" - - _client: TClient - _config: TConfig - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/__init__.py deleted file mode 100644 index 0a6c2b1f1f57..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._application_client import ApplicationClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ApplicationClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_application_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_application_client.py deleted file mode 100644 index 6e35bbf30bc9..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_application_client.py +++ /dev/null @@ -1,149 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import ApplicationClientConfiguration -from .operations import ( - ApplicationDefinitionsOperations, - ApplicationsOperations, - JitRequestsOperations, - _ApplicationClientOperationsMixin, -) - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ApplicationClient(_ApplicationClientOperationsMixin): - """ARM applications. - - :ivar applications: ApplicationsOperations operations - :vartype applications: - azure.mgmt.resource.managedapplications.aio.operations.ApplicationsOperations - :ivar application_definitions: ApplicationDefinitionsOperations operations - :vartype application_definitions: - azure.mgmt.resource.managedapplications.aio.operations.ApplicationDefinitionsOperations - :ivar jit_requests: JitRequestsOperations operations - :vartype jit_requests: - azure.mgmt.resource.managedapplications.aio.operations.JitRequestsOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ApplicationClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.applications = ApplicationsOperations(self._client, self._config, self._serialize, self._deserialize) - self.application_definitions = ApplicationDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.jit_requests = JitRequestsOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_configuration.py deleted file mode 100644 index d71eb4477d51..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ApplicationClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ApplicationClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2019-07-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/__init__.py deleted file mode 100644 index cdaa4d1b9b46..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _ApplicationClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import ApplicationsOperations # type: ignore -from ._operations import ApplicationDefinitionsOperations # type: ignore -from ._operations import JitRequestsOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ApplicationsOperations", - "ApplicationDefinitionsOperations", - "JitRequestsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_operations.py deleted file mode 100644 index 1271ab5d8fdf..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_operations.py +++ /dev/null @@ -1,2856 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ..._utils.utils import ClientMixinABC -from ...operations._operations import ( - build_application_definitions_create_or_update_by_id_request, - build_application_definitions_create_or_update_request, - build_application_definitions_delete_by_id_request, - build_application_definitions_delete_request, - build_application_definitions_get_by_id_request, - build_application_definitions_get_request, - build_application_definitions_list_by_resource_group_request, - build_application_list_operations_request, - build_applications_create_or_update_by_id_request, - build_applications_create_or_update_request, - build_applications_delete_by_id_request, - build_applications_delete_request, - build_applications_get_by_id_request, - build_applications_get_request, - build_applications_list_by_resource_group_request, - build_applications_list_by_subscription_request, - build_applications_refresh_permissions_request, - build_applications_update_by_id_request, - build_applications_update_request, - build_jit_requests_create_or_update_request, - build_jit_requests_delete_request, - build_jit_requests_get_request, - build_jit_requests_list_by_resource_group_request, - build_jit_requests_list_by_subscription_request, - build_jit_requests_update_request, -) -from .._configuration import ApplicationClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _ApplicationClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], ApplicationClientConfiguration] -): - - @distributed_trace - def list_operations(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Solutions REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_application_list_operations_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class ApplicationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.managedapplications.aio.ApplicationClient`'s - :attr:`applications` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get(self, resource_group_name: str, application_name: str, **kwargs: Any) -> _models.Application: - """Gets the managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - - _request = build_applications_get_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_initial( - self, resource_group_name: str, application_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_applications_delete_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, application_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - application_name=application_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - application_name: str, - parameters: Union[_models.Application, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Application") - - _request = build_applications_create_or_update_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - application_name: str, - parameters: _models.Application, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.Application]: - """Creates a new managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - application_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.Application]: - """Creates a new managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - application_name: str, - parameters: Union[_models.Application, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.Application]: - """Creates a new managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to the create or update a managed application. Is either - a Application type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] - :return: An instance of AsyncLROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - application_name=application_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Application", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.Application].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.Application]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @overload - async def update( - self, - resource_group_name: str, - application_name: str, - parameters: Optional[_models.ApplicationPatchable] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> Optional[_models.Application]: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - application_name: str, - parameters: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> Optional[_models.Application]: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - resource_group_name: str, - application_name: str, - parameters: Optional[Union[_models.ApplicationPatchable, IO[bytes]]] = None, - **kwargs: Any - ) -> Optional[_models.Application]: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to update an existing managed application. Is either a - ApplicationPatchable type or a IO[bytes] type. Default value is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable or - IO[bytes] - :return: Application or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if parameters else None - cls: ClsType[Optional[_models.Application]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if parameters else None - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - if parameters is not None: - _json = self._serialize.body(parameters, "ApplicationPatchable") - else: - _json = None - - _request = build_applications_update_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncItemPaged["_models.Application"]: - """Gets all the applications within a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either Application or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_applications_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ApplicationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.Application"]: - """Gets all the applications within a subscription. - - :return: An iterator like instance of either Application or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_applications_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ApplicationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_by_id(self, application_id: str, **kwargs: Any) -> _models.Application: - """Gets the managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - - _request = build_applications_get_by_id_request( - application_id=application_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_by_id_initial(self, application_id: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_applications_delete_by_id_request( - application_id=application_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_by_id(self, application_id: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Deletes the managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_by_id_initial( - application_id=application_id, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _create_or_update_by_id_initial( - self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Application") - - _request = build_applications_create_or_update_by_id_request( - application_id=application_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update_by_id( - self, - application_id: str, - parameters: _models.Application, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.Application]: - """Creates a new managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update_by_id( - self, application_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.Application]: - """Creates a new managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update_by_id( - self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any - ) -> AsyncLROPoller[_models.Application]: - """Creates a new managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to the create or update a managed application. Is either - a Application type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] - :return: An instance of AsyncLROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_by_id_initial( - application_id=application_id, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Application", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.Application].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.Application]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @overload - async def update_by_id( - self, - application_id: str, - parameters: Optional[_models.Application] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Application: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_by_id( - self, - application_id: str, - parameters: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Application: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update_by_id( - self, application_id: str, parameters: Optional[Union[_models.Application, IO[bytes]]] = None, **kwargs: Any - ) -> _models.Application: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to update an existing managed application. Is either a - Application type or a IO[bytes] type. Default value is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if parameters else None - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if parameters else None - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - if parameters is not None: - _json = self._serialize.body(parameters, "Application") - else: - _json = None - - _request = build_applications_update_by_id_request( - application_id=application_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _refresh_permissions_initial( - self, resource_group_name: str, application_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_applications_refresh_permissions_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_refresh_permissions( - self, resource_group_name: str, application_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Refresh Permissions for application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._refresh_permissions_initial( - resource_group_name=resource_group_name, - application_name=application_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - -class ApplicationDefinitionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.managedapplications.aio.ApplicationClient`'s - :attr:`application_definitions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> _models.ApplicationDefinition: - """Gets the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :return: ApplicationDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - - _request = build_application_definitions_get_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_initial( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_application_definitions_delete_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition to delete. - Required. - :type application_definition_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ApplicationDefinition") - - _request = build_application_definitions_create_or_update_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - application_definition_name: str, - parameters: _models.ApplicationDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update an managed application - definition. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - application_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update an managed application - definition. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update an managed application - definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ApplicationDefinition].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ApplicationDefinition]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> AsyncItemPaged["_models.ApplicationDefinition"]: - """Lists the managed application definitions in a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_application_definitions_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ApplicationDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_by_id( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> _models.ApplicationDefinition: - """Gets the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :return: ApplicationDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - - _request = build_application_definitions_get_by_id_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_by_id_initial( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_application_definitions_delete_by_id_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_by_id( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_by_id_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _create_or_update_by_id_initial( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ApplicationDefinition") - - _request = build_application_definitions_create_or_update_by_id_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update_by_id( - self, - resource_group_name: str, - application_definition_name: str, - parameters: _models.ApplicationDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update a managed application - definition. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update_by_id( - self, - resource_group_name: str, - application_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update a managed application - definition. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update_by_id( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update a managed application - definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_by_id_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ApplicationDefinition].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ApplicationDefinition]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - -class JitRequestsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.managedapplications.aio.ApplicationClient`'s - :attr:`jit_requests` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> _models.JitRequestDefinition: - """Gets the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) - - _request = build_jit_requests_get_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - jit_request_name: str, - parameters: Union[_models.JitRequestDefinition, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "JitRequestDefinition") - - _request = build_jit_requests_create_or_update_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: _models.JitRequestDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.JitRequestDefinition]: - """Creates or updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.JitRequestDefinition]: - """Creates or updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: Union[_models.JitRequestDefinition, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.JitRequestDefinition]: - """Creates or updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Is either a - JitRequestDefinition type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result - of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.JitRequestDefinition].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.JitRequestDefinition]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @overload - async def update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: _models.JitRequestPatchable, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.JitRequestDefinition: - """Updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.JitRequestDefinition: - """Updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: Union[_models.JitRequestPatchable, IO[bytes]], - **kwargs: Any - ) -> _models.JitRequestDefinition: - """Updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Is either a - JitRequestPatchable type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable or - IO[bytes] - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "JitRequestPatchable") - - _request = build_jit_requests_update_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> None: - """Deletes the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_jit_requests_delete_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def list_by_subscription(self, **kwargs: Any) -> _models.JitRequestDefinitionListResult: - """Retrieves all JIT requests within the subscription. - - :return: JitRequestDefinitionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) - - _request = build_jit_requests_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> _models.JitRequestDefinitionListResult: - """Retrieves all JIT requests within the resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: JitRequestDefinitionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) - - _request = build_jit_requests_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/__init__.py deleted file mode 100644 index 4e1a1fb629ae..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/__init__.py +++ /dev/null @@ -1,138 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - Application, - ApplicationArtifact, - ApplicationAuthorization, - ApplicationBillingDetailsDefinition, - ApplicationClientDetails, - ApplicationDefinition, - ApplicationDefinitionArtifact, - ApplicationDefinitionListResult, - ApplicationDeploymentPolicy, - ApplicationJitAccessPolicy, - ApplicationListResult, - ApplicationManagementPolicy, - ApplicationNotificationEndpoint, - ApplicationNotificationPolicy, - ApplicationPackageContact, - ApplicationPackageLockingPolicyDefinition, - ApplicationPackageSupportUrls, - ApplicationPatchable, - ApplicationPolicy, - ApplicationPropertiesPatchable, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - GenericResource, - Identity, - JitApproverDefinition, - JitAuthorizationPolicies, - JitRequestDefinition, - JitRequestDefinitionListResult, - JitRequestPatchable, - JitSchedulingPolicy, - Operation, - OperationAutoGenerated, - OperationDisplay, - OperationDisplayAutoGenerated, - OperationListResult, - Plan, - PlanPatchable, - Resource, - Sku, - UserAssignedResourceIdentity, -) - -from ._application_client_enums import ( # type: ignore - ActionType, - ApplicationArtifactName, - ApplicationArtifactType, - ApplicationDefinitionArtifactName, - ApplicationLockLevel, - ApplicationManagementMode, - DeploymentMode, - JitApprovalMode, - JitApproverType, - JitRequestState, - JitSchedulingType, - Origin, - ProvisioningState, - ResourceIdentityType, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Application", - "ApplicationArtifact", - "ApplicationAuthorization", - "ApplicationBillingDetailsDefinition", - "ApplicationClientDetails", - "ApplicationDefinition", - "ApplicationDefinitionArtifact", - "ApplicationDefinitionListResult", - "ApplicationDeploymentPolicy", - "ApplicationJitAccessPolicy", - "ApplicationListResult", - "ApplicationManagementPolicy", - "ApplicationNotificationEndpoint", - "ApplicationNotificationPolicy", - "ApplicationPackageContact", - "ApplicationPackageLockingPolicyDefinition", - "ApplicationPackageSupportUrls", - "ApplicationPatchable", - "ApplicationPolicy", - "ApplicationPropertiesPatchable", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "GenericResource", - "Identity", - "JitApproverDefinition", - "JitAuthorizationPolicies", - "JitRequestDefinition", - "JitRequestDefinitionListResult", - "JitRequestPatchable", - "JitSchedulingPolicy", - "Operation", - "OperationAutoGenerated", - "OperationDisplay", - "OperationDisplayAutoGenerated", - "OperationListResult", - "Plan", - "PlanPatchable", - "Resource", - "Sku", - "UserAssignedResourceIdentity", - "ActionType", - "ApplicationArtifactName", - "ApplicationArtifactType", - "ApplicationDefinitionArtifactName", - "ApplicationLockLevel", - "ApplicationManagementMode", - "DeploymentMode", - "JitApprovalMode", - "JitApproverType", - "JitRequestState", - "JitSchedulingType", - "Origin", - "ProvisioningState", - "ResourceIdentityType", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_application_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_application_client_enums.py deleted file mode 100644 index ce93a089dad3..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_application_client_enums.py +++ /dev/null @@ -1,138 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" - - INTERNAL = "Internal" - - -class ApplicationArtifactName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The managed application artifact name.""" - - NOT_SPECIFIED = "NotSpecified" - VIEW_DEFINITION = "ViewDefinition" - AUTHORIZATIONS = "Authorizations" - CUSTOM_ROLE_DEFINITION = "CustomRoleDefinition" - - -class ApplicationArtifactType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The managed application artifact type.""" - - NOT_SPECIFIED = "NotSpecified" - TEMPLATE = "Template" - CUSTOM = "Custom" - - -class ApplicationDefinitionArtifactName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The managed application artifact name.""" - - NOT_SPECIFIED = "NotSpecified" - APPLICATION_RESOURCE_TEMPLATE = "ApplicationResourceTemplate" - CREATE_UI_DEFINITION = "CreateUiDefinition" - MAIN_TEMPLATE_PARAMETERS = "MainTemplateParameters" - - -class ApplicationLockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The managed application lock level.""" - - CAN_NOT_DELETE = "CanNotDelete" - READ_ONLY = "ReadOnly" - NONE = "None" - - -class ApplicationManagementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The management mode.""" - - NOT_SPECIFIED = "NotSpecified" - UNMANAGED = "Unmanaged" - MANAGED = "Managed" - - -class DeploymentMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The deployment mode.""" - - NOT_SPECIFIED = "NotSpecified" - INCREMENTAL = "Incremental" - COMPLETE = "Complete" - - -class JitApprovalMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The Jit approval mode.""" - - NOT_SPECIFIED = "NotSpecified" - AUTO_APPROVE = "AutoApprove" - MANUAL_APPROVE = "ManualApprove" - - -class JitApproverType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The approver type.""" - - USER = "user" - GROUP = "group" - - -class JitRequestState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The JIT request state.""" - - NOT_SPECIFIED = "NotSpecified" - PENDING = "Pending" - APPROVED = "Approved" - DENIED = "Denied" - FAILED = "Failed" - CANCELED = "Canceled" - EXPIRED = "Expired" - TIMEOUT = "Timeout" - - -class JitSchedulingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The JIT request scheduling type.""" - - NOT_SPECIFIED = "NotSpecified" - ONCE = "Once" - RECURRING = "Recurring" - - -class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit - logs UX. Default value is "user,system". - """ - - USER = "user" - SYSTEM = "system" - USER_SYSTEM = "user,system" - - -class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Provisioning status of the managed application.""" - - NOT_SPECIFIED = "NotSpecified" - ACCEPTED = "Accepted" - RUNNING = "Running" - READY = "Ready" - CREATING = "Creating" - CREATED = "Created" - DELETING = "Deleting" - DELETED = "Deleted" - CANCELED = "Canceled" - FAILED = "Failed" - SUCCEEDED = "Succeeded" - UPDATING = "Updating" - - -class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The identity type.""" - - SYSTEM_ASSIGNED = "SystemAssigned" - USER_ASSIGNED = "UserAssigned" - SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" - NONE = "None" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_models_py3.py deleted file mode 100644 index c9b872b4907d..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_models_py3.py +++ /dev/null @@ -1,2141 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class Resource(_serialization.Model): - """Resource information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar location: Resource location. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - } - - def __init__(self, *, location: Optional[str] = None, tags: Optional[dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword location: Resource location. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.location = location - self.tags = tags - - -class GenericResource(Resource): - """Resource information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar location: Resource location. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar managed_by: ID of the resource that manages this resource. - :vartype managed_by: str - :ivar sku: The SKU of the resource. - :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "managed_by": {"key": "managedBy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[dict[str, str]] = None, - managed_by: Optional[str] = None, - sku: Optional["_models.Sku"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword managed_by: ID of the resource that manages this resource. - :paramtype managed_by: str - :keyword sku: The SKU of the resource. - :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku - """ - super().__init__(location=location, tags=tags, **kwargs) - self.managed_by = managed_by - self.sku = sku - - -class Application(GenericResource): - """Information about managed application. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar location: Resource location. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar managed_by: ID of the resource that manages this resource. - :vartype managed_by: str - :ivar sku: The SKU of the resource. - :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku - :ivar plan: The plan information. - :vartype plan: ~azure.mgmt.resource.managedapplications.models.Plan - :ivar kind: The kind of the managed application. Allowed values are MarketPlace and - ServiceCatalog. Required. - :vartype kind: str - :ivar identity: The identity of the resource. - :vartype identity: ~azure.mgmt.resource.managedapplications.models.Identity - :ivar managed_resource_group_id: The managed resource group Id. - :vartype managed_resource_group_id: str - :ivar application_definition_id: The fully qualified path of managed application definition Id. - :vartype application_definition_id: str - :ivar parameters: Name and value pairs that define the managed application parameters. It can - be a JObject or a well formed JSON string. - :vartype parameters: JSON - :ivar outputs: Name and value pairs that define the managed application outputs. - :vartype outputs: JSON - :ivar provisioning_state: The managed application provisioning state. Known values are: - "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", - "Canceled", "Failed", "Succeeded", and "Updating". - :vartype provisioning_state: str or - ~azure.mgmt.resource.managedapplications.models.ProvisioningState - :ivar billing_details: The managed application billing details. - :vartype billing_details: - ~azure.mgmt.resource.managedapplications.models.ApplicationBillingDetailsDefinition - :ivar jit_access_policy: The managed application Jit access policy. - :vartype jit_access_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy - :ivar publisher_tenant_id: The publisher tenant Id. - :vartype publisher_tenant_id: str - :ivar authorizations: The read-only authorizations property that is retrieved from the - application package. - :vartype authorizations: - list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] - :ivar management_mode: The managed application management mode. Known values are: - "NotSpecified", "Unmanaged", and "Managed". - :vartype management_mode: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode - :ivar customer_support: The read-only customer support property that is retrieved from the - application package. - :vartype customer_support: - ~azure.mgmt.resource.managedapplications.models.ApplicationPackageContact - :ivar support_urls: The read-only support URLs property that is retrieved from the application - package. - :vartype support_urls: - ~azure.mgmt.resource.managedapplications.models.ApplicationPackageSupportUrls - :ivar artifacts: The collection of managed application artifacts. - :vartype artifacts: list[~azure.mgmt.resource.managedapplications.models.ApplicationArtifact] - :ivar created_by: The client entity that created the JIT request. - :vartype created_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails - :ivar updated_by: The client entity that last updated the JIT request. - :vartype updated_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "kind": {"required": True, "pattern": r"^[-\w\._,\(\)]+$"}, - "outputs": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "billing_details": {"readonly": True}, - "publisher_tenant_id": {"readonly": True}, - "authorizations": {"readonly": True}, - "management_mode": {"readonly": True}, - "customer_support": {"readonly": True}, - "support_urls": {"readonly": True}, - "artifacts": {"readonly": True}, - "created_by": {"readonly": True}, - "updated_by": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "managed_by": {"key": "managedBy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - "plan": {"key": "plan", "type": "Plan"}, - "kind": {"key": "kind", "type": "str"}, - "identity": {"key": "identity", "type": "Identity"}, - "managed_resource_group_id": {"key": "properties.managedResourceGroupId", "type": "str"}, - "application_definition_id": {"key": "properties.applicationDefinitionId", "type": "str"}, - "parameters": {"key": "properties.parameters", "type": "object"}, - "outputs": {"key": "properties.outputs", "type": "object"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "billing_details": {"key": "properties.billingDetails", "type": "ApplicationBillingDetailsDefinition"}, - "jit_access_policy": {"key": "properties.jitAccessPolicy", "type": "ApplicationJitAccessPolicy"}, - "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, - "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, - "management_mode": {"key": "properties.managementMode", "type": "str"}, - "customer_support": {"key": "properties.customerSupport", "type": "ApplicationPackageContact"}, - "support_urls": {"key": "properties.supportUrls", "type": "ApplicationPackageSupportUrls"}, - "artifacts": {"key": "properties.artifacts", "type": "[ApplicationArtifact]"}, - "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, - "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, - } - - def __init__( - self, - *, - kind: str, - location: Optional[str] = None, - tags: Optional[dict[str, str]] = None, - managed_by: Optional[str] = None, - sku: Optional["_models.Sku"] = None, - plan: Optional["_models.Plan"] = None, - identity: Optional["_models.Identity"] = None, - managed_resource_group_id: Optional[str] = None, - application_definition_id: Optional[str] = None, - parameters: Optional[JSON] = None, - jit_access_policy: Optional["_models.ApplicationJitAccessPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword managed_by: ID of the resource that manages this resource. - :paramtype managed_by: str - :keyword sku: The SKU of the resource. - :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku - :keyword plan: The plan information. - :paramtype plan: ~azure.mgmt.resource.managedapplications.models.Plan - :keyword kind: The kind of the managed application. Allowed values are MarketPlace and - ServiceCatalog. Required. - :paramtype kind: str - :keyword identity: The identity of the resource. - :paramtype identity: ~azure.mgmt.resource.managedapplications.models.Identity - :keyword managed_resource_group_id: The managed resource group Id. - :paramtype managed_resource_group_id: str - :keyword application_definition_id: The fully qualified path of managed application definition - Id. - :paramtype application_definition_id: str - :keyword parameters: Name and value pairs that define the managed application parameters. It - can be a JObject or a well formed JSON string. - :paramtype parameters: JSON - :keyword jit_access_policy: The managed application Jit access policy. - :paramtype jit_access_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy - """ - super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) - self.plan = plan - self.kind = kind - self.identity = identity - self.managed_resource_group_id = managed_resource_group_id - self.application_definition_id = application_definition_id - self.parameters = parameters - self.outputs: Optional[JSON] = None - self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None - self.billing_details: Optional["_models.ApplicationBillingDetailsDefinition"] = None - self.jit_access_policy = jit_access_policy - self.publisher_tenant_id: Optional[str] = None - self.authorizations: Optional[list["_models.ApplicationAuthorization"]] = None - self.management_mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None - self.customer_support: Optional["_models.ApplicationPackageContact"] = None - self.support_urls: Optional["_models.ApplicationPackageSupportUrls"] = None - self.artifacts: Optional[list["_models.ApplicationArtifact"]] = None - self.created_by: Optional["_models.ApplicationClientDetails"] = None - self.updated_by: Optional["_models.ApplicationClientDetails"] = None - - -class ApplicationArtifact(_serialization.Model): - """Managed application artifact. - - All required parameters must be populated in order to send to server. - - :ivar name: The managed application artifact name. Required. Known values are: "NotSpecified", - "ViewDefinition", "Authorizations", and "CustomRoleDefinition". - :vartype name: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactName - :ivar uri: The managed application artifact blob uri. Required. - :vartype uri: str - :ivar type: The managed application artifact type. Required. Known values are: "NotSpecified", - "Template", and "Custom". - :vartype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType - """ - - _validation = { - "name": {"required": True}, - "uri": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "uri": {"key": "uri", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, - *, - name: Union[str, "_models.ApplicationArtifactName"], - uri: str, - type: Union[str, "_models.ApplicationArtifactType"], - **kwargs: Any - ) -> None: - """ - :keyword name: The managed application artifact name. Required. Known values are: - "NotSpecified", "ViewDefinition", "Authorizations", and "CustomRoleDefinition". - :paramtype name: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactName - :keyword uri: The managed application artifact blob uri. Required. - :paramtype uri: str - :keyword type: The managed application artifact type. Required. Known values are: - "NotSpecified", "Template", and "Custom". - :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType - """ - super().__init__(**kwargs) - self.name = name - self.uri = uri - self.type = type - - -class ApplicationAuthorization(_serialization.Model): - """The managed application provider authorization. - - All required parameters must be populated in order to send to server. - - :ivar principal_id: The provider's principal identifier. This is the identity that the provider - will use to call ARM to manage the managed application resources. Required. - :vartype principal_id: str - :ivar role_definition_id: The provider's role definition identifier. This role will define all - the permissions that the provider must have on the managed application's container resource - group. This role definition cannot have permission to delete the resource group. Required. - :vartype role_definition_id: str - """ - - _validation = { - "principal_id": {"required": True}, - "role_definition_id": {"required": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, - } - - def __init__(self, *, principal_id: str, role_definition_id: str, **kwargs: Any) -> None: - """ - :keyword principal_id: The provider's principal identifier. This is the identity that the - provider will use to call ARM to manage the managed application resources. Required. - :paramtype principal_id: str - :keyword role_definition_id: The provider's role definition identifier. This role will define - all the permissions that the provider must have on the managed application's container resource - group. This role definition cannot have permission to delete the resource group. Required. - :paramtype role_definition_id: str - """ - super().__init__(**kwargs) - self.principal_id = principal_id - self.role_definition_id = role_definition_id - - -class ApplicationBillingDetailsDefinition(_serialization.Model): - """Managed application billing details definition. - - :ivar resource_usage_id: The managed application resource usage Id. - :vartype resource_usage_id: str - """ - - _attribute_map = { - "resource_usage_id": {"key": "resourceUsageId", "type": "str"}, - } - - def __init__(self, *, resource_usage_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword resource_usage_id: The managed application resource usage Id. - :paramtype resource_usage_id: str - """ - super().__init__(**kwargs) - self.resource_usage_id = resource_usage_id - - -class ApplicationClientDetails(_serialization.Model): - """The application client details to track the entity creating/updating the managed app resource. - - :ivar oid: The client Oid. - :vartype oid: str - :ivar puid: The client Puid. - :vartype puid: str - :ivar application_id: The client application Id. - :vartype application_id: str - """ - - _attribute_map = { - "oid": {"key": "oid", "type": "str"}, - "puid": {"key": "puid", "type": "str"}, - "application_id": {"key": "applicationId", "type": "str"}, - } - - def __init__( - self, - *, - oid: Optional[str] = None, - puid: Optional[str] = None, - application_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword oid: The client Oid. - :paramtype oid: str - :keyword puid: The client Puid. - :paramtype puid: str - :keyword application_id: The client application Id. - :paramtype application_id: str - """ - super().__init__(**kwargs) - self.oid = oid - self.puid = puid - self.application_id = application_id - - -class ApplicationDefinition(GenericResource): - """Information about managed application definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar location: Resource location. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar managed_by: ID of the resource that manages this resource. - :vartype managed_by: str - :ivar sku: The SKU of the resource. - :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku - :ivar lock_level: The managed application lock level. Required. Known values are: - "CanNotDelete", "ReadOnly", and "None". - :vartype lock_level: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationLockLevel - :ivar display_name: The managed application definition display name. - :vartype display_name: str - :ivar is_enabled: A value indicating whether the package is enabled or not. - :vartype is_enabled: bool - :ivar authorizations: The managed application provider authorizations. - :vartype authorizations: - list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] - :ivar artifacts: The collection of managed application artifacts. The portal will use the files - specified as artifacts to construct the user experience of creating a managed application from - a managed application definition. - :vartype artifacts: - list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifact] - :ivar description: The managed application definition description. - :vartype description: str - :ivar package_file_uri: The managed application definition package file Uri. Use this element. - :vartype package_file_uri: str - :ivar main_template: The inline main template json which has resources to be provisioned. It - can be a JObject or well-formed JSON string. - :vartype main_template: JSON - :ivar create_ui_definition: The createUiDefinition json for the backing template with - Microsoft.Solutions/applications resource. It can be a JObject or well-formed JSON string. - :vartype create_ui_definition: JSON - :ivar notification_policy: The managed application notification policy. - :vartype notification_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationNotificationPolicy - :ivar locking_policy: The managed application locking policy. - :vartype locking_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationPackageLockingPolicyDefinition - :ivar deployment_policy: The managed application deployment policy. - :vartype deployment_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationDeploymentPolicy - :ivar management_policy: The managed application management policy that determines publisher's - access to the managed resource group. - :vartype management_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationManagementPolicy - :ivar policies: The managed application provider policies. - :vartype policies: list[~azure.mgmt.resource.managedapplications.models.ApplicationPolicy] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "lock_level": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "managed_by": {"key": "managedBy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - "lock_level": {"key": "properties.lockLevel", "type": "str"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, - "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, - "artifacts": {"key": "properties.artifacts", "type": "[ApplicationDefinitionArtifact]"}, - "description": {"key": "properties.description", "type": "str"}, - "package_file_uri": {"key": "properties.packageFileUri", "type": "str"}, - "main_template": {"key": "properties.mainTemplate", "type": "object"}, - "create_ui_definition": {"key": "properties.createUiDefinition", "type": "object"}, - "notification_policy": {"key": "properties.notificationPolicy", "type": "ApplicationNotificationPolicy"}, - "locking_policy": {"key": "properties.lockingPolicy", "type": "ApplicationPackageLockingPolicyDefinition"}, - "deployment_policy": {"key": "properties.deploymentPolicy", "type": "ApplicationDeploymentPolicy"}, - "management_policy": {"key": "properties.managementPolicy", "type": "ApplicationManagementPolicy"}, - "policies": {"key": "properties.policies", "type": "[ApplicationPolicy]"}, - } - - def __init__( - self, - *, - lock_level: Union[str, "_models.ApplicationLockLevel"], - location: Optional[str] = None, - tags: Optional[dict[str, str]] = None, - managed_by: Optional[str] = None, - sku: Optional["_models.Sku"] = None, - display_name: Optional[str] = None, - is_enabled: Optional[bool] = None, - authorizations: Optional[list["_models.ApplicationAuthorization"]] = None, - artifacts: Optional[list["_models.ApplicationDefinitionArtifact"]] = None, - description: Optional[str] = None, - package_file_uri: Optional[str] = None, - main_template: Optional[JSON] = None, - create_ui_definition: Optional[JSON] = None, - notification_policy: Optional["_models.ApplicationNotificationPolicy"] = None, - locking_policy: Optional["_models.ApplicationPackageLockingPolicyDefinition"] = None, - deployment_policy: Optional["_models.ApplicationDeploymentPolicy"] = None, - management_policy: Optional["_models.ApplicationManagementPolicy"] = None, - policies: Optional[list["_models.ApplicationPolicy"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword managed_by: ID of the resource that manages this resource. - :paramtype managed_by: str - :keyword sku: The SKU of the resource. - :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku - :keyword lock_level: The managed application lock level. Required. Known values are: - "CanNotDelete", "ReadOnly", and "None". - :paramtype lock_level: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationLockLevel - :keyword display_name: The managed application definition display name. - :paramtype display_name: str - :keyword is_enabled: A value indicating whether the package is enabled or not. - :paramtype is_enabled: bool - :keyword authorizations: The managed application provider authorizations. - :paramtype authorizations: - list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] - :keyword artifacts: The collection of managed application artifacts. The portal will use the - files specified as artifacts to construct the user experience of creating a managed application - from a managed application definition. - :paramtype artifacts: - list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifact] - :keyword description: The managed application definition description. - :paramtype description: str - :keyword package_file_uri: The managed application definition package file Uri. Use this - element. - :paramtype package_file_uri: str - :keyword main_template: The inline main template json which has resources to be provisioned. It - can be a JObject or well-formed JSON string. - :paramtype main_template: JSON - :keyword create_ui_definition: The createUiDefinition json for the backing template with - Microsoft.Solutions/applications resource. It can be a JObject or well-formed JSON string. - :paramtype create_ui_definition: JSON - :keyword notification_policy: The managed application notification policy. - :paramtype notification_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationNotificationPolicy - :keyword locking_policy: The managed application locking policy. - :paramtype locking_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationPackageLockingPolicyDefinition - :keyword deployment_policy: The managed application deployment policy. - :paramtype deployment_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationDeploymentPolicy - :keyword management_policy: The managed application management policy that determines - publisher's access to the managed resource group. - :paramtype management_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationManagementPolicy - :keyword policies: The managed application provider policies. - :paramtype policies: list[~azure.mgmt.resource.managedapplications.models.ApplicationPolicy] - """ - super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) - self.lock_level = lock_level - self.display_name = display_name - self.is_enabled = is_enabled - self.authorizations = authorizations - self.artifacts = artifacts - self.description = description - self.package_file_uri = package_file_uri - self.main_template = main_template - self.create_ui_definition = create_ui_definition - self.notification_policy = notification_policy - self.locking_policy = locking_policy - self.deployment_policy = deployment_policy - self.management_policy = management_policy - self.policies = policies - - -class ApplicationDefinitionArtifact(_serialization.Model): - """Application definition artifact. - - All required parameters must be populated in order to send to server. - - :ivar name: The managed application definition artifact name. Required. Known values are: - "NotSpecified", "ApplicationResourceTemplate", "CreateUiDefinition", and - "MainTemplateParameters". - :vartype name: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifactName - :ivar uri: The managed application definition artifact blob uri. Required. - :vartype uri: str - :ivar type: The managed application definition artifact type. Required. Known values are: - "NotSpecified", "Template", and "Custom". - :vartype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType - """ - - _validation = { - "name": {"required": True}, - "uri": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "uri": {"key": "uri", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, - *, - name: Union[str, "_models.ApplicationDefinitionArtifactName"], - uri: str, - type: Union[str, "_models.ApplicationArtifactType"], - **kwargs: Any - ) -> None: - """ - :keyword name: The managed application definition artifact name. Required. Known values are: - "NotSpecified", "ApplicationResourceTemplate", "CreateUiDefinition", and - "MainTemplateParameters". - :paramtype name: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationDefinitionArtifactName - :keyword uri: The managed application definition artifact blob uri. Required. - :paramtype uri: str - :keyword type: The managed application definition artifact type. Required. Known values are: - "NotSpecified", "Template", and "Custom". - :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType - """ - super().__init__(**kwargs) - self.name = name - self.uri = uri - self.type = type - - -class ApplicationDefinitionListResult(_serialization.Model): - """List of managed application definitions. - - :ivar value: The array of managed application definitions. - :vartype value: list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[ApplicationDefinition]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.ApplicationDefinition"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: The array of managed application definitions. - :paramtype value: list[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ApplicationDeploymentPolicy(_serialization.Model): - """Managed application deployment policy. - - All required parameters must be populated in order to send to server. - - :ivar deployment_mode: The managed application deployment mode. Required. Known values are: - "NotSpecified", "Incremental", and "Complete". - :vartype deployment_mode: str or ~azure.mgmt.resource.managedapplications.models.DeploymentMode - """ - - _validation = { - "deployment_mode": {"required": True}, - } - - _attribute_map = { - "deployment_mode": {"key": "deploymentMode", "type": "str"}, - } - - def __init__(self, *, deployment_mode: Union[str, "_models.DeploymentMode"], **kwargs: Any) -> None: - """ - :keyword deployment_mode: The managed application deployment mode. Required. Known values are: - "NotSpecified", "Incremental", and "Complete". - :paramtype deployment_mode: str or - ~azure.mgmt.resource.managedapplications.models.DeploymentMode - """ - super().__init__(**kwargs) - self.deployment_mode = deployment_mode - - -class ApplicationJitAccessPolicy(_serialization.Model): - """Managed application Jit access policy. - - All required parameters must be populated in order to send to server. - - :ivar jit_access_enabled: Whether the JIT access is enabled. Required. - :vartype jit_access_enabled: bool - :ivar jit_approval_mode: JIT approval mode. Known values are: "NotSpecified", "AutoApprove", - and "ManualApprove". - :vartype jit_approval_mode: str or - ~azure.mgmt.resource.managedapplications.models.JitApprovalMode - :ivar jit_approvers: The JIT approvers. - :vartype jit_approvers: - list[~azure.mgmt.resource.managedapplications.models.JitApproverDefinition] - :ivar maximum_jit_access_duration: The maximum duration JIT access is granted. This is an - ISO8601 time period value. - :vartype maximum_jit_access_duration: str - """ - - _validation = { - "jit_access_enabled": {"required": True}, - } - - _attribute_map = { - "jit_access_enabled": {"key": "jitAccessEnabled", "type": "bool"}, - "jit_approval_mode": {"key": "jitApprovalMode", "type": "str"}, - "jit_approvers": {"key": "jitApprovers", "type": "[JitApproverDefinition]"}, - "maximum_jit_access_duration": {"key": "maximumJitAccessDuration", "type": "str"}, - } - - def __init__( - self, - *, - jit_access_enabled: bool, - jit_approval_mode: Optional[Union[str, "_models.JitApprovalMode"]] = None, - jit_approvers: Optional[list["_models.JitApproverDefinition"]] = None, - maximum_jit_access_duration: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword jit_access_enabled: Whether the JIT access is enabled. Required. - :paramtype jit_access_enabled: bool - :keyword jit_approval_mode: JIT approval mode. Known values are: "NotSpecified", "AutoApprove", - and "ManualApprove". - :paramtype jit_approval_mode: str or - ~azure.mgmt.resource.managedapplications.models.JitApprovalMode - :keyword jit_approvers: The JIT approvers. - :paramtype jit_approvers: - list[~azure.mgmt.resource.managedapplications.models.JitApproverDefinition] - :keyword maximum_jit_access_duration: The maximum duration JIT access is granted. This is an - ISO8601 time period value. - :paramtype maximum_jit_access_duration: str - """ - super().__init__(**kwargs) - self.jit_access_enabled = jit_access_enabled - self.jit_approval_mode = jit_approval_mode - self.jit_approvers = jit_approvers - self.maximum_jit_access_duration = maximum_jit_access_duration - - -class ApplicationListResult(_serialization.Model): - """List of managed applications. - - :ivar value: The array of managed applications. - :vartype value: list[~azure.mgmt.resource.managedapplications.models.Application] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[Application]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[list["_models.Application"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword value: The array of managed applications. - :paramtype value: list[~azure.mgmt.resource.managedapplications.models.Application] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ApplicationManagementPolicy(_serialization.Model): - """Managed application management policy. - - :ivar mode: The managed application management mode. Known values are: "NotSpecified", - "Unmanaged", and "Managed". - :vartype mode: str or ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode - """ - - _attribute_map = { - "mode": {"key": "mode", "type": "str"}, - } - - def __init__( - self, *, mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None, **kwargs: Any - ) -> None: - """ - :keyword mode: The managed application management mode. Known values are: "NotSpecified", - "Unmanaged", and "Managed". - :paramtype mode: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode - """ - super().__init__(**kwargs) - self.mode = mode - - -class ApplicationNotificationEndpoint(_serialization.Model): - """Managed application notification endpoint. - - All required parameters must be populated in order to send to server. - - :ivar uri: The managed application notification endpoint uri. Required. - :vartype uri: str - """ - - _validation = { - "uri": {"required": True}, - } - - _attribute_map = { - "uri": {"key": "uri", "type": "str"}, - } - - def __init__(self, *, uri: str, **kwargs: Any) -> None: - """ - :keyword uri: The managed application notification endpoint uri. Required. - :paramtype uri: str - """ - super().__init__(**kwargs) - self.uri = uri - - -class ApplicationNotificationPolicy(_serialization.Model): - """Managed application notification policy. - - All required parameters must be populated in order to send to server. - - :ivar notification_endpoints: The managed application notification endpoint. Required. - :vartype notification_endpoints: - list[~azure.mgmt.resource.managedapplications.models.ApplicationNotificationEndpoint] - """ - - _validation = { - "notification_endpoints": {"required": True}, - } - - _attribute_map = { - "notification_endpoints": {"key": "notificationEndpoints", "type": "[ApplicationNotificationEndpoint]"}, - } - - def __init__( - self, *, notification_endpoints: list["_models.ApplicationNotificationEndpoint"], **kwargs: Any - ) -> None: - """ - :keyword notification_endpoints: The managed application notification endpoint. Required. - :paramtype notification_endpoints: - list[~azure.mgmt.resource.managedapplications.models.ApplicationNotificationEndpoint] - """ - super().__init__(**kwargs) - self.notification_endpoints = notification_endpoints - - -class ApplicationPackageContact(_serialization.Model): - """The application package contact information. - - All required parameters must be populated in order to send to server. - - :ivar contact_name: The contact name. - :vartype contact_name: str - :ivar email: The contact email. Required. - :vartype email: str - :ivar phone: The contact phone number. Required. - :vartype phone: str - """ - - _validation = { - "email": {"required": True}, - "phone": {"required": True}, - } - - _attribute_map = { - "contact_name": {"key": "contactName", "type": "str"}, - "email": {"key": "email", "type": "str"}, - "phone": {"key": "phone", "type": "str"}, - } - - def __init__(self, *, email: str, phone: str, contact_name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword contact_name: The contact name. - :paramtype contact_name: str - :keyword email: The contact email. Required. - :paramtype email: str - :keyword phone: The contact phone number. Required. - :paramtype phone: str - """ - super().__init__(**kwargs) - self.contact_name = contact_name - self.email = email - self.phone = phone - - -class ApplicationPackageLockingPolicyDefinition(_serialization.Model): # pylint: disable=name-too-long - """Managed application locking policy. - - :ivar allowed_actions: The deny assignment excluded actions. - :vartype allowed_actions: list[str] - :ivar allowed_data_actions: The deny assignment excluded data actions. - :vartype allowed_data_actions: list[str] - """ - - _attribute_map = { - "allowed_actions": {"key": "allowedActions", "type": "[str]"}, - "allowed_data_actions": {"key": "allowedDataActions", "type": "[str]"}, - } - - def __init__( - self, - *, - allowed_actions: Optional[list[str]] = None, - allowed_data_actions: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword allowed_actions: The deny assignment excluded actions. - :paramtype allowed_actions: list[str] - :keyword allowed_data_actions: The deny assignment excluded data actions. - :paramtype allowed_data_actions: list[str] - """ - super().__init__(**kwargs) - self.allowed_actions = allowed_actions - self.allowed_data_actions = allowed_data_actions - - -class ApplicationPackageSupportUrls(_serialization.Model): - """The appliance package support URLs. - - :ivar public_azure: The public azure support URL. - :vartype public_azure: str - :ivar government_cloud: The government cloud support URL. - :vartype government_cloud: str - """ - - _attribute_map = { - "public_azure": {"key": "publicAzure", "type": "str"}, - "government_cloud": {"key": "governmentCloud", "type": "str"}, - } - - def __init__( - self, *, public_azure: Optional[str] = None, government_cloud: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword public_azure: The public azure support URL. - :paramtype public_azure: str - :keyword government_cloud: The government cloud support URL. - :paramtype government_cloud: str - """ - super().__init__(**kwargs) - self.public_azure = public_azure - self.government_cloud = government_cloud - - -class ApplicationPatchable(GenericResource): - """Information about managed application. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar location: Resource location. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar managed_by: ID of the resource that manages this resource. - :vartype managed_by: str - :ivar sku: The SKU of the resource. - :vartype sku: ~azure.mgmt.resource.managedapplications.models.Sku - :ivar plan: The plan information. - :vartype plan: ~azure.mgmt.resource.managedapplications.models.PlanPatchable - :ivar kind: The kind of the managed application. Allowed values are MarketPlace and - ServiceCatalog. - :vartype kind: str - :ivar identity: The identity of the resource. - :vartype identity: ~azure.mgmt.resource.managedapplications.models.Identity - :ivar managed_resource_group_id: The managed resource group Id. - :vartype managed_resource_group_id: str - :ivar application_definition_id: The fully qualified path of managed application definition Id. - :vartype application_definition_id: str - :ivar parameters: Name and value pairs that define the managed application parameters. It can - be a JObject or a well formed JSON string. - :vartype parameters: JSON - :ivar outputs: Name and value pairs that define the managed application outputs. - :vartype outputs: JSON - :ivar provisioning_state: The managed application provisioning state. Known values are: - "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", - "Canceled", "Failed", "Succeeded", and "Updating". - :vartype provisioning_state: str or - ~azure.mgmt.resource.managedapplications.models.ProvisioningState - :ivar billing_details: The managed application billing details. - :vartype billing_details: - ~azure.mgmt.resource.managedapplications.models.ApplicationBillingDetailsDefinition - :ivar jit_access_policy: The managed application Jit access policy. - :vartype jit_access_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy - :ivar publisher_tenant_id: The publisher tenant Id. - :vartype publisher_tenant_id: str - :ivar authorizations: The read-only authorizations property that is retrieved from the - application package. - :vartype authorizations: - list[~azure.mgmt.resource.managedapplications.models.ApplicationAuthorization] - :ivar management_mode: The managed application management mode. Known values are: - "NotSpecified", "Unmanaged", and "Managed". - :vartype management_mode: str or - ~azure.mgmt.resource.managedapplications.models.ApplicationManagementMode - :ivar customer_support: The read-only customer support property that is retrieved from the - application package. - :vartype customer_support: - ~azure.mgmt.resource.managedapplications.models.ApplicationPackageContact - :ivar support_urls: The read-only support URLs property that is retrieved from the application - package. - :vartype support_urls: - ~azure.mgmt.resource.managedapplications.models.ApplicationPackageSupportUrls - :ivar artifacts: The collection of managed application artifacts. - :vartype artifacts: list[~azure.mgmt.resource.managedapplications.models.ApplicationArtifact] - :ivar created_by: The client entity that created the JIT request. - :vartype created_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails - :ivar updated_by: The client entity that last updated the JIT request. - :vartype updated_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "kind": {"pattern": r"^[-\w\._,\(\)]+$"}, - "outputs": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "billing_details": {"readonly": True}, - "publisher_tenant_id": {"readonly": True}, - "authorizations": {"readonly": True}, - "management_mode": {"readonly": True}, - "customer_support": {"readonly": True}, - "support_urls": {"readonly": True}, - "artifacts": {"readonly": True}, - "created_by": {"readonly": True}, - "updated_by": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "managed_by": {"key": "managedBy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - "plan": {"key": "plan", "type": "PlanPatchable"}, - "kind": {"key": "kind", "type": "str"}, - "identity": {"key": "identity", "type": "Identity"}, - "managed_resource_group_id": {"key": "properties.managedResourceGroupId", "type": "str"}, - "application_definition_id": {"key": "properties.applicationDefinitionId", "type": "str"}, - "parameters": {"key": "properties.parameters", "type": "object"}, - "outputs": {"key": "properties.outputs", "type": "object"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "billing_details": {"key": "properties.billingDetails", "type": "ApplicationBillingDetailsDefinition"}, - "jit_access_policy": {"key": "properties.jitAccessPolicy", "type": "ApplicationJitAccessPolicy"}, - "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, - "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, - "management_mode": {"key": "properties.managementMode", "type": "str"}, - "customer_support": {"key": "properties.customerSupport", "type": "ApplicationPackageContact"}, - "support_urls": {"key": "properties.supportUrls", "type": "ApplicationPackageSupportUrls"}, - "artifacts": {"key": "properties.artifacts", "type": "[ApplicationArtifact]"}, - "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, - "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[dict[str, str]] = None, - managed_by: Optional[str] = None, - sku: Optional["_models.Sku"] = None, - plan: Optional["_models.PlanPatchable"] = None, - kind: Optional[str] = None, - identity: Optional["_models.Identity"] = None, - managed_resource_group_id: Optional[str] = None, - application_definition_id: Optional[str] = None, - parameters: Optional[JSON] = None, - jit_access_policy: Optional["_models.ApplicationJitAccessPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword managed_by: ID of the resource that manages this resource. - :paramtype managed_by: str - :keyword sku: The SKU of the resource. - :paramtype sku: ~azure.mgmt.resource.managedapplications.models.Sku - :keyword plan: The plan information. - :paramtype plan: ~azure.mgmt.resource.managedapplications.models.PlanPatchable - :keyword kind: The kind of the managed application. Allowed values are MarketPlace and - ServiceCatalog. - :paramtype kind: str - :keyword identity: The identity of the resource. - :paramtype identity: ~azure.mgmt.resource.managedapplications.models.Identity - :keyword managed_resource_group_id: The managed resource group Id. - :paramtype managed_resource_group_id: str - :keyword application_definition_id: The fully qualified path of managed application definition - Id. - :paramtype application_definition_id: str - :keyword parameters: Name and value pairs that define the managed application parameters. It - can be a JObject or a well formed JSON string. - :paramtype parameters: JSON - :keyword jit_access_policy: The managed application Jit access policy. - :paramtype jit_access_policy: - ~azure.mgmt.resource.managedapplications.models.ApplicationJitAccessPolicy - """ - super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) - self.plan = plan - self.kind = kind - self.identity = identity - self.managed_resource_group_id = managed_resource_group_id - self.application_definition_id = application_definition_id - self.parameters = parameters - self.outputs: Optional[JSON] = None - self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None - self.billing_details: Optional["_models.ApplicationBillingDetailsDefinition"] = None - self.jit_access_policy = jit_access_policy - self.publisher_tenant_id: Optional[str] = None - self.authorizations: Optional[list["_models.ApplicationAuthorization"]] = None - self.management_mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None - self.customer_support: Optional["_models.ApplicationPackageContact"] = None - self.support_urls: Optional["_models.ApplicationPackageSupportUrls"] = None - self.artifacts: Optional[list["_models.ApplicationArtifact"]] = None - self.created_by: Optional["_models.ApplicationClientDetails"] = None - self.updated_by: Optional["_models.ApplicationClientDetails"] = None - - -class ApplicationPolicy(_serialization.Model): - """Managed application policy. - - :ivar name: The policy name. - :vartype name: str - :ivar policy_definition_id: The policy definition Id. - :vartype policy_definition_id: str - :ivar parameters: The policy parameters. - :vartype parameters: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, - "parameters": {"key": "parameters", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - policy_definition_id: Optional[str] = None, - parameters: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The policy name. - :paramtype name: str - :keyword policy_definition_id: The policy definition Id. - :paramtype policy_definition_id: str - :keyword parameters: The policy parameters. - :paramtype parameters: str - """ - super().__init__(**kwargs) - self.name = name - self.policy_definition_id = policy_definition_id - self.parameters = parameters - - -class ApplicationPropertiesPatchable(_serialization.Model): - """The managed application properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar managed_resource_group_id: The managed resource group Id. - :vartype managed_resource_group_id: str - :ivar application_definition_id: The fully qualified path of managed application definition Id. - :vartype application_definition_id: str - :ivar parameters: Name and value pairs that define the managed application parameters. It can - be a JObject or a well formed JSON string. - :vartype parameters: JSON - :ivar outputs: Name and value pairs that define the managed application outputs. - :vartype outputs: JSON - :ivar provisioning_state: The managed application provisioning state. Known values are: - "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", - "Canceled", "Failed", "Succeeded", and "Updating". - :vartype provisioning_state: str or - ~azure.mgmt.resource.managedapplications.models.ProvisioningState - """ - - _validation = { - "outputs": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "managed_resource_group_id": {"key": "managedResourceGroupId", "type": "str"}, - "application_definition_id": {"key": "applicationDefinitionId", "type": "str"}, - "parameters": {"key": "parameters", "type": "object"}, - "outputs": {"key": "outputs", "type": "object"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - managed_resource_group_id: Optional[str] = None, - application_definition_id: Optional[str] = None, - parameters: Optional[JSON] = None, - **kwargs: Any - ) -> None: - """ - :keyword managed_resource_group_id: The managed resource group Id. - :paramtype managed_resource_group_id: str - :keyword application_definition_id: The fully qualified path of managed application definition - Id. - :paramtype application_definition_id: str - :keyword parameters: Name and value pairs that define the managed application parameters. It - can be a JObject or a well formed JSON string. - :paramtype parameters: JSON - """ - super().__init__(**kwargs) - self.managed_resource_group_id = managed_resource_group_id - self.application_definition_id = application_definition_id - self.parameters = parameters - self.outputs: Optional[JSON] = None - self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.managedapplications.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.resource.managedapplications.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.resource.managedapplications.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.resource.managedapplications.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class Identity(_serialization.Model): - """Identity for the resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal ID of resource identity. - :vartype principal_id: str - :ivar tenant_id: The tenant ID of resource. - :vartype tenant_id: str - :ivar type: The identity type. Known values are: "SystemAssigned", "UserAssigned", - "SystemAssigned, UserAssigned", and "None". - :vartype type: str or ~azure.mgmt.resource.managedapplications.models.ResourceIdentityType - :ivar user_assigned_identities: The list of user identities associated with the resource. The - user identity dictionary key references will be resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - :vartype user_assigned_identities: dict[str, - ~azure.mgmt.resource.managedapplications.models.UserAssignedResourceIdentity] - """ - - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedResourceIdentity}"}, - } - - def __init__( - self, - *, - type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, - user_assigned_identities: Optional[dict[str, "_models.UserAssignedResourceIdentity"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: The identity type. Known values are: "SystemAssigned", "UserAssigned", - "SystemAssigned, UserAssigned", and "None". - :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.ResourceIdentityType - :keyword user_assigned_identities: The list of user identities associated with the resource. - The user identity dictionary key references will be resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.resource.managedapplications.models.UserAssignedResourceIdentity] - """ - super().__init__(**kwargs) - self.principal_id: Optional[str] = None - self.tenant_id: Optional[str] = None - self.type = type - self.user_assigned_identities = user_assigned_identities - - -class JitApproverDefinition(_serialization.Model): - """JIT approver definition. - - All required parameters must be populated in order to send to server. - - :ivar id: The approver service principal Id. Required. - :vartype id: str - :ivar type: The approver type. Known values are: "user" and "group". - :vartype type: str or ~azure.mgmt.resource.managedapplications.models.JitApproverType - :ivar display_name: The approver display name. - :vartype display_name: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - type: Optional[Union[str, "_models.JitApproverType"]] = None, - display_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The approver service principal Id. Required. - :paramtype id: str - :keyword type: The approver type. Known values are: "user" and "group". - :paramtype type: str or ~azure.mgmt.resource.managedapplications.models.JitApproverType - :keyword display_name: The approver display name. - :paramtype display_name: str - """ - super().__init__(**kwargs) - self.id = id - self.type = type - self.display_name = display_name - - -class JitAuthorizationPolicies(_serialization.Model): - """The JIT authorization policies. - - All required parameters must be populated in order to send to server. - - :ivar principal_id: The the principal id that will be granted JIT access. Required. - :vartype principal_id: str - :ivar role_definition_id: The role definition id that will be granted to the Principal. - Required. - :vartype role_definition_id: str - """ - - _validation = { - "principal_id": {"required": True}, - "role_definition_id": {"required": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, - } - - def __init__(self, *, principal_id: str, role_definition_id: str, **kwargs: Any) -> None: - """ - :keyword principal_id: The the principal id that will be granted JIT access. Required. - :paramtype principal_id: str - :keyword role_definition_id: The role definition id that will be granted to the Principal. - Required. - :paramtype role_definition_id: str - """ - super().__init__(**kwargs) - self.principal_id = principal_id - self.role_definition_id = role_definition_id - - -class JitRequestDefinition(Resource): - """Information about JIT request definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar location: Resource location. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar application_resource_id: The parent application id. - :vartype application_resource_id: str - :ivar publisher_tenant_id: The publisher tenant id. - :vartype publisher_tenant_id: str - :ivar jit_authorization_policies: The JIT authorization policies. - :vartype jit_authorization_policies: - list[~azure.mgmt.resource.managedapplications.models.JitAuthorizationPolicies] - :ivar jit_scheduling_policy: The JIT request properties. - :vartype jit_scheduling_policy: - ~azure.mgmt.resource.managedapplications.models.JitSchedulingPolicy - :ivar provisioning_state: The JIT request provisioning state. Known values are: "NotSpecified", - "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", "Canceled", - "Failed", "Succeeded", and "Updating". - :vartype provisioning_state: str or - ~azure.mgmt.resource.managedapplications.models.ProvisioningState - :ivar jit_request_state: The JIT request state. Known values are: "NotSpecified", "Pending", - "Approved", "Denied", "Failed", "Canceled", "Expired", and "Timeout". - :vartype jit_request_state: str or - ~azure.mgmt.resource.managedapplications.models.JitRequestState - :ivar created_by: The client entity that created the JIT request. - :vartype created_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails - :ivar updated_by: The client entity that last updated the JIT request. - :vartype updated_by: ~azure.mgmt.resource.managedapplications.models.ApplicationClientDetails - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "publisher_tenant_id": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "jit_request_state": {"readonly": True}, - "created_by": {"readonly": True}, - "updated_by": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "application_resource_id": {"key": "properties.applicationResourceId", "type": "str"}, - "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, - "jit_authorization_policies": { - "key": "properties.jitAuthorizationPolicies", - "type": "[JitAuthorizationPolicies]", - }, - "jit_scheduling_policy": {"key": "properties.jitSchedulingPolicy", "type": "JitSchedulingPolicy"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "jit_request_state": {"key": "properties.jitRequestState", "type": "str"}, - "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, - "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[dict[str, str]] = None, - application_resource_id: Optional[str] = None, - jit_authorization_policies: Optional[list["_models.JitAuthorizationPolicies"]] = None, - jit_scheduling_policy: Optional["_models.JitSchedulingPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword application_resource_id: The parent application id. - :paramtype application_resource_id: str - :keyword jit_authorization_policies: The JIT authorization policies. - :paramtype jit_authorization_policies: - list[~azure.mgmt.resource.managedapplications.models.JitAuthorizationPolicies] - :keyword jit_scheduling_policy: The JIT request properties. - :paramtype jit_scheduling_policy: - ~azure.mgmt.resource.managedapplications.models.JitSchedulingPolicy - """ - super().__init__(location=location, tags=tags, **kwargs) - self.application_resource_id = application_resource_id - self.publisher_tenant_id: Optional[str] = None - self.jit_authorization_policies = jit_authorization_policies - self.jit_scheduling_policy = jit_scheduling_policy - self.provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None - self.jit_request_state: Optional[Union[str, "_models.JitRequestState"]] = None - self.created_by: Optional["_models.ApplicationClientDetails"] = None - self.updated_by: Optional["_models.ApplicationClientDetails"] = None - - -class JitRequestDefinitionListResult(_serialization.Model): - """List of JIT requests. - - :ivar value: The array of Jit request definition. - :vartype value: list[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[JitRequestDefinition]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.JitRequestDefinition"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: The array of Jit request definition. - :paramtype value: list[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class JitRequestPatchable(_serialization.Model): - """Information about JIT request. - - :ivar tags: Jit request tags. - :vartype tags: dict[str, str] - """ - - _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - } - - def __init__(self, *, tags: Optional[dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword tags: Jit request tags. - :paramtype tags: dict[str, str] - """ - super().__init__(**kwargs) - self.tags = tags - - -class JitSchedulingPolicy(_serialization.Model): - """The JIT scheduling policies. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of JIT schedule. Required. Known values are: "NotSpecified", "Once", and - "Recurring". - :vartype type: str or ~azure.mgmt.resource.managedapplications.models.JitSchedulingType - :ivar duration: The required duration of the JIT request. Required. - :vartype duration: ~datetime.timedelta - :ivar start_time: The start time of the request. Required. - :vartype start_time: ~datetime.datetime - """ - - _validation = { - "type": {"required": True, "readonly": True}, - "duration": {"required": True}, - "start_time": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "duration": {"key": "duration", "type": "duration"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - } - - def __init__(self, *, duration: datetime.timedelta, start_time: datetime.datetime, **kwargs: Any) -> None: - """ - :keyword duration: The required duration of the JIT request. Required. - :paramtype duration: ~datetime.timedelta - :keyword start_time: The start time of the request. Required. - :paramtype start_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.type: Optional[Union[str, "_models.JitSchedulingType"]] = None - self.duration = duration - self.start_time = start_time - - -class Operation(_serialization.Model): - """Details of a REST API operation, returned from the Resource Provider Operations API. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: - "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". - :vartype name: str - :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for - data-plane operations and "false" for ARM/control-plane operations. - :vartype is_data_action: bool - :ivar display: Localized display information for this particular operation. - :vartype display: ~azure.mgmt.resource.managedapplications.models.OperationDisplay - :ivar origin: The intended executor of the operation; as in Resource Based Access Control - (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", - and "user,system". - :vartype origin: str or ~azure.mgmt.resource.managedapplications.models.Origin - :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for - internal only APIs. "Internal" - :vartype action_type: str or ~azure.mgmt.resource.managedapplications.models.ActionType - """ - - _validation = { - "name": {"readonly": True}, - "is_data_action": {"readonly": True}, - "origin": {"readonly": True}, - "action_type": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "is_data_action": {"key": "isDataAction", "type": "bool"}, - "display": {"key": "display", "type": "OperationDisplay"}, - "origin": {"key": "origin", "type": "str"}, - "action_type": {"key": "actionType", "type": "str"}, - } - - def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: - """ - :keyword display: Localized display information for this particular operation. - :paramtype display: ~azure.mgmt.resource.managedapplications.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.is_data_action: Optional[bool] = None - self.display = display - self.origin: Optional[Union[str, "_models.Origin"]] = None - self.action_type: Optional[Union[str, "_models.ActionType"]] = None - - -class OperationAutoGenerated(_serialization.Model): - """Microsoft.Solutions operation. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that represents the operation. - :vartype display: ~azure.mgmt.resource.managedapplications.models.OperationDisplayAutoGenerated - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplayAutoGenerated"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - display: Optional["_models.OperationDisplayAutoGenerated"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: The object that represents the operation. - :paramtype display: - ~azure.mgmt.resource.managedapplications.models.OperationDisplayAutoGenerated - """ - super().__init__(**kwargs) - self.name = name - self.display = display - - -class OperationDisplay(_serialization.Model): - """Localized display information for this particular operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft - Monitoring Insights" or "Microsoft Compute". - :vartype provider: str - :ivar resource: The localized friendly name of the resource type related to this operation. - E.g. "Virtual Machines" or "Job Schedule Collections". - :vartype resource: str - :ivar operation: The concise, localized friendly name for the operation; suitable for - dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". - :vartype operation: str - :ivar description: The short, localized friendly description of the operation; suitable for - tool tips and detailed views. - :vartype description: str - """ - - _validation = { - "provider": {"readonly": True}, - "resource": {"readonly": True}, - "operation": {"readonly": True}, - "description": {"readonly": True}, - } - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.provider: Optional[str] = None - self.resource: Optional[str] = None - self.operation: Optional[str] = None - self.description: Optional[str] = None - - -class OperationDisplayAutoGenerated(_serialization.Model): - """The object that represents the operation. - - :ivar provider: Service provider: Microsoft.Solutions. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Application, JitRequest, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - """ - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Service provider: Microsoft.Solutions. - :paramtype provider: str - :keyword resource: Resource on which the operation is performed: Application, JitRequest, etc. - :paramtype resource: str - :keyword operation: Operation type: Read, write, delete, etc. - :paramtype operation: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - - -class OperationListResult(_serialization.Model): - """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link - to get the next set of results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of operations supported by the resource provider. - :vartype value: list[~azure.mgmt.resource.managedapplications.models.Operation] - :ivar next_link: URL to get the next set of operation list results (if there are any). - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value: Optional[list["_models.Operation"]] = None - self.next_link: Optional[str] = None - - -class Plan(_serialization.Model): - """Plan for the managed application. - - All required parameters must be populated in order to send to server. - - :ivar name: The plan name. Required. - :vartype name: str - :ivar publisher: The publisher ID. Required. - :vartype publisher: str - :ivar product: The product code. Required. - :vartype product: str - :ivar promotion_code: The promotion code. - :vartype promotion_code: str - :ivar version: The plan's version. Required. - :vartype version: str - """ - - _validation = { - "name": {"required": True}, - "publisher": {"required": True}, - "product": {"required": True}, - "version": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "publisher": {"key": "publisher", "type": "str"}, - "product": {"key": "product", "type": "str"}, - "promotion_code": {"key": "promotionCode", "type": "str"}, - "version": {"key": "version", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - publisher: str, - product: str, - version: str, - promotion_code: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The plan name. Required. - :paramtype name: str - :keyword publisher: The publisher ID. Required. - :paramtype publisher: str - :keyword product: The product code. Required. - :paramtype product: str - :keyword promotion_code: The promotion code. - :paramtype promotion_code: str - :keyword version: The plan's version. Required. - :paramtype version: str - """ - super().__init__(**kwargs) - self.name = name - self.publisher = publisher - self.product = product - self.promotion_code = promotion_code - self.version = version - - -class PlanPatchable(_serialization.Model): - """Plan for the managed application. - - :ivar name: The plan name. - :vartype name: str - :ivar publisher: The publisher ID. - :vartype publisher: str - :ivar product: The product code. - :vartype product: str - :ivar promotion_code: The promotion code. - :vartype promotion_code: str - :ivar version: The plan's version. - :vartype version: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "publisher": {"key": "publisher", "type": "str"}, - "product": {"key": "product", "type": "str"}, - "promotion_code": {"key": "promotionCode", "type": "str"}, - "version": {"key": "version", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - publisher: Optional[str] = None, - product: Optional[str] = None, - promotion_code: Optional[str] = None, - version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The plan name. - :paramtype name: str - :keyword publisher: The publisher ID. - :paramtype publisher: str - :keyword product: The product code. - :paramtype product: str - :keyword promotion_code: The promotion code. - :paramtype promotion_code: str - :keyword version: The plan's version. - :paramtype version: str - """ - super().__init__(**kwargs) - self.name = name - self.publisher = publisher - self.product = product - self.promotion_code = promotion_code - self.version = version - - -class Sku(_serialization.Model): - """SKU for the resource. - - All required parameters must be populated in order to send to server. - - :ivar name: The SKU name. Required. - :vartype name: str - :ivar tier: The SKU tier. - :vartype tier: str - :ivar size: The SKU size. - :vartype size: str - :ivar family: The SKU family. - :vartype family: str - :ivar model: The SKU model. - :vartype model: str - :ivar capacity: The SKU capacity. - :vartype capacity: int - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "tier": {"key": "tier", "type": "str"}, - "size": {"key": "size", "type": "str"}, - "family": {"key": "family", "type": "str"}, - "model": {"key": "model", "type": "str"}, - "capacity": {"key": "capacity", "type": "int"}, - } - - def __init__( - self, - *, - name: str, - tier: Optional[str] = None, - size: Optional[str] = None, - family: Optional[str] = None, - model: Optional[str] = None, - capacity: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The SKU name. Required. - :paramtype name: str - :keyword tier: The SKU tier. - :paramtype tier: str - :keyword size: The SKU size. - :paramtype size: str - :keyword family: The SKU family. - :paramtype family: str - :keyword model: The SKU model. - :paramtype model: str - :keyword capacity: The SKU capacity. - :paramtype capacity: int - """ - super().__init__(**kwargs) - self.name = name - self.tier = tier - self.size = size - self.family = family - self.model = model - self.capacity = capacity - - -class UserAssignedResourceIdentity(_serialization.Model): - """Represents the user assigned identity that is contained within the UserAssignedIdentities - dictionary on ResourceIdentity. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal id of user assigned identity. - :vartype principal_id: str - :ivar tenant_id: The tenant id of user assigned identity. - :vartype tenant_id: str - """ - - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.principal_id: Optional[str] = None - self.tenant_id: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/__init__.py deleted file mode 100644 index cdaa4d1b9b46..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _ApplicationClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import ApplicationsOperations # type: ignore -from ._operations import ApplicationDefinitionsOperations # type: ignore -from ._operations import JitRequestsOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ApplicationsOperations", - "ApplicationDefinitionsOperations", - "JitRequestsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_operations.py deleted file mode 100644 index b8c49dd259a7..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_operations.py +++ /dev/null @@ -1,3622 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._configuration import ApplicationClientConfiguration -from .._utils.serialization import Deserializer, Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_application_list_operations_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Solutions/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_get_request( - resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_delete_request( - resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_create_or_update_request( # pylint: disable=name-too-long - resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_update_request( - resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_list_by_resource_group_request( # pylint: disable=name-too-long - resource_group_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_list_by_subscription_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/applications") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_get_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{applicationId}") - path_format_arguments = { - "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_delete_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{applicationId}") - path_format_arguments = { - "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_create_or_update_by_id_request( # pylint: disable=name-too-long - application_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{applicationId}") - path_format_arguments = { - "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_update_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{applicationId}") - path_format_arguments = { - "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_applications_refresh_permissions_request( # pylint: disable=name-too-long - resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_get_request( # pylint: disable=name-too-long - resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationDefinitionName": _SERIALIZER.url( - "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_delete_request( # pylint: disable=name-too-long - resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationDefinitionName": _SERIALIZER.url( - "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_create_or_update_request( # pylint: disable=name-too-long - resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationDefinitionName": _SERIALIZER.url( - "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_list_by_resource_group_request( # pylint: disable=name-too-long - resource_group_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_get_by_id_request( # pylint: disable=name-too-long - resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationDefinitionName": _SERIALIZER.url( - "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_delete_by_id_request( # pylint: disable=name-too-long - resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationDefinitionName": _SERIALIZER.url( - "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_application_definitions_create_or_update_by_id_request( # pylint: disable=name-too-long - resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "applicationDefinitionName": _SERIALIZER.url( - "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_jit_requests_get_request( - resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_jit_requests_create_or_update_request( # pylint: disable=name-too-long - resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_jit_requests_update_request( - resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_jit_requests_delete_request( - resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_jit_requests_list_by_subscription_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/jitRequests") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_jit_requests_list_by_resource_group_request( # pylint: disable=name-too-long - resource_group_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests", - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class _ApplicationClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], ApplicationClientConfiguration] -): - - @distributed_trace - def list_operations(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Solutions REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_application_list_operations_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class ApplicationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.managedapplications.ApplicationClient`'s - :attr:`applications` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, resource_group_name: str, application_name: str, **kwargs: Any) -> _models.Application: - """Gets the managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - - _request = build_applications_get_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_initial(self, resource_group_name: str, application_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_applications_delete_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete(self, resource_group_name: str, application_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes the managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - application_name=application_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - application_name: str, - parameters: Union[_models.Application, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Application") - - _request = build_applications_create_or_update_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - application_name: str, - parameters: _models.Application, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.Application]: - """Creates a new managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - application_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.Application]: - """Creates a new managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - application_name: str, - parameters: Union[_models.Application, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.Application]: - """Creates a new managed application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to the create or update a managed application. Is either - a Application type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] - :return: An instance of LROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - application_name=application_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Application", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.Application].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.Application]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @overload - def update( - self, - resource_group_name: str, - application_name: str, - parameters: Optional[_models.ApplicationPatchable] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> Optional[_models.Application]: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - application_name: str, - parameters: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> Optional[_models.Application]: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - resource_group_name: str, - application_name: str, - parameters: Optional[Union[_models.ApplicationPatchable, IO[bytes]]] = None, - **kwargs: Any - ) -> Optional[_models.Application]: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :param parameters: Parameters supplied to update an existing managed application. Is either a - ApplicationPatchable type or a IO[bytes] type. Default value is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationPatchable or - IO[bytes] - :return: Application or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if parameters else None - cls: ClsType[Optional[_models.Application]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if parameters else None - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - if parameters is not None: - _json = self._serialize.body(parameters, "ApplicationPatchable") - else: - _json = None - - _request = build_applications_update_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> ItemPaged["_models.Application"]: - """Gets all the applications within a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either Application or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_applications_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ApplicationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> ItemPaged["_models.Application"]: - """Gets all the applications within a subscription. - - :return: An iterator like instance of either Application or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_applications_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ApplicationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_by_id(self, application_id: str, **kwargs: Any) -> _models.Application: - """Gets the managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - - _request = build_applications_get_by_id_request( - application_id=application_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_by_id_initial(self, application_id: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_applications_delete_by_id_request( - application_id=application_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_by_id(self, application_id: str, **kwargs: Any) -> LROPoller[None]: - """Deletes the managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_by_id_initial( - application_id=application_id, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _create_or_update_by_id_initial( - self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Application") - - _request = build_applications_create_or_update_by_id_request( - application_id=application_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update_by_id( - self, - application_id: str, - parameters: _models.Application, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.Application]: - """Creates a new managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update_by_id( - self, application_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.Application]: - """Creates a new managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to the create or update a managed application. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update_by_id( - self, application_id: str, parameters: Union[_models.Application, IO[bytes]], **kwargs: Any - ) -> LROPoller[_models.Application]: - """Creates a new managed application. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to the create or update a managed application. Is either - a Application type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] - :return: An instance of LROPoller that returns either Application or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.Application] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_by_id_initial( - application_id=application_id, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Application", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.Application].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.Application]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @overload - def update_by_id( - self, - application_id: str, - parameters: Optional[_models.Application] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Application: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_by_id( - self, - application_id: str, - parameters: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Application: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to update an existing managed application. Default value - is None. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_by_id( - self, application_id: str, parameters: Optional[Union[_models.Application, IO[bytes]]] = None, **kwargs: Any - ) -> _models.Application: - """Updates an existing managed application. The only value that can be updated via PATCH currently - is the tags. - - :param application_id: The fully qualified ID of the managed application, including the managed - application name and the managed application resource type. Use the format, - /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. - Required. - :type application_id: str - :param parameters: Parameters supplied to update an existing managed application. Is either a - Application type or a IO[bytes] type. Default value is None. - :type parameters: ~azure.mgmt.resource.managedapplications.models.Application or IO[bytes] - :return: Application or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.Application - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if parameters else None - cls: ClsType[_models.Application] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if parameters else None - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - if parameters is not None: - _json = self._serialize.body(parameters, "Application") - else: - _json = None - - _request = build_applications_update_by_id_request( - application_id=application_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Application", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _refresh_permissions_initial( - self, resource_group_name: str, application_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_applications_refresh_permissions_request( - resource_group_name=resource_group_name, - application_name=application_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_refresh_permissions( - self, resource_group_name: str, application_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Refresh Permissions for application. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_name: The name of the managed application. Required. - :type application_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._refresh_permissions_initial( - resource_group_name=resource_group_name, - application_name=application_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - -class ApplicationDefinitionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.managedapplications.ApplicationClient`'s - :attr:`application_definitions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> _models.ApplicationDefinition: - """Gets the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :return: ApplicationDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - - _request = build_application_definitions_get_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_initial( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_application_definitions_delete_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition to delete. - Required. - :type application_definition_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ApplicationDefinition") - - _request = build_application_definitions_create_or_update_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - application_definition_name: str, - parameters: _models.ApplicationDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update an managed application - definition. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - application_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update an managed application - definition. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update an managed application - definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or - IO[bytes] - :return: An instance of LROPoller that returns either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ApplicationDefinition].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ApplicationDefinition]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> ItemPaged["_models.ApplicationDefinition"]: - """Lists the managed application definitions in a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_application_definitions_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ApplicationDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_by_id( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> _models.ApplicationDefinition: - """Gets the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :return: ApplicationDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - - _request = build_application_definitions_get_by_id_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_by_id_initial( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_application_definitions_delete_by_id_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_by_id( - self, resource_group_name: str, application_definition_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes the managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_by_id_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _create_or_update_by_id_initial( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ApplicationDefinition") - - _request = build_application_definitions_create_or_update_by_id_request( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update_by_id( - self, - resource_group_name: str, - application_definition_name: str, - parameters: _models.ApplicationDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update a managed application - definition. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update_by_id( - self, - resource_group_name: str, - application_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update a managed application - definition. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update_by_id( - self, - resource_group_name: str, - application_definition_name: str, - parameters: Union[_models.ApplicationDefinition, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ApplicationDefinition]: - """Creates a new managed application definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param application_definition_name: The name of the managed application definition. Required. - :type application_definition_name: str - :param parameters: Parameters supplied to the create or update a managed application - definition. Is either a ApplicationDefinition type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition or - IO[bytes] - :return: An instance of LROPoller that returns either ApplicationDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_by_id_initial( - resource_group_name=resource_group_name, - application_definition_name=application_definition_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ApplicationDefinition", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ApplicationDefinition].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ApplicationDefinition]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - -class JitRequestsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.managedapplications.ApplicationClient`'s - :attr:`jit_requests` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ApplicationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> _models.JitRequestDefinition: - """Gets the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) - - _request = build_jit_requests_get_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - jit_request_name: str, - parameters: Union[_models.JitRequestDefinition, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "JitRequestDefinition") - - _request = build_jit_requests_create_or_update_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: _models.JitRequestDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.JitRequestDefinition]: - """Creates or updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either JitRequestDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.JitRequestDefinition]: - """Creates or updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either JitRequestDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: Union[_models.JitRequestDefinition, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.JitRequestDefinition]: - """Creates or updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Is either a - JitRequestDefinition type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition or - IO[bytes] - :return: An instance of LROPoller that returns either JitRequestDefinition or the result of - cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.models.JitRequestDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.JitRequestDefinition].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.JitRequestDefinition]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @overload - def update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: _models.JitRequestPatchable, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.JitRequestDefinition: - """Updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.JitRequestDefinition: - """Updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - resource_group_name: str, - jit_request_name: str, - parameters: Union[_models.JitRequestPatchable, IO[bytes]], - **kwargs: Any - ) -> _models.JitRequestDefinition: - """Updates the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :param parameters: Parameters supplied to the update JIT request. Is either a - JitRequestPatchable type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.managedapplications.models.JitRequestPatchable or - IO[bytes] - :return: JitRequestDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "JitRequestPatchable") - - _request = build_jit_requests_update_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, jit_request_name: str, **kwargs: Any - ) -> None: - """Deletes the JIT request. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param jit_request_name: The name of the JIT request. Required. - :type jit_request_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_jit_requests_delete_request( - resource_group_name=resource_group_name, - jit_request_name=jit_request_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> _models.JitRequestDefinitionListResult: - """Retrieves all JIT requests within the subscription. - - :return: JitRequestDefinitionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) - - _request = build_jit_requests_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> _models.JitRequestDefinitionListResult: - """Retrieves all JIT requests within the resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: JitRequestDefinitionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.managedapplications.models.JitRequestDefinitionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) - - _request = build_jit_requests_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/managedapplications/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/__init__.py deleted file mode 100644 index 02f33f3e073a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._policy_client import PolicyClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "PolicyClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_configuration.py deleted file mode 100644 index fabedabfdb2e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_configuration.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class PolicyClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for PolicyClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_policy_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_policy_client.py deleted file mode 100644 index d5acd962a9af..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_policy_client.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import PolicyClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import ( - DataPolicyManifestsOperations, - PolicyAssignmentsOperations, - PolicyDefinitionVersionsOperations, - PolicyDefinitionsOperations, - PolicyExemptionsOperations, - PolicySetDefinitionVersionsOperations, - PolicySetDefinitionsOperations, - VariableValuesOperations, - VariablesOperations, -) - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class PolicyClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - """To manage and control access to your resources, you can define customized policies and assign - them at a scope. - - :ivar data_policy_manifests: DataPolicyManifestsOperations operations - :vartype data_policy_manifests: - azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations - :ivar policy_definitions: PolicyDefinitionsOperations operations - :vartype policy_definitions: azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations - :ivar policy_definition_versions: PolicyDefinitionVersionsOperations operations - :vartype policy_definition_versions: - azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations - :ivar policy_set_definitions: PolicySetDefinitionsOperations operations - :vartype policy_set_definitions: - azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations - :ivar policy_set_definition_versions: PolicySetDefinitionVersionsOperations operations - :vartype policy_set_definition_versions: - azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations - :ivar policy_assignments: PolicyAssignmentsOperations operations - :vartype policy_assignments: azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations - :ivar policy_exemptions: PolicyExemptionsOperations operations - :vartype policy_exemptions: azure.mgmt.resource.policy.operations.PolicyExemptionsOperations - :ivar variables: VariablesOperations operations - :vartype variables: azure.mgmt.resource.policy.operations.VariablesOperations - :ivar variable_values: VariableValuesOperations operations - :vartype variable_values: azure.mgmt.resource.policy.operations.VariableValuesOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = PolicyClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.data_policy_manifests = DataPolicyManifestsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_definitions = PolicyDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_definition_versions = PolicyDefinitionVersionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_set_definitions = PolicySetDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_set_definition_versions = PolicySetDefinitionVersionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_assignments = PolicyAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_exemptions = PolicyExemptionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.variables = VariablesOperations(self._client, self._config, self._serialize, self._deserialize) - self.variable_values = VariableValuesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/__init__.py deleted file mode 100644 index 18537e83bff7..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._policy_client import PolicyClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "PolicyClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_configuration.py deleted file mode 100644 index e2bf84bb231a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_configuration.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class PolicyClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for PolicyClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_policy_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_policy_client.py deleted file mode 100644 index e0c9001989a0..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/_policy_client.py +++ /dev/null @@ -1,184 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import PolicyClientConfiguration -from .operations import ( - DataPolicyManifestsOperations, - PolicyAssignmentsOperations, - PolicyDefinitionVersionsOperations, - PolicyDefinitionsOperations, - PolicyExemptionsOperations, - PolicySetDefinitionVersionsOperations, - PolicySetDefinitionsOperations, - VariableValuesOperations, - VariablesOperations, -) - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class PolicyClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - """To manage and control access to your resources, you can define customized policies and assign - them at a scope. - - :ivar data_policy_manifests: DataPolicyManifestsOperations operations - :vartype data_policy_manifests: - azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations - :ivar policy_definitions: PolicyDefinitionsOperations operations - :vartype policy_definitions: - azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations - :ivar policy_definition_versions: PolicyDefinitionVersionsOperations operations - :vartype policy_definition_versions: - azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations - :ivar policy_set_definitions: PolicySetDefinitionsOperations operations - :vartype policy_set_definitions: - azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations - :ivar policy_set_definition_versions: PolicySetDefinitionVersionsOperations operations - :vartype policy_set_definition_versions: - azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations - :ivar policy_assignments: PolicyAssignmentsOperations operations - :vartype policy_assignments: - azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations - :ivar policy_exemptions: PolicyExemptionsOperations operations - :vartype policy_exemptions: - azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations - :ivar variables: VariablesOperations operations - :vartype variables: azure.mgmt.resource.policy.aio.operations.VariablesOperations - :ivar variable_values: VariableValuesOperations operations - :vartype variable_values: azure.mgmt.resource.policy.aio.operations.VariableValuesOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = PolicyClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.data_policy_manifests = DataPolicyManifestsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_definitions = PolicyDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_definition_versions = PolicyDefinitionVersionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_set_definitions = PolicySetDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_set_definition_versions = PolicySetDefinitionVersionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_assignments = PolicyAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.policy_exemptions = PolicyExemptionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.variables = VariablesOperations(self._client, self._config, self._serialize, self._deserialize) - self.variable_values = VariableValuesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/__init__.py deleted file mode 100644 index f302859689f6..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import DataPolicyManifestsOperations # type: ignore -from ._operations import PolicyDefinitionsOperations # type: ignore -from ._operations import PolicyDefinitionVersionsOperations # type: ignore -from ._operations import PolicySetDefinitionsOperations # type: ignore -from ._operations import PolicySetDefinitionVersionsOperations # type: ignore -from ._operations import PolicyAssignmentsOperations # type: ignore -from ._operations import PolicyExemptionsOperations # type: ignore -from ._operations import VariablesOperations # type: ignore -from ._operations import VariableValuesOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataPolicyManifestsOperations", - "PolicyDefinitionsOperations", - "PolicyDefinitionVersionsOperations", - "PolicySetDefinitionsOperations", - "PolicySetDefinitionVersionsOperations", - "PolicyAssignmentsOperations", - "PolicyExemptionsOperations", - "VariablesOperations", - "VariableValuesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_operations.py deleted file mode 100644 index b166b31b9016..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_operations.py +++ /dev/null @@ -1,7433 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import ( - build_data_policy_manifests_get_by_policy_mode_request, - build_data_policy_manifests_list_request, - build_policy_assignments_create_by_id_request, - build_policy_assignments_create_request, - build_policy_assignments_delete_by_id_request, - build_policy_assignments_delete_request, - build_policy_assignments_get_by_id_request, - build_policy_assignments_get_request, - build_policy_assignments_list_for_management_group_request, - build_policy_assignments_list_for_resource_group_request, - build_policy_assignments_list_for_resource_request, - build_policy_assignments_list_request, - build_policy_assignments_update_by_id_request, - build_policy_assignments_update_request, - build_policy_definition_versions_create_or_update_at_management_group_request, - build_policy_definition_versions_create_or_update_request, - build_policy_definition_versions_delete_at_management_group_request, - build_policy_definition_versions_delete_request, - build_policy_definition_versions_get_at_management_group_request, - build_policy_definition_versions_get_built_in_request, - build_policy_definition_versions_get_request, - build_policy_definition_versions_list_all_at_management_group_request, - build_policy_definition_versions_list_all_builtins_request, - build_policy_definition_versions_list_all_request, - build_policy_definition_versions_list_built_in_request, - build_policy_definition_versions_list_by_management_group_request, - build_policy_definition_versions_list_request, - build_policy_definitions_create_or_update_at_management_group_request, - build_policy_definitions_create_or_update_request, - build_policy_definitions_delete_at_management_group_request, - build_policy_definitions_delete_request, - build_policy_definitions_get_at_management_group_request, - build_policy_definitions_get_built_in_request, - build_policy_definitions_get_request, - build_policy_definitions_list_built_in_request, - build_policy_definitions_list_by_management_group_request, - build_policy_definitions_list_request, - build_policy_exemptions_create_or_update_request, - build_policy_exemptions_delete_request, - build_policy_exemptions_get_request, - build_policy_exemptions_list_for_management_group_request, - build_policy_exemptions_list_for_resource_group_request, - build_policy_exemptions_list_for_resource_request, - build_policy_exemptions_list_request, - build_policy_exemptions_update_request, - build_policy_set_definition_versions_create_or_update_at_management_group_request, - build_policy_set_definition_versions_create_or_update_request, - build_policy_set_definition_versions_delete_at_management_group_request, - build_policy_set_definition_versions_delete_request, - build_policy_set_definition_versions_get_at_management_group_request, - build_policy_set_definition_versions_get_built_in_request, - build_policy_set_definition_versions_get_request, - build_policy_set_definition_versions_list_all_at_management_group_request, - build_policy_set_definition_versions_list_all_builtins_request, - build_policy_set_definition_versions_list_all_request, - build_policy_set_definition_versions_list_built_in_request, - build_policy_set_definition_versions_list_by_management_group_request, - build_policy_set_definition_versions_list_request, - build_policy_set_definitions_create_or_update_at_management_group_request, - build_policy_set_definitions_create_or_update_request, - build_policy_set_definitions_delete_at_management_group_request, - build_policy_set_definitions_delete_request, - build_policy_set_definitions_get_at_management_group_request, - build_policy_set_definitions_get_built_in_request, - build_policy_set_definitions_get_request, - build_policy_set_definitions_list_built_in_request, - build_policy_set_definitions_list_by_management_group_request, - build_policy_set_definitions_list_request, - build_variable_values_create_or_update_at_management_group_request, - build_variable_values_create_or_update_request, - build_variable_values_delete_at_management_group_request, - build_variable_values_delete_request, - build_variable_values_get_at_management_group_request, - build_variable_values_get_request, - build_variable_values_list_for_management_group_request, - build_variable_values_list_request, - build_variables_create_or_update_at_management_group_request, - build_variables_create_or_update_request, - build_variables_delete_at_management_group_request, - build_variables_delete_request, - build_variables_get_at_management_group_request, - build_variables_get_request, - build_variables_list_for_management_group_request, - build_variables_list_request, -) -from .._configuration import PolicyClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class DataPolicyManifestsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`data_policy_manifests` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get_by_policy_mode(self, policy_mode: str, **kwargs: Any) -> _models.DataPolicyManifest: - """Retrieves a data policy manifest. - - This operation retrieves the data policy manifest with the given policy mode. - - :param policy_mode: The policy mode of the data policy manifest to get. Required. - :type policy_mode: str - :return: DataPolicyManifest or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.DataPolicyManifest - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) - cls: ClsType[_models.DataPolicyManifest] = kwargs.pop("cls", None) - - _request = build_data_policy_manifests_get_by_policy_mode_request( - policy_mode=policy_mode, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataPolicyManifest", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.DataPolicyManifest"]: - """Retrieves data policy manifests. - - This operation retrieves a list of all the data policy manifests that match the optional given - $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not - provided, the unfiltered list includes all data policy manifests for data resource types. If - $filter=namespace is provided, the returned list only includes all data policy manifests that - have a namespace matching the provided value. - - :param filter: The filter to apply on the operation. Valid values for $filter are: "namespace - eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq - '{value}' is provided, the returned list only includes all data policy manifests that have a - namespace matching the provided value. Default value is None. - :type filter: str - :return: An iterator like instance of either DataPolicyManifest or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.DataPolicyManifest] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) - cls: ClsType[_models.DataPolicyManifestListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_data_policy_manifests_list_request( - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("DataPolicyManifestListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class PolicyDefinitionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`policy_definitions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - policy_definition_name: str, - parameters: _models.PolicyDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - policy_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO[bytes]], **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Is either a PolicyDefinition type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinition") - - _request = build_policy_definitions_create_or_update_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, policy_definition_name: str, **kwargs: Any) -> None: - """Deletes a policy definition in a subscription. - - This operation deletes the policy definition in the given subscription with the given name. - - :param policy_definition_name: The name of the policy definition to delete. Required. - :type policy_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definitions_delete_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: - """Retrieves a policy definition in a subscription. - - This operation retrieves the policy definition in the given subscription with the given name. - - :param policy_definition_name: The name of the policy definition to get. Required. - :type policy_definition_name: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - _request = build_policy_definitions_get_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: - """Retrieves a built-in policy definition. - - This operation retrieves the built-in policy definition with the given name. - - :param policy_definition_name: The name of the built-in policy definition to get. Required. - :type policy_definition_name: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - _request = build_policy_definitions_get_built_in_request( - policy_definition_name=policy_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - policy_definition_name: str, - parameters: _models.PolicyDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a management group. - - This operation creates or updates a policy definition in the given management group with the - given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - policy_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a management group. - - This operation creates or updates a policy definition in the given management group with the - given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_management_group( - self, - management_group_id: str, - policy_definition_name: str, - parameters: Union[_models.PolicyDefinition, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a management group. - - This operation creates or updates a policy definition in the given management group with the - given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Is either a PolicyDefinition type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinition") - - _request = build_policy_definitions_create_or_update_at_management_group_request( - management_group_id=management_group_id, - policy_definition_name=policy_definition_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_management_group( - self, management_group_id: str, policy_definition_name: str, **kwargs: Any - ) -> None: - """Deletes a policy definition in a management group. - - This operation deletes the policy definition in the given management group with the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to delete. Required. - :type policy_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definitions_delete_at_management_group_request( - management_group_id=management_group_id, - policy_definition_name=policy_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_management_group( - self, management_group_id: str, policy_definition_name: str, **kwargs: Any - ) -> _models.PolicyDefinition: - """Retrieve a policy definition in a management group. - - This operation retrieves the policy definition in the given management group with the given - name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to get. Required. - :type policy_definition_name: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - _request = build_policy_definitions_get_at_management_group_request( - management_group_id=management_group_id, - policy_definition_name=policy_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyDefinition"]: - """Retrieves policy definitions in a subscription. - - This operation retrieves a list of all the policy definitions in a given subscription that - match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType - -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list - includes all policy definitions associated with the subscription, including those that apply - directly or from management groups that contain the given subscription. If - $filter=atExactScope() is provided, the returned list only includes all policy definitions that - at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list - only includes all policy definitions whose type match the {value}. Possible policyType values - are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, - the returned list only includes all policy definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy definitions whose type match - the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy - definitions whose category match the {value}. Default value is None. - :type filter: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinition or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definitions_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyDefinition"]: - """Retrieve built-in policy definitions. - - This operation retrieves a list of all the built-in policy definitions that match the optional - given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes - all built-in policy definitions whose type match the {value}. Possible policyType values are - NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the - returned list only includes all built-in policy definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy definitions whose type match - the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy - definitions whose category match the {value}. Default value is None. - :type filter: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinition or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definitions_list_built_in_request( - filter=filter, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_management_group( - self, management_group_id: str, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyDefinition"]: - """Retrieve policy definitions in a management group. - - This operation retrieves a list of all the policy definitions in a given management group that - match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType - -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list - includes all policy definitions associated with the management group, including those that - apply directly or from management groups that contain the given management group. If - $filter=atExactScope() is provided, the returned list only includes all policy definitions that - at the given management group. If $filter='policyType -eq {value}' is provided, the returned - list only includes all policy definitions whose type match the {value}. Possible policyType - values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is - provided, the returned list only includes all policy definitions whose category match the - {value}. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy definitions whose type match - the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy - definitions whose category match the {value}. Default value is None. - :type filter: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinition or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definitions_list_by_management_group_request( - management_group_id=management_group_id, - filter=filter, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class PolicyDefinitionVersionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`policy_definition_versions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def list_all_builtins(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: - """Lists all built-in policy definition versions. - - This operation lists all the built-in policy definition versions for all built-in policy - definitions. - - :return: PolicyDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_list_all_builtins_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_all_at_management_group( - self, management_group_name: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersionListResult: - """Lists all policy definition versions at management group scope. - - This operation lists all the policy definition versions for all policy definitions at the - management group scope. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :return: PolicyDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_list_all_at_management_group_request( - management_group_name=management_group_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_all(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: - """Lists all policy definition versions within a subscription. - - This operation lists all the policy definition versions for all policy definitions within a - subscription. - - :return: PolicyDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_list_all_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - policy_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicyDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - policy_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - policy_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinitionVersion") - - _request = build_policy_definition_versions_create_or_update_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any) -> None: - """Deletes a policy definition version in a subscription. - - This operation deletes the policy definition version in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_delete_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Retrieves a policy definition version in a subscription. - - This operation retrieves the policy definition version in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_get_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_built_in( - self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Retrieves a built-in policy definition version. - - This operation retrieves the built-in policy definition version with the given name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_get_built_in_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update_at_management_group( - self, - management_group_name: str, - policy_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicyDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition version in a management group. - - This operation creates or updates a policy definition version in the given management group - with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_management_group( - self, - management_group_name: str, - policy_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition version in a management group. - - This operation creates or updates a policy definition version in the given management group - with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_management_group( - self, - management_group_name: str, - policy_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition version in a management group. - - This operation creates or updates a policy definition version in the given management group - with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinitionVersion") - - _request = build_policy_definition_versions_create_or_update_at_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_management_group( - self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> None: - """Deletes a policy definition in a management group. - - This operation deletes the policy definition in the given management group with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_delete_at_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_management_group( - self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Retrieve a policy definition version in a management group. - - This operation retrieves the policy definition version in the given management group with the - given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_get_at_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: - """Retrieves policy definition versions for a given policy definition in a subscription. - - This operation retrieves a list of all the policy definition versions for the given policy - definition. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definition_versions_list_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: - """Retrieve built-in policy definition versions. - - This operation retrieves a list of all the built-in policy definition versions for the given - policy definition. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definition_versions_list_built_in_request( - policy_definition_name=policy_definition_name, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_management_group( - self, management_group_name: str, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: - """Retrieve policy definition versions in a management group policy definition. - - This operation retrieves a list of all the policy definition versions for the given policy - definition in the given management group. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definition_versions_list_by_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class PolicySetDefinitionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`policy_set_definitions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - policy_set_definition_name: str, - parameters: _models.PolicySetDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given subscription with the - given name. - - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - policy_set_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given subscription with the - given name. - - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO[bytes]], **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given subscription with the - given name. - - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Is either a PolicySetDefinition type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinition") - - _request = build_policy_set_definitions_create_or_update_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, policy_set_definition_name: str, **kwargs: Any) -> None: - """Deletes a policy set definition. - - This operation deletes the policy set definition in the given subscription with the given name. - - :param policy_set_definition_name: The name of the policy set definition to delete. Required. - :type policy_set_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_delete_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicySetDefinition: - """Retrieves a policy set definition. - - This operation retrieves the policy set definition in the given subscription with the given - name. - - :param policy_set_definition_name: The name of the policy set definition to get. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_get_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_built_in( - self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicySetDefinition: - """Retrieves a built in policy set definition. - - This operation retrieves the built-in policy set definition with the given name. - - :param policy_set_definition_name: The name of the policy set definition to get. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_get_built_in_request( - policy_set_definition_name=policy_set_definition_name, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicySetDefinition"]: - """Retrieves the policy set definitions for a subscription. - - This operation retrieves a list of all the policy set definitions in a given subscription that - match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType - -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list - includes all policy set definitions associated with the subscription, including those that - apply directly or from management groups that contain the given subscription. If - $filter=atExactScope() is provided, the returned list only includes all policy set definitions - that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned - list only includes all policy set definitions whose type match the {value}. Possible policyType - values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the - returned list only includes all policy set definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy set definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy set definitions whose type - match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy set - definitions whose category match the {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definitions_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicySetDefinition"]: - """Retrieves built-in policy set definitions. - - This operation retrieves a list of all the built-in policy set definitions that match the - optional given $filter. If $filter='category -eq {value}' is provided, the returned list only - includes all built-in policy set definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy set definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy set definitions whose type - match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy set - definitions whose category match the {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definitions_list_built_in_request( - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - policy_set_definition_name: str, - parameters: _models.PolicySetDefinition, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given management group with - the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - policy_set_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given management group with - the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_management_group( - self, - management_group_id: str, - policy_set_definition_name: str, - parameters: Union[_models.PolicySetDefinition, IO[bytes]], - **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given management group with - the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Is either a PolicySetDefinition type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinition") - - _request = build_policy_set_definitions_create_or_update_at_management_group_request( - management_group_id=management_group_id, - policy_set_definition_name=policy_set_definition_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_management_group( - self, management_group_id: str, policy_set_definition_name: str, **kwargs: Any - ) -> None: - """Deletes a policy set definition. - - This operation deletes the policy set definition in the given management group with the given - name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to delete. Required. - :type policy_set_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_delete_at_management_group_request( - management_group_id=management_group_id, - policy_set_definition_name=policy_set_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_management_group( - self, management_group_id: str, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicySetDefinition: - """Retrieves a policy set definition. - - This operation retrieves the policy set definition in the given management group with the given - name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to get. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_get_at_management_group_request( - management_group_id=management_group_id, - policy_set_definition_name=policy_set_definition_name, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_management_group( - self, - management_group_id: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.PolicySetDefinition"]: - """Retrieves all policy set definitions in management group. - - This operation retrieves a list of all the policy set definitions in a given management group - that match the optional given $filter. Valid values for $filter are: 'atExactScope()', - 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered - list includes all policy set definitions associated with the management group, including those - that apply directly or from management groups that contain the given management group. If - $filter=atExactScope() is provided, the returned list only includes all policy set definitions - that at the given management group. If $filter='policyType -eq {value}' is provided, the - returned list only includes all policy set definitions whose type match the {value}. Possible - policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is - provided, the returned list only includes all policy set definitions whose category match the - {value}. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy set definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy set definitions whose type - match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy set - definitions whose category match the {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definitions_list_by_management_group_request( - management_group_id=management_group_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class PolicySetDefinitionVersionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`policy_set_definition_versions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def list_all_builtins(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: - """Lists all built-in policy set definition versions. - - This operation lists all the built-in policy set definition versions for all built-in policy - set definitions. - - :return: PolicySetDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_list_all_builtins_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_all_at_management_group( - self, management_group_name: str, **kwargs: Any - ) -> _models.PolicySetDefinitionVersionListResult: - """Lists all policy set definition versions at management group scope. - - This operation lists all the policy set definition versions for all policy set definitions at - the management group scope. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :return: PolicySetDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_list_all_at_management_group_request( - management_group_name=management_group_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_all(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: - """Lists all policy set definition versions within a subscription. - - This operation lists all the policy set definition versions for all policy set definitions - within a subscription. - - :return: PolicySetDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_list_all_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicySetDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given subscription - with the given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given subscription - with the given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given subscription - with the given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition properties. Is either a PolicySetDefinitionVersion - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") - - _request = build_policy_set_definition_versions_create_or_update_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any) -> None: - """Deletes a policy set definition version. - - This operation deletes the policy set definition version in the given subscription with the - given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_delete_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, - policy_set_definition_name: str, - policy_definition_version: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Retrieves a policy set definition version. - - This operation retrieves the policy set definition version in the given subscription with the - given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_get_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_built_in( - self, - policy_set_definition_name: str, - policy_definition_version: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Retrieves a built in policy set definition version. - - This operation retrieves the built-in policy set definition version with the given name and - version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_get_built_in_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: - """Retrieves the policy set definition versions for a given policy set definition in a - subscription. - - This operation retrieves a list of all the policy set definition versions for the given policy - set definition. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definition_versions_list_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: - """Retrieves built-in policy set definition versions. - - This operation retrieves a list of all the built-in policy set definition versions for the - given built-in policy set definition. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definition_versions_list_built_in_request( - policy_set_definition_name=policy_set_definition_name, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create_or_update_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicySetDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given management group - with the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition version properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given management group - with the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition version properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given management group - with the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition version properties. Is either a - PolicySetDefinitionVersion type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") - - _request = build_policy_set_definition_versions_create_or_update_at_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_management_group( - self, management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> None: - """Deletes a policy set definition version. - - This operation deletes the policy set definition version in the given management group with the - given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_delete_at_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> _models.PolicySetDefinitionVersion: - """Retrieves a policy set definition version. - - This operation retrieves the policy set definition version in the given management group with - the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_get_at_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: - """Retrieves all policy set definition versions for a given policy set definition in a management - group. - - This operation retrieves a list of all the policy set definition versions for the given policy - set definition in a given management group. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definition_versions_list_by_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class PolicyAssignmentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`policy_assignments` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def delete( - self, scope: str, policy_assignment_name: str, **kwargs: Any - ) -> Optional[_models.PolicyAssignment]: - """Deletes a policy assignment. - - This operation deletes a policy assignment, given its name and the scope it was created in. The - scope of a policy assignment is the part of its ID preceding - '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment to delete. Required. - :type policy_assignment_name: str - :return: PolicyAssignment or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) - - _request = build_policy_assignments_delete_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - scope: str, - policy_assignment_name: str, - parameters: _models.PolicyAssignment, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates a policy assignment with the given scope and name. Policy - assignments apply to all resources contained within their scope. For example, when you assign a - policy at resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for the policy assignment. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - scope: str, - policy_assignment_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates a policy assignment with the given scope and name. Policy - assignments apply to all resources contained within their scope. For example, when you assign a - policy at resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for the policy assignment. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - scope: str, - policy_assignment_name: str, - parameters: Union[_models.PolicyAssignment, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates a policy assignment with the given scope and name. Policy - assignments apply to all resources contained within their scope. For example, when you assign a - policy at resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignment") - - _request = build_policy_assignments_create_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get( - self, scope: str, policy_assignment_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicyAssignment: - """Retrieves a policy assignment. - - This operation retrieves a single policy assignment, given its name and the scope it was - created at. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment to get. Required. - :type policy_assignment_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - _request = build_policy_assignments_get_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def update( - self, - scope: str, - policy_assignment_name: str, - parameters: _models.PolicyAssignmentUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates a policy assignment with the given scope and name. Policy assignments - apply to all resources contained within their scope. For example, when you assign a policy at - resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - scope: str, - policy_assignment_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates a policy assignment with the given scope and name. Policy assignments - apply to all resources contained within their scope. For example, when you assign a policy at - resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - scope: str, - policy_assignment_name: str, - parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates a policy assignment with the given scope and name. Policy assignments - apply to all resources contained within their scope. For example, when you assign a policy at - resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for policy assignment patch request. Is either a - PolicyAssignmentUpdate type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") - - _request = build_policy_assignments_update_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a resource group. - - This operation retrieves the list of all policy assignments associated with the given resource - group in the given subscription that match the optional given $filter. Valid values for $filter - are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not - provided, the unfiltered list includes all policy assignments associated with the resource - group, including those that apply directly or apply from containing scopes, as well as any - applied to resources contained within the resource group. If $filter=atScope() is provided, the - returned list includes all policy assignments that apply to the resource group, which is - everything in the unfiltered list except those applied to resources contained within the - resource group. If $filter=atExactScope() is provided, the returned list only includes all - policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is - provided, the returned list includes all policy assignments of the policy definition whose id - is {value} that apply to the resource group. - - :param resource_group_name: The name of the resource group that contains policy assignments. - Required. - :type resource_group_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_for_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_resource( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a resource. - - This operation retrieves the list of all policy assignments associated with the specified - resource in the given resource group and subscription that match the optional given $filter. - Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq - '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments - associated with the resource, including those that apply directly or from all containing - scopes, as well as any applied to resources contained within the resource. If $filter=atScope() - is provided, the returned list includes all policy assignments that apply to the resource, - which is everything in the unfiltered list except those applied to resources contained within - the resource. If $filter=atExactScope() is provided, the returned list only includes all policy - assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, - the returned list includes all policy assignments of the policy definition whose id is {value} - that apply to the resource. Three parameters plus the resource name are used to identify a - specific resource. If the resource is not part of a parent resource (the more common case), the - parent resource path should not be provided (or provided as ''). For example a web app could be - specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', - {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent - resource, then all parameters should be provided. For example a virtual machine DNS name could - be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == - 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == - 'MyComputerName'). A convenient alternative to providing the namespace and type name separately - is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', - {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == - 'MyWebApp'). - - :param resource_group_name: The name of the resource group containing the resource. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. For example, the - namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource path. Use empty string if there is none. - Required. - :type parent_resource_path: str - :param resource_type: The resource type name. For example the type name of a web app is 'sites' - (from Microsoft.Web/sites). Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_for_resource_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group( - self, - management_group_id: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a management group. - - This operation retrieves the list of all policy assignments applicable to the management group - that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or - 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes - all policy assignments that are assigned to the management group or the management group's - ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy - assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is - provided, the returned list includes all policy assignments of the policy definition whose id - is {value} that apply to the management group. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_for_management_group_request( - management_group_id=management_group_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list( - self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a subscription. - - This operation retrieves the list of all policy assignments associated with the given - subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the - unfiltered list includes all policy assignments associated with the subscription, including - those that apply directly or from management groups that contain the given subscription, as - well as any applied to objects contained within the subscription. If $filter=atScope() is - provided, the returned list includes all policy assignments that apply to the subscription, - which is everything in the unfiltered list except those applied to objects contained within the - subscription. If $filter=atExactScope() is provided, the returned list only includes all policy - assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, - the returned list includes all policy assignments of the policy definition whose id is {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: - """Deletes a policy assignment. - - This operation deletes the policy with the given ID. Policy assignment IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - formats for {scope} are: '/providers/Microsoft.Management/managementGroups/{managementGroup}' - (management group), '/subscriptions/{subscriptionId}' (subscription), - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' (resource group), or - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}' - (resource). - - :param policy_assignment_id: The ID of the policy assignment to delete. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :return: PolicyAssignment or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) - - _request = build_policy_assignments_delete_by_id_request( - policy_assignment_id=policy_assignment_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_by_id( - self, - policy_assignment_id: str, - parameters: _models.PolicyAssignment, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates the policy assignment with the given ID. Policy assignments - made on a scope apply to all resources contained in that scope. For example, when you assign a - policy to a resource group that policy applies to all resources in the group. Policy assignment - IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to create. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_by_id( - self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates the policy assignment with the given ID. Policy assignments - made on a scope apply to all resources contained in that scope. For example, when you assign a - policy to a resource group that policy applies to all resources in the group. Policy assignment - IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to create. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_by_id( - self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO[bytes]], **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates the policy assignment with the given ID. Policy assignments - made on a scope apply to all resources contained in that scope. For example, when you assign a - policy to a resource group that policy applies to all resources in the group. Policy assignment - IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to create. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignment") - - _request = build_policy_assignments_create_by_id_request( - policy_assignment_id=policy_assignment_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_by_id( - self, policy_assignment_id: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicyAssignment: - """Retrieves the policy assignment with the given ID. - - The operation retrieves the policy assignment with the given ID. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to get. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - _request = build_policy_assignments_get_by_id_request( - policy_assignment_id=policy_assignment_id, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def update_by_id( - self, - policy_assignment_id: str, - parameters: _models.PolicyAssignmentUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates the policy assignment with the given ID. Policy assignments made on a - scope apply to all resources contained in that scope. For example, when you assign a policy to - a resource group that policy applies to all resources in the group. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to update. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_by_id( - self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates the policy assignment with the given ID. Policy assignments made on a - scope apply to all resources contained in that scope. For example, when you assign a policy to - a resource group that policy applies to all resources in the group. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to update. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update_by_id( - self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates the policy assignment with the given ID. Policy assignments made on a - scope apply to all resources contained in that scope. For example, when you assign a policy to - a resource group that policy applies to all resources in the group. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to update. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment patch request. Is either a - PolicyAssignmentUpdate type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") - - _request = build_policy_assignments_update_by_id_request( - policy_assignment_id=policy_assignment_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class PolicyExemptionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`policy_exemptions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def delete(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> None: - """Deletes a policy exemption. - - This operation deletes a policy exemption, given its name and the scope it was created in. The - scope of a policy exemption is the part of its ID preceding - '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_exemptions_delete_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update( - self, - scope: str, - policy_exemption_name: str, - parameters: _models.PolicyExemption, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyExemption: - """Creates or updates a policy exemption. - - This operation creates or updates a policy exemption with the given scope and name. Policy - exemptions apply to all resources contained within their scope. For example, when you create a - policy exemption at resource group scope for a policy assignment at the same or above level, - the exemption exempts to all applicable resources in the resource group. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for the policy exemption. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - scope: str, - policy_exemption_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyExemption: - """Creates or updates a policy exemption. - - This operation creates or updates a policy exemption with the given scope and name. Policy - exemptions apply to all resources contained within their scope. For example, when you create a - policy exemption at resource group scope for a policy assignment at the same or above level, - the exemption exempts to all applicable resources in the resource group. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for the policy exemption. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - scope: str, - policy_exemption_name: str, - parameters: Union[_models.PolicyExemption, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyExemption: - """Creates or updates a policy exemption. - - This operation creates or updates a policy exemption with the given scope and name. Policy - exemptions apply to all resources contained within their scope. For example, when you create a - policy exemption at resource group scope for a policy assignment at the same or above level, - the exemption exempts to all applicable resources in the resource group. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for the policy exemption. Is either a PolicyExemption type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption or IO[bytes] - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyExemption") - - _request = build_policy_exemptions_create_or_update_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> _models.PolicyExemption: - """Retrieves a policy exemption. - - This operation retrieves a single policy exemption, given its name and the scope it was created - at. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) - - _request = build_policy_exemptions_get_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def update( - self, - scope: str, - policy_exemption_name: str, - parameters: _models.PolicyExemptionUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyExemption: - """Updates a policy exemption. - - This operation updates a policy exemption with the given scope and name. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for policy exemption patch request. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - scope: str, - policy_exemption_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PolicyExemption: - """Updates a policy exemption. - - This operation updates a policy exemption with the given scope and name. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for policy exemption patch request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - scope: str, - policy_exemption_name: str, - parameters: Union[_models.PolicyExemptionUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.PolicyExemption: - """Updates a policy exemption. - - This operation updates a policy exemption with the given scope and name. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for policy exemption patch request. Is either a - PolicyExemptionUpdate type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate or IO[bytes] - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyExemptionUpdate") - - _request = build_policy_exemptions_update_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a subscription. - - This operation retrieves the list of all policy exemptions associated with the given - subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, the unfiltered list includes all policy exemptions associated with the subscription, - including those that apply directly or from management groups that contain the given - subscription, as well as any applied to objects contained within the subscription. - - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_resource_group( - self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a resource group. - - This operation retrieves the list of all policy exemptions associated with the given resource - group in the given subscription that match the optional given $filter. Valid values for $filter - are: 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If - $filter is not provided, the unfiltered list includes all policy exemptions associated with the - resource group, including those that apply directly or apply from containing scopes, as well as - any applied to resources contained within the resource group. - - :param resource_group_name: The name of the resource group containing the resource. Required. - :type resource_group_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_for_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_resource( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a resource. - - This operation retrieves the list of all policy exemptions associated with the specified - resource in the given resource group and subscription that match the optional given $filter. - Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or - 'policyAssignmentId eq '{value}''. If $filter is not provided, the unfiltered list includes all - policy exemptions associated with the resource, including those that apply directly or from all - containing scopes, as well as any applied to resources contained within the resource. Three - parameters plus the resource name are used to identify a specific resource. If the resource is - not part of a parent resource (the more common case), the parent resource path should not be - provided (or provided as ''). For example a web app could be specified as - ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == - 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all - parameters should be provided. For example a virtual machine DNS name could be specified as - ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == - 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == - 'MyComputerName'). A convenient alternative to providing the namespace and type name separately - is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', - {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == - 'MyWebApp'). - - :param resource_group_name: The name of the resource group containing the resource. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. For example, the - namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource path. Use empty string if there is none. - Required. - :type parent_resource_path: str - :param resource_type: The resource type name. For example the type name of a web app is 'sites' - (from Microsoft.Web/sites). Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_for_resource_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group( - self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a management group. - - This operation retrieves the list of all policy exemptions applicable to the management group - that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', - 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter=atScope() is provided, the - returned list includes all policy exemptions that are assigned to the management group or the - management group's ancestors. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_for_management_group_request( - management_group_id=management_group_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class VariablesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`variables` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def delete(self, variable_name: str, **kwargs: Any) -> None: - """Deletes a variable. - - This operation deletes a variable, given its name and the subscription it was created in. The - scope of a variable is the part of its ID preceding - '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variables_delete_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update( - self, variable_name: str, parameters: _models.Variable, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given subscription and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, variable_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given subscription and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, variable_name: str, parameters: Union[_models.Variable, IO[bytes]], **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given subscription and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Variable") - - _request = build_variables_create_or_update_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, variable_name: str, **kwargs: Any) -> _models.Variable: - """Retrieves a variable. - - This operation retrieves a single variable, given its name and the subscription it was created - at. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - _request = build_variables_get_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_at_management_group(self, management_group_id: str, variable_name: str, **kwargs: Any) -> None: - """Deletes a variable. - - This operation deletes a variable, given its name and the management group it was created in. - The scope of a variable is the part of its ID preceding - '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variables_delete_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - parameters: _models.Variable, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given management group and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given management group and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - parameters: Union[_models.Variable, IO[bytes]], - **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given management group and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Variable") - - _request = build_variables_create_or_update_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_at_management_group( - self, management_group_id: str, variable_name: str, **kwargs: Any - ) -> _models.Variable: - """Retrieves a variable. - - This operation retrieves a single variable, given its name and the management group it was - created at. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - _request = build_variables_get_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Variable"]: - """Retrieves all variables that are at this subscription level. - - This operation retrieves the list of all variables associated with the given subscription. - - :return: An iterator like instance of either Variable or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.Variable] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variables_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("VariableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group(self, management_group_id: str, **kwargs: Any) -> AsyncItemPaged["_models.Variable"]: - """Retrieves all variables that are at this management group level. - - This operation retrieves the list of all variables applicable to the management group. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :return: An iterator like instance of either Variable or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.Variable] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variables_list_for_management_group_request( - management_group_id=management_group_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("VariableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class VariableValuesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s - :attr:`variable_values` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def delete(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> None: - """Deletes a variable value. - - This operation deletes a variable value, given its name, the subscription it was created in, - and the variable it belongs to. The scope of a variable value is the part of its ID preceding - '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variable_values_delete_request( - variable_name=variable_name, - variable_value_name=variable_value_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update( - self, - variable_name: str, - variable_value_name: str, - parameters: _models.VariableValue, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given subscription and name for a - given variable. Variable values are scoped to the variable for which they are created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - variable_name: str, - variable_value_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given subscription and name for a - given variable. Variable values are scoped to the variable for which they are created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - variable_name: str, - variable_value_name: str, - parameters: Union[_models.VariableValue, IO[bytes]], - **kwargs: Any - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given subscription and name for a - given variable. Variable values are scoped to the variable for which they are created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Is either a VariableValue type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "VariableValue") - - _request = build_variable_values_create_or_update_request( - variable_name=variable_name, - variable_value_name=variable_value_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> _models.VariableValue: - """Retrieves a variable value. - - This operation retrieves a single variable value; given its name, subscription it was created - at and the variable it's created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - _request = build_variable_values_get_request( - variable_name=variable_name, - variable_value_name=variable_value_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, variable_name: str, **kwargs: Any) -> AsyncItemPaged["_models.VariableValue"]: - """List variable values for a variable. - - This operation retrieves the list of all variable values associated with the given variable - that is at a subscription level. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: An iterator like instance of either VariableValue or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.VariableValue] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variable_values_list_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("VariableValueListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group( - self, management_group_id: str, variable_name: str, **kwargs: Any - ) -> AsyncItemPaged["_models.VariableValue"]: - """List variable values at management group level. - - This operation retrieves the list of all variable values applicable the variable indicated at - the management group scope. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: An iterator like instance of either VariableValue or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.VariableValue] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variable_values_list_for_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("VariableValueListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def delete_at_management_group( - self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any - ) -> None: - """Deletes a variable value. - - This operation deletes a variable value, given its name, the management group it was created - in, and the variable it belongs to. The scope of a variable value is the part of its ID - preceding '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variable_values_delete_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - variable_value_name=variable_value_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - variable_value_name: str, - parameters: _models.VariableValue, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given management group and name for - a given variable. Variable values are scoped to the variable for which they are created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - variable_value_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given management group and name for - a given variable. Variable values are scoped to the variable for which they are created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - variable_value_name: str, - parameters: Union[_models.VariableValue, IO[bytes]], - **kwargs: Any - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given management group and name for - a given variable. Variable values are scoped to the variable for which they are created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Is either a VariableValue type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "VariableValue") - - _request = build_variable_values_create_or_update_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - variable_value_name=variable_value_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_at_management_group( - self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any - ) -> _models.VariableValue: - """Retrieves a variable value. - - This operation retrieves a single variable value; given its name, management group it was - created at and the variable it's created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - _request = build_variable_values_get_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - variable_value_name=variable_value_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/__init__.py deleted file mode 100644 index 28b5db51f4e5..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/__init__.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - Alias, - AliasPath, - AliasPathMetadata, - AliasPattern, - DataEffect, - DataManifestCustomResourceFunctionDefinition, - DataPolicyManifest, - DataPolicyManifestListResult, - ErrorAdditionalInfo, - ErrorResponse, - Identity, - NonComplianceMessage, - Override, - ParameterDefinitionsValue, - ParameterDefinitionsValueMetadata, - ParameterValuesValue, - PolicyAssignment, - PolicyAssignmentListResult, - PolicyAssignmentUpdate, - PolicyDefinition, - PolicyDefinitionGroup, - PolicyDefinitionListResult, - PolicyDefinitionReference, - PolicyDefinitionVersion, - PolicyDefinitionVersionListResult, - PolicyExemption, - PolicyExemptionListResult, - PolicyExemptionUpdate, - PolicySetDefinition, - PolicySetDefinitionListResult, - PolicySetDefinitionVersion, - PolicySetDefinitionVersionListResult, - PolicyVariableColumn, - PolicyVariableValueColumnValue, - ResourceSelector, - ResourceTypeAliases, - Selector, - SystemData, - UserAssignedIdentitiesValue, - Variable, - VariableListResult, - VariableValue, - VariableValueListResult, -) - -from ._policy_client_enums import ( # type: ignore - AliasPathAttributes, - AliasPathTokenType, - AliasPatternType, - AliasType, - AssignmentScopeValidation, - CreatedByType, - EnforcementMode, - ExemptionCategory, - OverrideKind, - ParameterType, - PolicyType, - ResourceIdentityType, - SelectorKind, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Alias", - "AliasPath", - "AliasPathMetadata", - "AliasPattern", - "DataEffect", - "DataManifestCustomResourceFunctionDefinition", - "DataPolicyManifest", - "DataPolicyManifestListResult", - "ErrorAdditionalInfo", - "ErrorResponse", - "Identity", - "NonComplianceMessage", - "Override", - "ParameterDefinitionsValue", - "ParameterDefinitionsValueMetadata", - "ParameterValuesValue", - "PolicyAssignment", - "PolicyAssignmentListResult", - "PolicyAssignmentUpdate", - "PolicyDefinition", - "PolicyDefinitionGroup", - "PolicyDefinitionListResult", - "PolicyDefinitionReference", - "PolicyDefinitionVersion", - "PolicyDefinitionVersionListResult", - "PolicyExemption", - "PolicyExemptionListResult", - "PolicyExemptionUpdate", - "PolicySetDefinition", - "PolicySetDefinitionListResult", - "PolicySetDefinitionVersion", - "PolicySetDefinitionVersionListResult", - "PolicyVariableColumn", - "PolicyVariableValueColumnValue", - "ResourceSelector", - "ResourceTypeAliases", - "Selector", - "SystemData", - "UserAssignedIdentitiesValue", - "Variable", - "VariableListResult", - "VariableValue", - "VariableValueListResult", - "AliasPathAttributes", - "AliasPathTokenType", - "AliasPatternType", - "AliasType", - "AssignmentScopeValidation", - "CreatedByType", - "EnforcementMode", - "ExemptionCategory", - "OverrideKind", - "ParameterType", - "PolicyType", - "ResourceIdentityType", - "SelectorKind", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_models_py3.py deleted file mode 100644 index 5292feea9241..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_models_py3.py +++ /dev/null @@ -1,2333 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class Alias(_serialization.Model): - """The alias type. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The alias name. - :vartype name: str - :ivar paths: The paths for an alias. - :vartype paths: list[~azure.mgmt.resource.policy.models.AliasPath] - :ivar type: The type of the alias. Known values are: "NotSpecified", "PlainText", and "Mask". - :vartype type: str or ~azure.mgmt.resource.policy.models.AliasType - :ivar default_path: The default path for an alias. - :vartype default_path: str - :ivar default_pattern: The default pattern for an alias. - :vartype default_pattern: ~azure.mgmt.resource.policy.models.AliasPattern - :ivar default_metadata: The default alias path metadata. Applies to the default path and to any - alias path that doesn't have metadata. - :vartype default_metadata: ~azure.mgmt.resource.policy.models.AliasPathMetadata - """ - - _validation = { - "default_metadata": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "paths": {"key": "paths", "type": "[AliasPath]"}, - "type": {"key": "type", "type": "str"}, - "default_path": {"key": "defaultPath", "type": "str"}, - "default_pattern": {"key": "defaultPattern", "type": "AliasPattern"}, - "default_metadata": {"key": "defaultMetadata", "type": "AliasPathMetadata"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - paths: Optional[list["_models.AliasPath"]] = None, - type: Optional[Union[str, "_models.AliasType"]] = None, - default_path: Optional[str] = None, - default_pattern: Optional["_models.AliasPattern"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The alias name. - :paramtype name: str - :keyword paths: The paths for an alias. - :paramtype paths: list[~azure.mgmt.resource.policy.models.AliasPath] - :keyword type: The type of the alias. Known values are: "NotSpecified", "PlainText", and - "Mask". - :paramtype type: str or ~azure.mgmt.resource.policy.models.AliasType - :keyword default_path: The default path for an alias. - :paramtype default_path: str - :keyword default_pattern: The default pattern for an alias. - :paramtype default_pattern: ~azure.mgmt.resource.policy.models.AliasPattern - """ - super().__init__(**kwargs) - self.name = name - self.paths = paths - self.type = type - self.default_path = default_path - self.default_pattern = default_pattern - self.default_metadata: Optional["_models.AliasPathMetadata"] = None - - -class AliasPath(_serialization.Model): - """The type of the paths for alias. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar path: The path of an alias. - :vartype path: str - :ivar api_versions: The API versions. - :vartype api_versions: list[str] - :ivar pattern: The pattern for an alias path. - :vartype pattern: ~azure.mgmt.resource.policy.models.AliasPattern - :ivar metadata: The metadata of the alias path. If missing, fall back to the default metadata - of the alias. - :vartype metadata: ~azure.mgmt.resource.policy.models.AliasPathMetadata - """ - - _validation = { - "metadata": {"readonly": True}, - } - - _attribute_map = { - "path": {"key": "path", "type": "str"}, - "api_versions": {"key": "apiVersions", "type": "[str]"}, - "pattern": {"key": "pattern", "type": "AliasPattern"}, - "metadata": {"key": "metadata", "type": "AliasPathMetadata"}, - } - - def __init__( - self, - *, - path: Optional[str] = None, - api_versions: Optional[list[str]] = None, - pattern: Optional["_models.AliasPattern"] = None, - **kwargs: Any - ) -> None: - """ - :keyword path: The path of an alias. - :paramtype path: str - :keyword api_versions: The API versions. - :paramtype api_versions: list[str] - :keyword pattern: The pattern for an alias path. - :paramtype pattern: ~azure.mgmt.resource.policy.models.AliasPattern - """ - super().__init__(**kwargs) - self.path = path - self.api_versions = api_versions - self.pattern = pattern - self.metadata: Optional["_models.AliasPathMetadata"] = None - - -class AliasPathMetadata(_serialization.Model): - """AliasPathMetadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The type of the token that the alias path is referring to. Known values are: - "NotSpecified", "Any", "String", "Object", "Array", "Integer", "Number", and "Boolean". - :vartype type: str or ~azure.mgmt.resource.policy.models.AliasPathTokenType - :ivar attributes: The attributes of the token that the alias path is referring to. Known values - are: "None" and "Modifiable". - :vartype attributes: str or ~azure.mgmt.resource.policy.models.AliasPathAttributes - """ - - _validation = { - "type": {"readonly": True}, - "attributes": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "attributes": {"key": "attributes", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[Union[str, "_models.AliasPathTokenType"]] = None - self.attributes: Optional[Union[str, "_models.AliasPathAttributes"]] = None - - -class AliasPattern(_serialization.Model): - """The type of the pattern for an alias path. - - :ivar phrase: The alias pattern phrase. - :vartype phrase: str - :ivar variable: The alias pattern variable. - :vartype variable: str - :ivar type: The type of alias pattern. Known values are: "NotSpecified" and "Extract". - :vartype type: str or ~azure.mgmt.resource.policy.models.AliasPatternType - """ - - _attribute_map = { - "phrase": {"key": "phrase", "type": "str"}, - "variable": {"key": "variable", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, - *, - phrase: Optional[str] = None, - variable: Optional[str] = None, - type: Optional[Union[str, "_models.AliasPatternType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword phrase: The alias pattern phrase. - :paramtype phrase: str - :keyword variable: The alias pattern variable. - :paramtype variable: str - :keyword type: The type of alias pattern. Known values are: "NotSpecified" and "Extract". - :paramtype type: str or ~azure.mgmt.resource.policy.models.AliasPatternType - """ - super().__init__(**kwargs) - self.phrase = phrase - self.variable = variable - self.type = type - - -class DataEffect(_serialization.Model): - """The data effect definition. - - :ivar name: The data effect name. - :vartype name: str - :ivar details_schema: The data effect details schema. - :vartype details_schema: JSON - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "details_schema": {"key": "detailsSchema", "type": "object"}, - } - - def __init__(self, *, name: Optional[str] = None, details_schema: Optional[JSON] = None, **kwargs: Any) -> None: - """ - :keyword name: The data effect name. - :paramtype name: str - :keyword details_schema: The data effect details schema. - :paramtype details_schema: JSON - """ - super().__init__(**kwargs) - self.name = name - self.details_schema = details_schema - - -class DataManifestCustomResourceFunctionDefinition(_serialization.Model): # pylint: disable=name-too-long - """The custom resource function definition. - - :ivar name: The function name as it will appear in the policy rule. eg - 'vault'. - :vartype name: str - :ivar fully_qualified_resource_type: The fully qualified control plane resource type that this - function represents. eg - 'Microsoft.KeyVault/vaults'. - :vartype fully_qualified_resource_type: str - :ivar default_properties: The top-level properties that can be selected on the function's - output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - :vartype default_properties: list[str] - :ivar allow_custom_properties: A value indicating whether the custom properties within the - property bag are allowed. Needs api-version to be specified in the policy rule eg - - vault('2019-06-01'). - :vartype allow_custom_properties: bool - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "fully_qualified_resource_type": {"key": "fullyQualifiedResourceType", "type": "str"}, - "default_properties": {"key": "defaultProperties", "type": "[str]"}, - "allow_custom_properties": {"key": "allowCustomProperties", "type": "bool"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - fully_qualified_resource_type: Optional[str] = None, - default_properties: Optional[list[str]] = None, - allow_custom_properties: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The function name as it will appear in the policy rule. eg - 'vault'. - :paramtype name: str - :keyword fully_qualified_resource_type: The fully qualified control plane resource type that - this function represents. eg - 'Microsoft.KeyVault/vaults'. - :paramtype fully_qualified_resource_type: str - :keyword default_properties: The top-level properties that can be selected on the function's - output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - :paramtype default_properties: list[str] - :keyword allow_custom_properties: A value indicating whether the custom properties within the - property bag are allowed. Needs api-version to be specified in the policy rule eg - - vault('2019-06-01'). - :paramtype allow_custom_properties: bool - """ - super().__init__(**kwargs) - self.name = name - self.fully_qualified_resource_type = fully_qualified_resource_type - self.default_properties = default_properties - self.allow_custom_properties = allow_custom_properties - - -class DataPolicyManifest(_serialization.Model): - """The data policy manifest. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the data policy manifest. - :vartype id: str - :ivar name: The name of the data policy manifest (it's the same as the Policy Mode). - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/dataPolicyManifests). - :vartype type: str - :ivar namespaces: The list of namespaces for the data policy manifest. - :vartype namespaces: list[str] - :ivar policy_mode: The policy mode of the data policy manifest. - :vartype policy_mode: str - :ivar is_built_in_only: A value indicating whether policy mode is allowed only in built-in - definitions. - :vartype is_built_in_only: bool - :ivar resource_type_aliases: An array of resource type aliases. - :vartype resource_type_aliases: list[~azure.mgmt.resource.policy.models.ResourceTypeAliases] - :ivar effects: The effect definition. - :vartype effects: list[~azure.mgmt.resource.policy.models.DataEffect] - :ivar field_values: The non-alias field accessor values that can be used in the policy rule. - :vartype field_values: list[str] - :ivar standard: The standard resource functions (subscription and/or resourceGroup). - :vartype standard: list[str] - :ivar custom: An array of data manifest custom resource definition. - :vartype custom: - list[~azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "namespaces": {"key": "properties.namespaces", "type": "[str]"}, - "policy_mode": {"key": "properties.policyMode", "type": "str"}, - "is_built_in_only": {"key": "properties.isBuiltInOnly", "type": "bool"}, - "resource_type_aliases": {"key": "properties.resourceTypeAliases", "type": "[ResourceTypeAliases]"}, - "effects": {"key": "properties.effects", "type": "[DataEffect]"}, - "field_values": {"key": "properties.fieldValues", "type": "[str]"}, - "standard": {"key": "properties.resourceFunctions.standard", "type": "[str]"}, - "custom": { - "key": "properties.resourceFunctions.custom", - "type": "[DataManifestCustomResourceFunctionDefinition]", - }, - } - - def __init__( - self, - *, - namespaces: Optional[list[str]] = None, - policy_mode: Optional[str] = None, - is_built_in_only: Optional[bool] = None, - resource_type_aliases: Optional[list["_models.ResourceTypeAliases"]] = None, - effects: Optional[list["_models.DataEffect"]] = None, - field_values: Optional[list[str]] = None, - standard: Optional[list[str]] = None, - custom: Optional[list["_models.DataManifestCustomResourceFunctionDefinition"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword namespaces: The list of namespaces for the data policy manifest. - :paramtype namespaces: list[str] - :keyword policy_mode: The policy mode of the data policy manifest. - :paramtype policy_mode: str - :keyword is_built_in_only: A value indicating whether policy mode is allowed only in built-in - definitions. - :paramtype is_built_in_only: bool - :keyword resource_type_aliases: An array of resource type aliases. - :paramtype resource_type_aliases: list[~azure.mgmt.resource.policy.models.ResourceTypeAliases] - :keyword effects: The effect definition. - :paramtype effects: list[~azure.mgmt.resource.policy.models.DataEffect] - :keyword field_values: The non-alias field accessor values that can be used in the policy rule. - :paramtype field_values: list[str] - :keyword standard: The standard resource functions (subscription and/or resourceGroup). - :paramtype standard: list[str] - :keyword custom: An array of data manifest custom resource definition. - :paramtype custom: - list[~azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.namespaces = namespaces - self.policy_mode = policy_mode - self.is_built_in_only = is_built_in_only - self.resource_type_aliases = resource_type_aliases - self.effects = effects - self.field_values = field_values - self.standard = standard - self.custom = custom - - -class DataPolicyManifestListResult(_serialization.Model): - """List of data policy manifests. - - :ivar value: An array of data policy manifests. - :vartype value: list[~azure.mgmt.resource.policy.models.DataPolicyManifest] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[DataPolicyManifest]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.DataPolicyManifest"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: An array of data policy manifests. - :paramtype value: list[~azure.mgmt.resource.policy.models.DataPolicyManifest] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.policy.models.ErrorResponse] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.resource.policy.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorResponse]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorResponse"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class Identity(_serialization.Model): - """Identity for the resource. Policy assignments support a maximum of one identity. That is - either a system assigned identity or a single user assigned identity. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal ID of the resource identity. This property will only be - provided for a system assigned identity. - :vartype principal_id: str - :ivar tenant_id: The tenant ID of the resource identity. This property will only be provided - for a system assigned identity. - :vartype tenant_id: str - :ivar type: The identity type. This is the only required field when adding a system or user - assigned identity to a resource. Known values are: "SystemAssigned", "UserAssigned", and - "None". - :vartype type: str or ~azure.mgmt.resource.policy.models.ResourceIdentityType - :ivar user_assigned_identities: The user identity associated with the policy. The user identity - dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - :vartype user_assigned_identities: dict[str, - ~azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue] - """ - - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentitiesValue}"}, - } - - def __init__( - self, - *, - type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, - user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentitiesValue"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: The identity type. This is the only required field when adding a system or user - assigned identity to a resource. Known values are: "SystemAssigned", "UserAssigned", and - "None". - :paramtype type: str or ~azure.mgmt.resource.policy.models.ResourceIdentityType - :keyword user_assigned_identities: The user identity associated with the policy. The user - identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue] - """ - super().__init__(**kwargs) - self.principal_id: Optional[str] = None - self.tenant_id: Optional[str] = None - self.type = type - self.user_assigned_identities = user_assigned_identities - - -class NonComplianceMessage(_serialization.Model): - """A message that describes why a resource is non-compliant with the policy. This is shown in - 'deny' error messages and on resource's non-compliant compliance results. - - All required parameters must be populated in order to send to server. - - :ivar message: A message that describes why a resource is non-compliant with the policy. This - is shown in 'deny' error messages and on resource's non-compliant compliance results. Required. - :vartype message: str - :ivar policy_definition_reference_id: The policy definition reference ID within a policy set - definition the message is intended for. This is only applicable if the policy assignment - assigns a policy set definition. If this is not provided the message applies to all policies - assigned by this policy assignment. - :vartype policy_definition_reference_id: str - """ - - _validation = { - "message": {"required": True}, - } - - _attribute_map = { - "message": {"key": "message", "type": "str"}, - "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, - } - - def __init__(self, *, message: str, policy_definition_reference_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword message: A message that describes why a resource is non-compliant with the policy. - This is shown in 'deny' error messages and on resource's non-compliant compliance results. - Required. - :paramtype message: str - :keyword policy_definition_reference_id: The policy definition reference ID within a policy set - definition the message is intended for. This is only applicable if the policy assignment - assigns a policy set definition. If this is not provided the message applies to all policies - assigned by this policy assignment. - :paramtype policy_definition_reference_id: str - """ - super().__init__(**kwargs) - self.message = message - self.policy_definition_reference_id = policy_definition_reference_id - - -class Override(_serialization.Model): - """The policy property value override. - - :ivar kind: The override kind. "policyEffect" - :vartype kind: str or ~azure.mgmt.resource.policy.models.OverrideKind - :ivar value: The value to override the policy property. - :vartype value: str - :ivar selectors: The list of the selector expressions. - :vartype selectors: list[~azure.mgmt.resource.policy.models.Selector] - """ - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "value": {"key": "value", "type": "str"}, - "selectors": {"key": "selectors", "type": "[Selector]"}, - } - - def __init__( - self, - *, - kind: Optional[Union[str, "_models.OverrideKind"]] = None, - value: Optional[str] = None, - selectors: Optional[list["_models.Selector"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword kind: The override kind. "policyEffect" - :paramtype kind: str or ~azure.mgmt.resource.policy.models.OverrideKind - :keyword value: The value to override the policy property. - :paramtype value: str - :keyword selectors: The list of the selector expressions. - :paramtype selectors: list[~azure.mgmt.resource.policy.models.Selector] - """ - super().__init__(**kwargs) - self.kind = kind - self.value = value - self.selectors = selectors - - -class ParameterDefinitionsValue(_serialization.Model): - """The definition of a parameter that can be provided to the policy. - - :ivar type: The data type of the parameter. Known values are: "String", "Array", "Object", - "Boolean", "Integer", "Float", and "DateTime". - :vartype type: str or ~azure.mgmt.resource.policy.models.ParameterType - :ivar allowed_values: The allowed values for the parameter. - :vartype allowed_values: list[JSON] - :ivar default_value: The default value for the parameter if no value is provided. - :vartype default_value: JSON - :ivar schema: Provides validation of parameter inputs during assignment using a self-defined - JSON schema. This property is only supported for object-type parameters and follows the - Json.NET Schema 2019-09 implementation. You can learn more about using schemas at - https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/. - :vartype schema: JSON - :ivar metadata: General metadata for the parameter. - :vartype metadata: ~azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "allowed_values": {"key": "allowedValues", "type": "[object]"}, - "default_value": {"key": "defaultValue", "type": "object"}, - "schema": {"key": "schema", "type": "object"}, - "metadata": {"key": "metadata", "type": "ParameterDefinitionsValueMetadata"}, - } - - def __init__( - self, - *, - type: Optional[Union[str, "_models.ParameterType"]] = None, - allowed_values: Optional[list[JSON]] = None, - default_value: Optional[JSON] = None, - schema: Optional[JSON] = None, - metadata: Optional["_models.ParameterDefinitionsValueMetadata"] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: The data type of the parameter. Known values are: "String", "Array", "Object", - "Boolean", "Integer", "Float", and "DateTime". - :paramtype type: str or ~azure.mgmt.resource.policy.models.ParameterType - :keyword allowed_values: The allowed values for the parameter. - :paramtype allowed_values: list[JSON] - :keyword default_value: The default value for the parameter if no value is provided. - :paramtype default_value: JSON - :keyword schema: Provides validation of parameter inputs during assignment using a self-defined - JSON schema. This property is only supported for object-type parameters and follows the - Json.NET Schema 2019-09 implementation. You can learn more about using schemas at - https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/. - :paramtype schema: JSON - :keyword metadata: General metadata for the parameter. - :paramtype metadata: ~azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata - """ - super().__init__(**kwargs) - self.type = type - self.allowed_values = allowed_values - self.default_value = default_value - self.schema = schema - self.metadata = metadata - - -class ParameterDefinitionsValueMetadata(_serialization.Model): - """General metadata for the parameter. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, JSON] - :ivar display_name: The display name for the parameter. - :vartype display_name: str - :ivar description: The description of the parameter. - :vartype description: str - :ivar strong_type: Used when assigning the policy definition through the portal. Provides a - context aware list of values for the user to choose from. - :vartype strong_type: str - :ivar assign_permissions: Set to true to have Azure portal create role assignments on the - resource ID or resource scope value of this parameter during policy assignment. This property - is useful in case you wish to assign permissions outside the assignment scope. - :vartype assign_permissions: bool - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "display_name": {"key": "displayName", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "strong_type": {"key": "strongType", "type": "str"}, - "assign_permissions": {"key": "assignPermissions", "type": "bool"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, JSON]] = None, - display_name: Optional[str] = None, - description: Optional[str] = None, - strong_type: Optional[str] = None, - assign_permissions: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, JSON] - :keyword display_name: The display name for the parameter. - :paramtype display_name: str - :keyword description: The description of the parameter. - :paramtype description: str - :keyword strong_type: Used when assigning the policy definition through the portal. Provides a - context aware list of values for the user to choose from. - :paramtype strong_type: str - :keyword assign_permissions: Set to true to have Azure portal create role assignments on the - resource ID or resource scope value of this parameter during policy assignment. This property - is useful in case you wish to assign permissions outside the assignment scope. - :paramtype assign_permissions: bool - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.display_name = display_name - self.description = description - self.strong_type = strong_type - self.assign_permissions = assign_permissions - - -class ParameterValuesValue(_serialization.Model): - """The value of a parameter. - - :ivar value: The value of the parameter. - :vartype value: JSON - """ - - _attribute_map = { - "value": {"key": "value", "type": "object"}, - } - - def __init__(self, *, value: Optional[JSON] = None, **kwargs: Any) -> None: - """ - :keyword value: The value of the parameter. - :paramtype value: JSON - """ - super().__init__(**kwargs) - self.value = value - - -class PolicyAssignment(_serialization.Model): - """The policy assignment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy assignment. - :vartype id: str - :ivar type: The type of the policy assignment. - :vartype type: str - :ivar name: The name of the policy assignment. - :vartype name: str - :ivar location: The location of the policy assignment. Only required when utilizing managed - identity. - :vartype location: str - :ivar identity: The managed identity associated with the policy assignment. - :vartype identity: ~azure.mgmt.resource.policy.models.Identity - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar display_name: The display name of the policy assignment. - :vartype display_name: str - :ivar policy_definition_id: The ID of the policy definition or policy set definition being - assigned. - :vartype policy_definition_id: str - :ivar definition_version: The version of the policy definition to use. - :vartype definition_version: str - :ivar latest_definition_version: The latest version of the policy definition available. This is - only present if requested via the $expand query parameter. - :vartype latest_definition_version: str - :ivar effective_definition_version: The effective version of the policy definition in use. This - is only present if requested via the $expand query parameter. - :vartype effective_definition_version: str - :ivar scope: The scope for the policy assignment. - :vartype scope: str - :ivar not_scopes: The policy's excluded scopes. - :vartype not_scopes: list[str] - :ivar parameters: The parameter values for the assigned policy rule. The keys are the parameter - names. - :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] - :ivar description: This message will be part of response in case of policy violation. - :vartype description: str - :ivar metadata: The policy assignment metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :vartype metadata: JSON - :ivar enforcement_mode: The policy assignment enforcement mode. Possible values are Default and - DoNotEnforce. Known values are: "Default" and "DoNotEnforce". - :vartype enforcement_mode: str or ~azure.mgmt.resource.policy.models.EnforcementMode - :ivar non_compliance_messages: The messages that describe why a resource is non-compliant with - the policy. - :vartype non_compliance_messages: list[~azure.mgmt.resource.policy.models.NonComplianceMessage] - :ivar resource_selectors: The resource selector list to filter policies by resource properties. - :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :ivar overrides: The policy property value override. - :vartype overrides: list[~azure.mgmt.resource.policy.models.Override] - """ - - _validation = { - "id": {"readonly": True}, - "type": {"readonly": True}, - "name": {"readonly": True}, - "system_data": {"readonly": True}, - "latest_definition_version": {"readonly": True}, - "effective_definition_version": {"readonly": True}, - "scope": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "identity": {"key": "identity", "type": "Identity"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "policy_definition_id": {"key": "properties.policyDefinitionId", "type": "str"}, - "definition_version": {"key": "properties.definitionVersion", "type": "str"}, - "latest_definition_version": {"key": "properties.latestDefinitionVersion", "type": "str"}, - "effective_definition_version": {"key": "properties.effectiveDefinitionVersion", "type": "str"}, - "scope": {"key": "properties.scope", "type": "str"}, - "not_scopes": {"key": "properties.notScopes", "type": "[str]"}, - "parameters": {"key": "properties.parameters", "type": "{ParameterValuesValue}"}, - "description": {"key": "properties.description", "type": "str"}, - "metadata": {"key": "properties.metadata", "type": "object"}, - "enforcement_mode": {"key": "properties.enforcementMode", "type": "str"}, - "non_compliance_messages": {"key": "properties.nonComplianceMessages", "type": "[NonComplianceMessage]"}, - "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, - "overrides": {"key": "properties.overrides", "type": "[Override]"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - identity: Optional["_models.Identity"] = None, - display_name: Optional[str] = None, - policy_definition_id: Optional[str] = None, - definition_version: Optional[str] = None, - not_scopes: Optional[list[str]] = None, - parameters: Optional[dict[str, "_models.ParameterValuesValue"]] = None, - description: Optional[str] = None, - metadata: Optional[JSON] = None, - enforcement_mode: Union[str, "_models.EnforcementMode"] = "Default", - non_compliance_messages: Optional[list["_models.NonComplianceMessage"]] = None, - resource_selectors: Optional[list["_models.ResourceSelector"]] = None, - overrides: Optional[list["_models.Override"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the policy assignment. Only required when utilizing managed - identity. - :paramtype location: str - :keyword identity: The managed identity associated with the policy assignment. - :paramtype identity: ~azure.mgmt.resource.policy.models.Identity - :keyword display_name: The display name of the policy assignment. - :paramtype display_name: str - :keyword policy_definition_id: The ID of the policy definition or policy set definition being - assigned. - :paramtype policy_definition_id: str - :keyword definition_version: The version of the policy definition to use. - :paramtype definition_version: str - :keyword not_scopes: The policy's excluded scopes. - :paramtype not_scopes: list[str] - :keyword parameters: The parameter values for the assigned policy rule. The keys are the - parameter names. - :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] - :keyword description: This message will be part of response in case of policy violation. - :paramtype description: str - :keyword metadata: The policy assignment metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :paramtype metadata: JSON - :keyword enforcement_mode: The policy assignment enforcement mode. Possible values are Default - and DoNotEnforce. Known values are: "Default" and "DoNotEnforce". - :paramtype enforcement_mode: str or ~azure.mgmt.resource.policy.models.EnforcementMode - :keyword non_compliance_messages: The messages that describe why a resource is non-compliant - with the policy. - :paramtype non_compliance_messages: - list[~azure.mgmt.resource.policy.models.NonComplianceMessage] - :keyword resource_selectors: The resource selector list to filter policies by resource - properties. - :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :keyword overrides: The policy property value override. - :paramtype overrides: list[~azure.mgmt.resource.policy.models.Override] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.type: Optional[str] = None - self.name: Optional[str] = None - self.location = location - self.identity = identity - self.system_data: Optional["_models.SystemData"] = None - self.display_name = display_name - self.policy_definition_id = policy_definition_id - self.definition_version = definition_version - self.latest_definition_version: Optional[str] = None - self.effective_definition_version: Optional[str] = None - self.scope: Optional[str] = None - self.not_scopes = not_scopes - self.parameters = parameters - self.description = description - self.metadata = metadata - self.enforcement_mode = enforcement_mode - self.non_compliance_messages = non_compliance_messages - self.resource_selectors = resource_selectors - self.overrides = overrides - - -class PolicyAssignmentListResult(_serialization.Model): - """List of policy assignments. - - :ivar value: An array of policy assignments. - :vartype value: list[~azure.mgmt.resource.policy.models.PolicyAssignment] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PolicyAssignment]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.PolicyAssignment"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: An array of policy assignments. - :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyAssignment] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PolicyAssignmentUpdate(_serialization.Model): - """The policy assignment for Patch request. - - :ivar location: The location of the policy assignment. Only required when utilizing managed - identity. - :vartype location: str - :ivar identity: The managed identity associated with the policy assignment. - :vartype identity: ~azure.mgmt.resource.policy.models.Identity - :ivar resource_selectors: The resource selector list to filter policies by resource properties. - :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :ivar overrides: The policy property value override. - :vartype overrides: list[~azure.mgmt.resource.policy.models.Override] - """ - - _attribute_map = { - "location": {"key": "location", "type": "str"}, - "identity": {"key": "identity", "type": "Identity"}, - "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, - "overrides": {"key": "properties.overrides", "type": "[Override]"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - identity: Optional["_models.Identity"] = None, - resource_selectors: Optional[list["_models.ResourceSelector"]] = None, - overrides: Optional[list["_models.Override"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the policy assignment. Only required when utilizing managed - identity. - :paramtype location: str - :keyword identity: The managed identity associated with the policy assignment. - :paramtype identity: ~azure.mgmt.resource.policy.models.Identity - :keyword resource_selectors: The resource selector list to filter policies by resource - properties. - :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :keyword overrides: The policy property value override. - :paramtype overrides: list[~azure.mgmt.resource.policy.models.Override] - """ - super().__init__(**kwargs) - self.location = location - self.identity = identity - self.resource_selectors = resource_selectors - self.overrides = overrides - - -class PolicyDefinition(_serialization.Model): - """The policy definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy definition. - :vartype id: str - :ivar name: The name of the policy definition. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/policyDefinitions). - :vartype type: str - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, - Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". - :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :ivar mode: The policy definition mode. Some examples are All, Indexed, - Microsoft.KeyVault.Data. - :vartype mode: str - :ivar display_name: The display name of the policy definition. - :vartype display_name: str - :ivar description: The policy definition description. - :vartype description: str - :ivar policy_rule: The policy rule. - :vartype policy_rule: JSON - :ivar metadata: The policy definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :vartype metadata: JSON - :ivar parameters: The parameter definitions for parameters used in the policy rule. The keys - are the parameter names. - :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :ivar version: The policy definition version in #.#.# format. - :vartype version: str - :ivar versions: A list of available versions for this policy definition. - :vartype versions: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "policy_type": {"key": "properties.policyType", "type": "str"}, - "mode": {"key": "properties.mode", "type": "str"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "policy_rule": {"key": "properties.policyRule", "type": "object"}, - "metadata": {"key": "properties.metadata", "type": "object"}, - "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, - "version": {"key": "properties.version", "type": "str"}, - "versions": {"key": "properties.versions", "type": "[str]"}, - } - - def __init__( - self, - *, - policy_type: Optional[Union[str, "_models.PolicyType"]] = None, - mode: str = "Indexed", - display_name: Optional[str] = None, - description: Optional[str] = None, - policy_rule: Optional[JSON] = None, - metadata: Optional[JSON] = None, - parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, - version: Optional[str] = None, - versions: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, - Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". - :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :keyword mode: The policy definition mode. Some examples are All, Indexed, - Microsoft.KeyVault.Data. - :paramtype mode: str - :keyword display_name: The display name of the policy definition. - :paramtype display_name: str - :keyword description: The policy definition description. - :paramtype description: str - :keyword policy_rule: The policy rule. - :paramtype policy_rule: JSON - :keyword metadata: The policy definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :paramtype metadata: JSON - :keyword parameters: The parameter definitions for parameters used in the policy rule. The keys - are the parameter names. - :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :keyword version: The policy definition version in #.#.# format. - :paramtype version: str - :keyword versions: A list of available versions for this policy definition. - :paramtype versions: list[str] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.system_data: Optional["_models.SystemData"] = None - self.policy_type = policy_type - self.mode = mode - self.display_name = display_name - self.description = description - self.policy_rule = policy_rule - self.metadata = metadata - self.parameters = parameters - self.version = version - self.versions = versions - - -class PolicyDefinitionGroup(_serialization.Model): - """The policy definition group. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the group. Required. - :vartype name: str - :ivar display_name: The group's display name. - :vartype display_name: str - :ivar category: The group's category. - :vartype category: str - :ivar description: The group's description. - :vartype description: str - :ivar additional_metadata_id: A resource ID of a resource that contains additional metadata - about the group. - :vartype additional_metadata_id: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - "category": {"key": "category", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "additional_metadata_id": {"key": "additionalMetadataId", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - display_name: Optional[str] = None, - category: Optional[str] = None, - description: Optional[str] = None, - additional_metadata_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the group. Required. - :paramtype name: str - :keyword display_name: The group's display name. - :paramtype display_name: str - :keyword category: The group's category. - :paramtype category: str - :keyword description: The group's description. - :paramtype description: str - :keyword additional_metadata_id: A resource ID of a resource that contains additional metadata - about the group. - :paramtype additional_metadata_id: str - """ - super().__init__(**kwargs) - self.name = name - self.display_name = display_name - self.category = category - self.description = description - self.additional_metadata_id = additional_metadata_id - - -class PolicyDefinitionListResult(_serialization.Model): - """List of policy definitions. - - :ivar value: An array of policy definitions. - :vartype value: list[~azure.mgmt.resource.policy.models.PolicyDefinition] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PolicyDefinition]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.PolicyDefinition"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: An array of policy definitions. - :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyDefinition] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PolicyDefinitionReference(_serialization.Model): - """The policy definition reference. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar policy_definition_id: The ID of the policy definition or policy set definition. Required. - :vartype policy_definition_id: str - :ivar definition_version: The version of the policy definition to use. - :vartype definition_version: str - :ivar latest_definition_version: The latest version of the policy definition available. This is - only present if requested via the $expand query parameter. - :vartype latest_definition_version: str - :ivar effective_definition_version: The effective version of the policy definition in use. This - is only present if requested via the $expand query parameter. - :vartype effective_definition_version: str - :ivar parameters: The parameter values for the referenced policy rule. The keys are the - parameter names. - :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] - :ivar policy_definition_reference_id: A unique id (within the policy set definition) for this - policy definition reference. - :vartype policy_definition_reference_id: str - :ivar group_names: The name of the groups that this policy definition reference belongs to. - :vartype group_names: list[str] - """ - - _validation = { - "policy_definition_id": {"required": True}, - "latest_definition_version": {"readonly": True}, - "effective_definition_version": {"readonly": True}, - } - - _attribute_map = { - "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, - "definition_version": {"key": "definitionVersion", "type": "str"}, - "latest_definition_version": {"key": "latestDefinitionVersion", "type": "str"}, - "effective_definition_version": {"key": "effectiveDefinitionVersion", "type": "str"}, - "parameters": {"key": "parameters", "type": "{ParameterValuesValue}"}, - "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, - "group_names": {"key": "groupNames", "type": "[str]"}, - } - - def __init__( - self, - *, - policy_definition_id: str, - definition_version: Optional[str] = None, - parameters: Optional[dict[str, "_models.ParameterValuesValue"]] = None, - policy_definition_reference_id: Optional[str] = None, - group_names: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword policy_definition_id: The ID of the policy definition or policy set definition. - Required. - :paramtype policy_definition_id: str - :keyword definition_version: The version of the policy definition to use. - :paramtype definition_version: str - :keyword parameters: The parameter values for the referenced policy rule. The keys are the - parameter names. - :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] - :keyword policy_definition_reference_id: A unique id (within the policy set definition) for - this policy definition reference. - :paramtype policy_definition_reference_id: str - :keyword group_names: The name of the groups that this policy definition reference belongs to. - :paramtype group_names: list[str] - """ - super().__init__(**kwargs) - self.policy_definition_id = policy_definition_id - self.definition_version = definition_version - self.latest_definition_version: Optional[str] = None - self.effective_definition_version: Optional[str] = None - self.parameters = parameters - self.policy_definition_reference_id = policy_definition_reference_id - self.group_names = group_names - - -class PolicyDefinitionVersion(_serialization.Model): - """The ID of the policy definition version. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy definition version. - :vartype id: str - :ivar name: The name of the policy definition version. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/policyDefinitions/versions). - :vartype type: str - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, - Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". - :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :ivar mode: The policy definition mode. Some examples are All, Indexed, - Microsoft.KeyVault.Data. - :vartype mode: str - :ivar display_name: The display name of the policy definition. - :vartype display_name: str - :ivar description: The policy definition description. - :vartype description: str - :ivar policy_rule: The policy rule. - :vartype policy_rule: JSON - :ivar metadata: The policy definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :vartype metadata: JSON - :ivar parameters: The parameter definitions for parameters used in the policy rule. The keys - are the parameter names. - :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :ivar version: The policy definition version in #.#.# format. - :vartype version: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "policy_type": {"key": "properties.policyType", "type": "str"}, - "mode": {"key": "properties.mode", "type": "str"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "policy_rule": {"key": "properties.policyRule", "type": "object"}, - "metadata": {"key": "properties.metadata", "type": "object"}, - "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, - "version": {"key": "properties.version", "type": "str"}, - } - - def __init__( - self, - *, - policy_type: Optional[Union[str, "_models.PolicyType"]] = None, - mode: str = "Indexed", - display_name: Optional[str] = None, - description: Optional[str] = None, - policy_rule: Optional[JSON] = None, - metadata: Optional[JSON] = None, - parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, - version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, - Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". - :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :keyword mode: The policy definition mode. Some examples are All, Indexed, - Microsoft.KeyVault.Data. - :paramtype mode: str - :keyword display_name: The display name of the policy definition. - :paramtype display_name: str - :keyword description: The policy definition description. - :paramtype description: str - :keyword policy_rule: The policy rule. - :paramtype policy_rule: JSON - :keyword metadata: The policy definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :paramtype metadata: JSON - :keyword parameters: The parameter definitions for parameters used in the policy rule. The keys - are the parameter names. - :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :keyword version: The policy definition version in #.#.# format. - :paramtype version: str - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.system_data: Optional["_models.SystemData"] = None - self.policy_type = policy_type - self.mode = mode - self.display_name = display_name - self.description = description - self.policy_rule = policy_rule - self.metadata = metadata - self.parameters = parameters - self.version = version - - -class PolicyDefinitionVersionListResult(_serialization.Model): - """List of policy definition versions. - - :ivar value: An array of policy definitions versions. - :vartype value: list[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PolicyDefinitionVersion]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.PolicyDefinitionVersion"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: An array of policy definitions versions. - :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PolicyExemption(_serialization.Model): - """The policy exemption. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar id: The ID of the policy exemption. - :vartype id: str - :ivar name: The name of the policy exemption. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/policyExemptions). - :vartype type: str - :ivar policy_assignment_id: The ID of the policy assignment that is being exempted. Required. - :vartype policy_assignment_id: str - :ivar policy_definition_reference_ids: The policy definition reference ID list when the - associated policy assignment is an assignment of a policy set definition. - :vartype policy_definition_reference_ids: list[str] - :ivar exemption_category: The policy exemption category. Possible values are Waiver and - Mitigated. Required. Known values are: "Waiver" and "Mitigated". - :vartype exemption_category: str or ~azure.mgmt.resource.policy.models.ExemptionCategory - :ivar expires_on: The expiration date and time (in UTC ISO 8601 format yyyy-MM-ddTHH:mm:ssZ) of - the policy exemption. - :vartype expires_on: ~datetime.datetime - :ivar display_name: The display name of the policy exemption. - :vartype display_name: str - :ivar description: The description of the policy exemption. - :vartype description: str - :ivar metadata: The policy exemption metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :vartype metadata: JSON - :ivar resource_selectors: The resource selector list to filter policies by resource properties. - :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :ivar assignment_scope_validation: The option whether validate the exemption is at or under the - assignment scope. Known values are: "Default" and "DoNotValidate". - :vartype assignment_scope_validation: str or - ~azure.mgmt.resource.policy.models.AssignmentScopeValidation - """ - - _validation = { - "system_data": {"readonly": True}, - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "policy_assignment_id": {"required": True}, - "exemption_category": {"required": True}, - } - - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "policy_assignment_id": {"key": "properties.policyAssignmentId", "type": "str"}, - "policy_definition_reference_ids": {"key": "properties.policyDefinitionReferenceIds", "type": "[str]"}, - "exemption_category": {"key": "properties.exemptionCategory", "type": "str"}, - "expires_on": {"key": "properties.expiresOn", "type": "iso-8601"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "metadata": {"key": "properties.metadata", "type": "object"}, - "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, - "assignment_scope_validation": {"key": "properties.assignmentScopeValidation", "type": "str"}, - } - - def __init__( - self, - *, - policy_assignment_id: str, - exemption_category: Union[str, "_models.ExemptionCategory"], - policy_definition_reference_ids: Optional[list[str]] = None, - expires_on: Optional[datetime.datetime] = None, - display_name: Optional[str] = None, - description: Optional[str] = None, - metadata: Optional[JSON] = None, - resource_selectors: Optional[list["_models.ResourceSelector"]] = None, - assignment_scope_validation: Optional[Union[str, "_models.AssignmentScopeValidation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword policy_assignment_id: The ID of the policy assignment that is being exempted. - Required. - :paramtype policy_assignment_id: str - :keyword policy_definition_reference_ids: The policy definition reference ID list when the - associated policy assignment is an assignment of a policy set definition. - :paramtype policy_definition_reference_ids: list[str] - :keyword exemption_category: The policy exemption category. Possible values are Waiver and - Mitigated. Required. Known values are: "Waiver" and "Mitigated". - :paramtype exemption_category: str or ~azure.mgmt.resource.policy.models.ExemptionCategory - :keyword expires_on: The expiration date and time (in UTC ISO 8601 format yyyy-MM-ddTHH:mm:ssZ) - of the policy exemption. - :paramtype expires_on: ~datetime.datetime - :keyword display_name: The display name of the policy exemption. - :paramtype display_name: str - :keyword description: The description of the policy exemption. - :paramtype description: str - :keyword metadata: The policy exemption metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :paramtype metadata: JSON - :keyword resource_selectors: The resource selector list to filter policies by resource - properties. - :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :keyword assignment_scope_validation: The option whether validate the exemption is at or under - the assignment scope. Known values are: "Default" and "DoNotValidate". - :paramtype assignment_scope_validation: str or - ~azure.mgmt.resource.policy.models.AssignmentScopeValidation - """ - super().__init__(**kwargs) - self.system_data: Optional["_models.SystemData"] = None - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.policy_assignment_id = policy_assignment_id - self.policy_definition_reference_ids = policy_definition_reference_ids - self.exemption_category = exemption_category - self.expires_on = expires_on - self.display_name = display_name - self.description = description - self.metadata = metadata - self.resource_selectors = resource_selectors - self.assignment_scope_validation = assignment_scope_validation - - -class PolicyExemptionListResult(_serialization.Model): - """List of policy exemptions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: An array of policy exemptions. - :vartype value: list[~azure.mgmt.resource.policy.models.PolicyExemption] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[PolicyExemption]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[list["_models.PolicyExemption"]] = None, **kwargs: Any) -> None: - """ - :keyword value: An array of policy exemptions. - :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyExemption] - """ - super().__init__(**kwargs) - self.value = value - self.next_link: Optional[str] = None - - -class PolicyExemptionUpdate(_serialization.Model): - """The policy exemption for Patch request. - - :ivar resource_selectors: The resource selector list to filter policies by resource properties. - :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :ivar assignment_scope_validation: The option whether validate the exemption is at or under the - assignment scope. Known values are: "Default" and "DoNotValidate". - :vartype assignment_scope_validation: str or - ~azure.mgmt.resource.policy.models.AssignmentScopeValidation - """ - - _attribute_map = { - "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, - "assignment_scope_validation": {"key": "properties.assignmentScopeValidation", "type": "str"}, - } - - def __init__( - self, - *, - resource_selectors: Optional[list["_models.ResourceSelector"]] = None, - assignment_scope_validation: Optional[Union[str, "_models.AssignmentScopeValidation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_selectors: The resource selector list to filter policies by resource - properties. - :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] - :keyword assignment_scope_validation: The option whether validate the exemption is at or under - the assignment scope. Known values are: "Default" and "DoNotValidate". - :paramtype assignment_scope_validation: str or - ~azure.mgmt.resource.policy.models.AssignmentScopeValidation - """ - super().__init__(**kwargs) - self.resource_selectors = resource_selectors - self.assignment_scope_validation = assignment_scope_validation - - -class PolicySetDefinition(_serialization.Model): - """The policy set definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy set definition. - :vartype id: str - :ivar name: The name of the policy set definition. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/policySetDefinitions). - :vartype type: str - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar policy_type: The type of policy set definition. Possible values are NotSpecified, - BuiltIn, Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and - "Static". - :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :ivar display_name: The display name of the policy set definition. - :vartype display_name: str - :ivar description: The policy set definition description. - :vartype description: str - :ivar metadata: The policy set definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :vartype metadata: JSON - :ivar parameters: The policy set definition parameters that can be used in policy definition - references. - :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :ivar policy_definitions: An array of policy definition references. - :vartype policy_definitions: list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] - :ivar policy_definition_groups: The metadata describing groups of policy definition references - within the policy set definition. - :vartype policy_definition_groups: - list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] - :ivar version: The policy set definition version in #.#.# format. - :vartype version: str - :ivar versions: A list of available versions for this policy set definition. - :vartype versions: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "policy_type": {"key": "properties.policyType", "type": "str"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "metadata": {"key": "properties.metadata", "type": "object"}, - "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, - "policy_definitions": {"key": "properties.policyDefinitions", "type": "[PolicyDefinitionReference]"}, - "policy_definition_groups": {"key": "properties.policyDefinitionGroups", "type": "[PolicyDefinitionGroup]"}, - "version": {"key": "properties.version", "type": "str"}, - "versions": {"key": "properties.versions", "type": "[str]"}, - } - - def __init__( - self, - *, - policy_type: Optional[Union[str, "_models.PolicyType"]] = None, - display_name: Optional[str] = None, - description: Optional[str] = None, - metadata: Optional[JSON] = None, - parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, - policy_definitions: Optional[list["_models.PolicyDefinitionReference"]] = None, - policy_definition_groups: Optional[list["_models.PolicyDefinitionGroup"]] = None, - version: Optional[str] = None, - versions: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword policy_type: The type of policy set definition. Possible values are NotSpecified, - BuiltIn, Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and - "Static". - :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :keyword display_name: The display name of the policy set definition. - :paramtype display_name: str - :keyword description: The policy set definition description. - :paramtype description: str - :keyword metadata: The policy set definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :paramtype metadata: JSON - :keyword parameters: The policy set definition parameters that can be used in policy definition - references. - :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :keyword policy_definitions: An array of policy definition references. - :paramtype policy_definitions: - list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] - :keyword policy_definition_groups: The metadata describing groups of policy definition - references within the policy set definition. - :paramtype policy_definition_groups: - list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] - :keyword version: The policy set definition version in #.#.# format. - :paramtype version: str - :keyword versions: A list of available versions for this policy set definition. - :paramtype versions: list[str] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.system_data: Optional["_models.SystemData"] = None - self.policy_type = policy_type - self.display_name = display_name - self.description = description - self.metadata = metadata - self.parameters = parameters - self.policy_definitions = policy_definitions - self.policy_definition_groups = policy_definition_groups - self.version = version - self.versions = versions - - -class PolicySetDefinitionListResult(_serialization.Model): - """List of policy set definitions. - - :ivar value: An array of policy set definitions. - :vartype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PolicySetDefinition]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.PolicySetDefinition"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: An array of policy set definitions. - :paramtype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PolicySetDefinitionVersion(_serialization.Model): - """The policy set definition version. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy set definition version. - :vartype id: str - :ivar name: The name of the policy set definition version. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/policySetDefinitions/versions). - :vartype type: str - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, - Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". - :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :ivar display_name: The display name of the policy set definition. - :vartype display_name: str - :ivar description: The policy set definition description. - :vartype description: str - :ivar metadata: The policy set definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :vartype metadata: JSON - :ivar parameters: The policy set definition parameters that can be used in policy definition - references. - :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :ivar policy_definitions: An array of policy definition references. - :vartype policy_definitions: list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] - :ivar policy_definition_groups: The metadata describing groups of policy definition references - within the policy set definition. - :vartype policy_definition_groups: - list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] - :ivar version: The policy set definition version in #.#.# format. - :vartype version: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "policy_type": {"key": "properties.policyType", "type": "str"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "metadata": {"key": "properties.metadata", "type": "object"}, - "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, - "policy_definitions": {"key": "properties.policyDefinitions", "type": "[PolicyDefinitionReference]"}, - "policy_definition_groups": {"key": "properties.policyDefinitionGroups", "type": "[PolicyDefinitionGroup]"}, - "version": {"key": "properties.version", "type": "str"}, - } - - def __init__( - self, - *, - policy_type: Optional[Union[str, "_models.PolicyType"]] = None, - display_name: Optional[str] = None, - description: Optional[str] = None, - metadata: Optional[JSON] = None, - parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, - policy_definitions: Optional[list["_models.PolicyDefinitionReference"]] = None, - policy_definition_groups: Optional[list["_models.PolicyDefinitionGroup"]] = None, - version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, - Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". - :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType - :keyword display_name: The display name of the policy set definition. - :paramtype display_name: str - :keyword description: The policy set definition description. - :paramtype description: str - :keyword metadata: The policy set definition metadata. Metadata is an open ended object and is - typically a collection of key value pairs. - :paramtype metadata: JSON - :keyword parameters: The policy set definition parameters that can be used in policy definition - references. - :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] - :keyword policy_definitions: An array of policy definition references. - :paramtype policy_definitions: - list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] - :keyword policy_definition_groups: The metadata describing groups of policy definition - references within the policy set definition. - :paramtype policy_definition_groups: - list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] - :keyword version: The policy set definition version in #.#.# format. - :paramtype version: str - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.system_data: Optional["_models.SystemData"] = None - self.policy_type = policy_type - self.display_name = display_name - self.description = description - self.metadata = metadata - self.parameters = parameters - self.policy_definitions = policy_definitions - self.policy_definition_groups = policy_definition_groups - self.version = version - - -class PolicySetDefinitionVersionListResult(_serialization.Model): - """List of policy set definition versions. - - :ivar value: An array of policy set definition versions. - :vartype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PolicySetDefinitionVersion]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.PolicySetDefinitionVersion"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: An array of policy set definition versions. - :paramtype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :keyword next_link: The URL to use for getting the next set of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PolicyVariableColumn(_serialization.Model): - """The variable column. - - All required parameters must be populated in order to send to server. - - :ivar column_name: The name of this policy variable column. Required. - :vartype column_name: str - """ - - _validation = { - "column_name": {"required": True}, - } - - _attribute_map = { - "column_name": {"key": "columnName", "type": "str"}, - } - - def __init__(self, *, column_name: str, **kwargs: Any) -> None: - """ - :keyword column_name: The name of this policy variable column. Required. - :paramtype column_name: str - """ - super().__init__(**kwargs) - self.column_name = column_name - - -class PolicyVariableValueColumnValue(_serialization.Model): - """The name value tuple for this variable value column. - - All required parameters must be populated in order to send to server. - - :ivar column_name: Column name for the variable value. Required. - :vartype column_name: str - :ivar column_value: Column value for the variable value; this can be an integer, double, - boolean, null or a string. Required. - :vartype column_value: JSON - """ - - _validation = { - "column_name": {"required": True}, - "column_value": {"required": True}, - } - - _attribute_map = { - "column_name": {"key": "columnName", "type": "str"}, - "column_value": {"key": "columnValue", "type": "object"}, - } - - def __init__(self, *, column_name: str, column_value: JSON, **kwargs: Any) -> None: - """ - :keyword column_name: Column name for the variable value. Required. - :paramtype column_name: str - :keyword column_value: Column value for the variable value; this can be an integer, double, - boolean, null or a string. Required. - :paramtype column_value: JSON - """ - super().__init__(**kwargs) - self.column_name = column_name - self.column_value = column_value - - -class ResourceSelector(_serialization.Model): - """The resource selector to filter policies by resource properties. - - :ivar name: The name of the resource selector. - :vartype name: str - :ivar selectors: The list of the selector expressions. - :vartype selectors: list[~azure.mgmt.resource.policy.models.Selector] - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "selectors": {"key": "selectors", "type": "[Selector]"}, - } - - def __init__( - self, *, name: Optional[str] = None, selectors: Optional[list["_models.Selector"]] = None, **kwargs: Any - ) -> None: - """ - :keyword name: The name of the resource selector. - :paramtype name: str - :keyword selectors: The list of the selector expressions. - :paramtype selectors: list[~azure.mgmt.resource.policy.models.Selector] - """ - super().__init__(**kwargs) - self.name = name - self.selectors = selectors - - -class ResourceTypeAliases(_serialization.Model): - """The resource type aliases definition. - - :ivar resource_type: The resource type name. - :vartype resource_type: str - :ivar aliases: The aliases for property names. - :vartype aliases: list[~azure.mgmt.resource.policy.models.Alias] - """ - - _attribute_map = { - "resource_type": {"key": "resourceType", "type": "str"}, - "aliases": {"key": "aliases", "type": "[Alias]"}, - } - - def __init__( - self, *, resource_type: Optional[str] = None, aliases: Optional[list["_models.Alias"]] = None, **kwargs: Any - ) -> None: - """ - :keyword resource_type: The resource type name. - :paramtype resource_type: str - :keyword aliases: The aliases for property names. - :paramtype aliases: list[~azure.mgmt.resource.policy.models.Alias] - """ - super().__init__(**kwargs) - self.resource_type = resource_type - self.aliases = aliases - - -class Selector(_serialization.Model): - """The selector expression. - - :ivar kind: The selector kind. Known values are: "resourceLocation", "resourceType", - "resourceWithoutLocation", and "policyDefinitionReferenceId". - :vartype kind: str or ~azure.mgmt.resource.policy.models.SelectorKind - :ivar in_property: The list of values to filter in. - :vartype in_property: list[str] - :ivar not_in: The list of values to filter out. - :vartype not_in: list[str] - """ - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "in_property": {"key": "in", "type": "[str]"}, - "not_in": {"key": "notIn", "type": "[str]"}, - } - - def __init__( - self, - *, - kind: Optional[Union[str, "_models.SelectorKind"]] = None, - in_property: Optional[list[str]] = None, - not_in: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword kind: The selector kind. Known values are: "resourceLocation", "resourceType", - "resourceWithoutLocation", and "policyDefinitionReferenceId". - :paramtype kind: str or ~azure.mgmt.resource.policy.models.SelectorKind - :keyword in_property: The list of values to filter in. - :paramtype in_property: list[str] - :keyword not_in: The list of values to filter out. - :paramtype not_in: list[str] - """ - super().__init__(**kwargs) - self.kind = kind - self.in_property = in_property - self.not_in = not_in - - -class SystemData(_serialization.Model): - """Metadata pertaining to creation and last modification of the resource. - - :ivar created_by: The identity that created the resource. - :vartype created_by: str - :ivar created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType - :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime - :ivar last_modified_by: The identity that last modified the resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Known values - are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType - :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime - """ - - _attribute_map = { - "created_by": {"key": "createdBy", "type": "str"}, - "created_by_type": {"key": "createdByType", "type": "str"}, - "created_at": {"key": "createdAt", "type": "iso-8601"}, - "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, - "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, - "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, - } - - def __init__( - self, - *, - created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - created_at: Optional[datetime.datetime] = None, - last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - last_modified_at: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword created_by: The identity that created the resource. - :paramtype created_by: str - :keyword created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :paramtype created_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType - :keyword created_at: The timestamp of resource creation (UTC). - :paramtype created_at: ~datetime.datetime - :keyword last_modified_by: The identity that last modified the resource. - :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Known - values are: "User", "Application", "ManagedIdentity", and "Key". - :paramtype last_modified_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__(**kwargs) - self.created_by = created_by - self.created_by_type = created_by_type - self.created_at = created_at - self.last_modified_by = last_modified_by - self.last_modified_by_type = last_modified_by_type - self.last_modified_at = last_modified_at - - -class UserAssignedIdentitiesValue(_serialization.Model): - """UserAssignedIdentitiesValue. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal id of user assigned identity. - :vartype principal_id: str - :ivar client_id: The client id of user assigned identity. - :vartype client_id: str - """ - - _validation = { - "principal_id": {"readonly": True}, - "client_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "client_id": {"key": "clientId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.principal_id: Optional[str] = None - self.client_id: Optional[str] = None - - -class Variable(_serialization.Model): - """The variable. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar id: The ID of the variable. - :vartype id: str - :ivar name: The name of the variable. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/variables). - :vartype type: str - :ivar columns: Variable column definitions. Required. - :vartype columns: list[~azure.mgmt.resource.policy.models.PolicyVariableColumn] - """ - - _validation = { - "system_data": {"readonly": True}, - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "columns": {"required": True}, - } - - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "columns": {"key": "properties.columns", "type": "[PolicyVariableColumn]"}, - } - - def __init__(self, *, columns: list["_models.PolicyVariableColumn"], **kwargs: Any) -> None: - """ - :keyword columns: Variable column definitions. Required. - :paramtype columns: list[~azure.mgmt.resource.policy.models.PolicyVariableColumn] - """ - super().__init__(**kwargs) - self.system_data: Optional["_models.SystemData"] = None - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.columns = columns - - -class VariableListResult(_serialization.Model): - """List of variables. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: An array of variables. - :vartype value: list[~azure.mgmt.resource.policy.models.Variable] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Variable]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[list["_models.Variable"]] = None, **kwargs: Any) -> None: - """ - :keyword value: An array of variables. - :paramtype value: list[~azure.mgmt.resource.policy.models.Variable] - """ - super().__init__(**kwargs) - self.value = value - self.next_link: Optional[str] = None - - -class VariableValue(_serialization.Model): - """The variable value. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData - :ivar id: The ID of the variable. - :vartype id: str - :ivar name: The name of the variable. - :vartype name: str - :ivar type: The type of the resource (Microsoft.Authorization/variables/values). - :vartype type: str - :ivar values: Variable value column value array. Required. - :vartype values: list[~azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue] - """ - - _validation = { - "system_data": {"readonly": True}, - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "values": {"required": True}, - } - - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "values": {"key": "properties.values", "type": "[PolicyVariableValueColumnValue]"}, - } - - def __init__(self, *, values: list["_models.PolicyVariableValueColumnValue"], **kwargs: Any) -> None: - """ - :keyword values: Variable value column value array. Required. - :paramtype values: list[~azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue] - """ - super().__init__(**kwargs) - self.system_data: Optional["_models.SystemData"] = None - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.values = values - - -class VariableValueListResult(_serialization.Model): - """List of variable values. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: An array of variable values. - :vartype value: list[~azure.mgmt.resource.policy.models.VariableValue] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[VariableValue]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[list["_models.VariableValue"]] = None, **kwargs: Any) -> None: - """ - :keyword value: An array of variable values. - :paramtype value: list[~azure.mgmt.resource.policy.models.VariableValue] - """ - super().__init__(**kwargs) - self.value = value - self.next_link: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_policy_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_policy_client_enums.py deleted file mode 100644 index 72647fa2a336..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/models/_policy_client_enums.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class AliasPathAttributes(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The attributes of the token that the alias path is referring to.""" - - NONE = "None" - """The token that the alias path is referring to has no attributes.""" - MODIFIABLE = "Modifiable" - """The token that the alias path is referring to is modifiable by policies with 'modify' effect.""" - - -class AliasPathTokenType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of the token that the alias path is referring to.""" - - NOT_SPECIFIED = "NotSpecified" - """The token type is not specified.""" - ANY = "Any" - """The token type can be anything.""" - STRING = "String" - """The token type is string.""" - OBJECT = "Object" - """The token type is object.""" - ARRAY = "Array" - """The token type is array.""" - INTEGER = "Integer" - """The token type is integer.""" - NUMBER = "Number" - """The token type is number.""" - BOOLEAN = "Boolean" - """The token type is boolean.""" - - -class AliasPatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of alias pattern.""" - - NOT_SPECIFIED = "NotSpecified" - """NotSpecified is not allowed.""" - EXTRACT = "Extract" - """Extract is the only allowed value.""" - - -class AliasType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of the alias.""" - - NOT_SPECIFIED = "NotSpecified" - """Alias type is unknown (same as not providing alias type).""" - PLAIN_TEXT = "PlainText" - """Alias value is not secret.""" - MASK = "Mask" - """Alias value is secret.""" - - -class AssignmentScopeValidation(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The option whether validate the exemption is at or under the assignment scope.""" - - DEFAULT = "Default" - """This option will validate the exemption is at or under the assignment scope.""" - DO_NOT_VALIDATE = "DoNotValidate" - """This option will bypass the validation the exemption scope is at or under the policy assignment - scope.""" - - -class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity that created the resource.""" - - USER = "User" - APPLICATION = "Application" - MANAGED_IDENTITY = "ManagedIdentity" - KEY = "Key" - - -class EnforcementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The policy assignment enforcement mode. Possible values are Default and DoNotEnforce.""" - - DEFAULT = "Default" - """The policy effect is enforced during resource creation or update.""" - DO_NOT_ENFORCE = "DoNotEnforce" - """The policy effect is not enforced during resource creation or update.""" - - -class ExemptionCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The policy exemption category. Possible values are Waiver and Mitigated.""" - - WAIVER = "Waiver" - """This category of exemptions usually means the scope is not applicable for the policy.""" - MITIGATED = "Mitigated" - """This category of exemptions usually means the mitigation actions have been applied to the - scope.""" - - -class OverrideKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The override kind.""" - - POLICY_EFFECT = "policyEffect" - """It will override the policy effect type.""" - - -class ParameterType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The data type of the parameter.""" - - STRING = "String" - ARRAY = "Array" - OBJECT = "Object" - BOOLEAN = "Boolean" - INTEGER = "Integer" - FLOAT = "Float" - DATE_TIME = "DateTime" - - -class PolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static.""" - - NOT_SPECIFIED = "NotSpecified" - BUILT_IN = "BuiltIn" - CUSTOM = "Custom" - STATIC = "Static" - - -class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The identity type. This is the only required field when adding a system or user assigned - identity to a resource. - """ - - SYSTEM_ASSIGNED = "SystemAssigned" - """Indicates that a system assigned identity is associated with the resource.""" - USER_ASSIGNED = "UserAssigned" - """Indicates that a system assigned identity is associated with the resource.""" - NONE = "None" - """Indicates that no identity is associated with the resource or that the existing identity should - be removed.""" - - -class SelectorKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The selector kind.""" - - RESOURCE_LOCATION = "resourceLocation" - """The selector kind to filter policies by the resource location.""" - RESOURCE_TYPE = "resourceType" - """The selector kind to filter policies by the resource type.""" - RESOURCE_WITHOUT_LOCATION = "resourceWithoutLocation" - """The selector kind to filter policies by the resource without location.""" - POLICY_DEFINITION_REFERENCE_ID = "policyDefinitionReferenceId" - """The selector kind to filter policies by the policy definition reference ID.""" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/__init__.py deleted file mode 100644 index f302859689f6..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import DataPolicyManifestsOperations # type: ignore -from ._operations import PolicyDefinitionsOperations # type: ignore -from ._operations import PolicyDefinitionVersionsOperations # type: ignore -from ._operations import PolicySetDefinitionsOperations # type: ignore -from ._operations import PolicySetDefinitionVersionsOperations # type: ignore -from ._operations import PolicyAssignmentsOperations # type: ignore -from ._operations import PolicyExemptionsOperations # type: ignore -from ._operations import VariablesOperations # type: ignore -from ._operations import VariableValuesOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataPolicyManifestsOperations", - "PolicyDefinitionsOperations", - "PolicyDefinitionVersionsOperations", - "PolicySetDefinitionsOperations", - "PolicySetDefinitionVersionsOperations", - "PolicyAssignmentsOperations", - "PolicyExemptionsOperations", - "VariablesOperations", - "VariableValuesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_operations.py deleted file mode 100644 index 29e62121956e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_operations.py +++ /dev/null @@ -1,10155 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import PolicyClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_data_policy_manifests_get_by_policy_mode_request( # pylint: disable=name-too-long - policy_mode: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/dataPolicyManifests/{policyMode}") - path_format_arguments = { - "policyMode": _SERIALIZER.url("policy_mode", policy_mode, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_data_policy_manifests_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/dataPolicyManifests") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_create_or_update_request( # pylint: disable=name-too-long - policy_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_delete_request( - policy_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_get_request( - policy_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_get_built_in_request( # pylint: disable=name-too-long - policy_definition_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}") - path_format_arguments = { - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_create_or_update_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, policy_definition_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_delete_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, policy_definition_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_get_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, policy_definition_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_list_request( - subscription_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_list_built_in_request( # pylint: disable=name-too-long - *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definitions_list_by_management_group_request( # pylint: disable=name-too-long - management_group_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_list_all_builtins_request( # pylint: disable=name-too-long - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/listPolicyDefinitionVersions") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_list_all_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/listPolicyDefinitionVersions", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_list_all_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/listPolicyDefinitionVersions" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_create_or_update_request( # pylint: disable=name-too-long - policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_delete_request( # pylint: disable=name-too-long - policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_get_request( # pylint: disable=name-too-long - policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_get_built_in_request( # pylint: disable=name-too-long - policy_definition_name: str, policy_definition_version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_create_or_update_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_delete_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_get_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_list_request( # pylint: disable=name-too-long - policy_definition_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_list_built_in_request( # pylint: disable=name-too-long - policy_definition_name: str, *, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions" - ) - path_format_arguments = { - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_definition_versions_list_by_management_group_request( # pylint: disable=name-too-long - management_group_name: str, policy_definition_name: str, *, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policyDefinitionName": _SERIALIZER.url( - "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_create_or_update_request( # pylint: disable=name-too-long - policy_set_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_delete_request( # pylint: disable=name-too-long - policy_set_definition_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_get_request( - policy_set_definition_name: str, subscription_id: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_get_built_in_request( # pylint: disable=name-too-long - policy_set_definition_name: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" - ) - path_format_arguments = { - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_list_request( # pylint: disable=name-too-long - subscription_id: str, - *, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_list_built_in_request( # pylint: disable=name-too-long - *, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policySetDefinitions") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_create_or_update_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, policy_set_definition_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_delete_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, policy_set_definition_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_get_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, policy_set_definition_name: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definitions_list_by_management_group_request( # pylint: disable=name-too-long - management_group_id: str, - *, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_list_all_builtins_request( # pylint: disable=name-too-long - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/listPolicySetDefinitionVersions") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_list_all_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/listPolicySetDefinitionVersions", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_list_all_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/listPolicySetDefinitionVersions", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_create_or_update_request( # pylint: disable=name-too-long - policy_set_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_delete_request( # pylint: disable=name-too-long - policy_set_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_get_request( # pylint: disable=name-too-long - policy_set_definition_name: str, - policy_definition_version: str, - subscription_id: str, - *, - expand: Optional[str] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_get_built_in_request( # pylint: disable=name-too-long - policy_set_definition_name: str, policy_definition_version: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_list_request( # pylint: disable=name-too-long - policy_set_definition_name: str, - subscription_id: str, - *, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_list_built_in_request( # pylint: disable=name-too-long - policy_set_definition_name: str, *, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions" - ) - path_format_arguments = { - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_create_or_update_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_delete_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_get_at_management_group_request( # pylint: disable=name-too-long - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - *, - expand: Optional[str] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - "policyDefinitionVersion": _SERIALIZER.url( - "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_set_definition_versions_list_by_management_group_request( # pylint: disable=name-too-long - management_group_name: str, - policy_set_definition_name: str, - *, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions", - ) - path_format_arguments = { - "managementGroupName": _SERIALIZER.url( - "management_group_name", management_group_name, "str", max_length=90, min_length=1 - ), - "policySetDefinitionName": _SERIALIZER.url( - "policy_set_definition_name", - policy_set_definition_name, - "str", - pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_delete_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyAssignmentName": _SERIALIZER.url( - "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_create_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyAssignmentName": _SERIALIZER.url( - "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_get_request( - scope: str, policy_assignment_name: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyAssignmentName": _SERIALIZER.url( - "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_update_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyAssignmentName": _SERIALIZER.url( - "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_list_for_resource_group_request( # pylint: disable=name-too-long - resource_group_name: str, - subscription_id: str, - *, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_list_for_resource_request( # pylint: disable=name-too-long - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - subscription_id: str, - *, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", pattern=r"^.+$"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_list_for_management_group_request( # pylint: disable=name-too-long - management_group_id: str, - *, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_list_request( - subscription_id: str, - *, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_delete_by_id_request( # pylint: disable=name-too-long - policy_assignment_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{policyAssignmentId}") - path_format_arguments = { - "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_create_by_id_request( # pylint: disable=name-too-long - policy_assignment_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{policyAssignmentId}") - path_format_arguments = { - "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_get_by_id_request( # pylint: disable=name-too-long - policy_assignment_id: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{policyAssignmentId}") - path_format_arguments = { - "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_assignments_update_by_id_request( # pylint: disable=name-too-long - policy_assignment_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/{policyAssignmentId}") - path_format_arguments = { - "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_delete_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_create_or_update_request( # pylint: disable=name-too-long - scope: str, policy_exemption_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_get_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_update_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" - ) - path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), - "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_list_request( - subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyExemptions" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_list_for_resource_group_request( # pylint: disable=name-too-long - resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyExemptions", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_list_for_resource_request( # pylint: disable=name-too-long - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any, -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyExemptions", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" - ), - "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), - "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), - "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_policy_exemptions_list_for_management_group_request( # pylint: disable=name-too-long - management_group_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyExemptions", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_delete_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_create_or_update_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_get_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_delete_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_create_or_update_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_get_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variables_list_for_management_group_request( # pylint: disable=name-too-long - management_group_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_delete_request( - variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_create_or_update_request( # pylint: disable=name-too-long - variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_get_request( - variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_list_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_list_for_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_delete_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_create_or_update_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_variable_values_get_at_management_group_request( # pylint: disable=name-too-long - management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", - ) - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), - "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class DataPolicyManifestsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`data_policy_manifests` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get_by_policy_mode(self, policy_mode: str, **kwargs: Any) -> _models.DataPolicyManifest: - """Retrieves a data policy manifest. - - This operation retrieves the data policy manifest with the given policy mode. - - :param policy_mode: The policy mode of the data policy manifest to get. Required. - :type policy_mode: str - :return: DataPolicyManifest or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.DataPolicyManifest - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) - cls: ClsType[_models.DataPolicyManifest] = kwargs.pop("cls", None) - - _request = build_data_policy_manifests_get_by_policy_mode_request( - policy_mode=policy_mode, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataPolicyManifest", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.DataPolicyManifest"]: - """Retrieves data policy manifests. - - This operation retrieves a list of all the data policy manifests that match the optional given - $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not - provided, the unfiltered list includes all data policy manifests for data resource types. If - $filter=namespace is provided, the returned list only includes all data policy manifests that - have a namespace matching the provided value. - - :param filter: The filter to apply on the operation. Valid values for $filter are: "namespace - eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq - '{value}' is provided, the returned list only includes all data policy manifests that have a - namespace matching the provided value. Default value is None. - :type filter: str - :return: An iterator like instance of either DataPolicyManifest or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.DataPolicyManifest] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) - cls: ClsType[_models.DataPolicyManifestListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_data_policy_manifests_list_request( - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("DataPolicyManifestListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class PolicyDefinitionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`policy_definitions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - policy_definition_name: str, - parameters: _models.PolicyDefinition, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - policy_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO[bytes]], **kwargs: Any - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Is either a PolicyDefinition type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinition") - - _request = build_policy_definitions_create_or_update_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, policy_definition_name: str, **kwargs: Any - ) -> None: - """Deletes a policy definition in a subscription. - - This operation deletes the policy definition in the given subscription with the given name. - - :param policy_definition_name: The name of the policy definition to delete. Required. - :type policy_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definitions_delete_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: - """Retrieves a policy definition in a subscription. - - This operation retrieves the policy definition in the given subscription with the given name. - - :param policy_definition_name: The name of the policy definition to get. Required. - :type policy_definition_name: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - _request = build_policy_definitions_get_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: - """Retrieves a built-in policy definition. - - This operation retrieves the built-in policy definition with the given name. - - :param policy_definition_name: The name of the built-in policy definition to get. Required. - :type policy_definition_name: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - _request = build_policy_definitions_get_built_in_request( - policy_definition_name=policy_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - policy_definition_name: str, - parameters: _models.PolicyDefinition, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a management group. - - This operation creates or updates a policy definition in the given management group with the - given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - policy_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a management group. - - This operation creates or updates a policy definition in the given management group with the - given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_management_group( - self, - management_group_id: str, - policy_definition_name: str, - parameters: Union[_models.PolicyDefinition, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyDefinition: - """Creates or updates a policy definition in a management group. - - This operation creates or updates a policy definition in the given management group with the - given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to create. Required. - :type policy_definition_name: str - :param parameters: The policy definition properties. Is either a PolicyDefinition type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinition") - - _request = build_policy_definitions_create_or_update_at_management_group_request( - management_group_id=management_group_id, - policy_definition_name=policy_definition_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_management_group( # pylint: disable=inconsistent-return-statements - self, management_group_id: str, policy_definition_name: str, **kwargs: Any - ) -> None: - """Deletes a policy definition in a management group. - - This operation deletes the policy definition in the given management group with the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to delete. Required. - :type policy_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definitions_delete_at_management_group_request( - management_group_id=management_group_id, - policy_definition_name=policy_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_management_group( - self, management_group_id: str, policy_definition_name: str, **kwargs: Any - ) -> _models.PolicyDefinition: - """Retrieve a policy definition in a management group. - - This operation retrieves the policy definition in the given management group with the given - name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_definition_name: The name of the policy definition to get. Required. - :type policy_definition_name: str - :return: PolicyDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) - - _request = build_policy_definitions_get_at_management_group_request( - management_group_id=management_group_id, - policy_definition_name=policy_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyDefinition"]: - """Retrieves policy definitions in a subscription. - - This operation retrieves a list of all the policy definitions in a given subscription that - match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType - -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list - includes all policy definitions associated with the subscription, including those that apply - directly or from management groups that contain the given subscription. If - $filter=atExactScope() is provided, the returned list only includes all policy definitions that - at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list - only includes all policy definitions whose type match the {value}. Possible policyType values - are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, - the returned list only includes all policy definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy definitions whose type match - the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy - definitions whose category match the {value}. Default value is None. - :type filter: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definitions_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyDefinition"]: - """Retrieve built-in policy definitions. - - This operation retrieves a list of all the built-in policy definitions that match the optional - given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes - all built-in policy definitions whose type match the {value}. Possible policyType values are - NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the - returned list only includes all built-in policy definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy definitions whose type match - the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy - definitions whose category match the {value}. Default value is None. - :type filter: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definitions_list_built_in_request( - filter=filter, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_management_group( - self, management_group_id: str, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyDefinition"]: - """Retrieve policy definitions in a management group. - - This operation retrieves a list of all the policy definitions in a given management group that - match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType - -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list - includes all policy definitions associated with the management group, including those that - apply directly or from management groups that contain the given management group. If - $filter=atExactScope() is provided, the returned list only includes all policy definitions that - at the given management group. If $filter='policyType -eq {value}' is provided, the returned - list only includes all policy definitions whose type match the {value}. Possible policyType - values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is - provided, the returned list only includes all policy definitions whose category match the - {value}. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy definitions whose type match - the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy - definitions whose category match the {value}. Default value is None. - :type filter: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definitions_list_by_management_group_request( - management_group_id=management_group_id, - filter=filter, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class PolicyDefinitionVersionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`policy_definition_versions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_all_builtins(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: - """Lists all built-in policy definition versions. - - This operation lists all the built-in policy definition versions for all built-in policy - definitions. - - :return: PolicyDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_list_all_builtins_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_all_at_management_group( - self, management_group_name: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersionListResult: - """Lists all policy definition versions at management group scope. - - This operation lists all the policy definition versions for all policy definitions at the - management group scope. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :return: PolicyDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_list_all_at_management_group_request( - management_group_name=management_group_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_all(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: - """Lists all policy definition versions within a subscription. - - This operation lists all the policy definition versions for all policy definitions within a - subscription. - - :return: PolicyDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_list_all_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - policy_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicyDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - policy_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - policy_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition in a subscription. - - This operation creates or updates a policy definition in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinitionVersion") - - _request = build_policy_definition_versions_create_or_update_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> None: - """Deletes a policy definition version in a subscription. - - This operation deletes the policy definition version in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_delete_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Retrieves a policy definition version in a subscription. - - This operation retrieves the policy definition version in the given subscription with the given - name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_get_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_built_in( - self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Retrieves a built-in policy definition version. - - This operation retrieves the built-in policy definition version with the given name. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_get_built_in_request( - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update_at_management_group( - self, - management_group_name: str, - policy_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicyDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition version in a management group. - - This operation creates or updates a policy definition version in the given management group - with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_management_group( - self, - management_group_name: str, - policy_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition version in a management group. - - This operation creates or updates a policy definition version in the given management group - with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_management_group( - self, - management_group_name: str, - policy_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyDefinitionVersion: - """Creates or updates a policy definition version in a management group. - - This operation creates or updates a policy definition version in the given management group - with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyDefinitionVersion") - - _request = build_policy_definition_versions_create_or_update_at_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_management_group( # pylint: disable=inconsistent-return-statements - self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> None: - """Deletes a policy definition in a management group. - - This operation deletes the policy definition in the given management group with the given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_delete_at_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_management_group( - self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> _models.PolicyDefinitionVersion: - """Retrieve a policy definition version in a management group. - - This operation retrieves the policy definition version in the given management group with the - given name. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param policy_definition_version: The policy definition version. The format is x.y.z where x - is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: PolicyDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_definition_versions_get_at_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyDefinitionVersion"]: - """Retrieves policy definition versions for a given policy definition in a subscription. - - This operation retrieves a list of all the policy definition versions for the given policy - definition. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definition_versions_list_request( - policy_definition_name=policy_definition_name, - subscription_id=self._config.subscription_id, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyDefinitionVersion"]: - """Retrieve built-in policy definition versions. - - This operation retrieves a list of all the built-in policy definition versions for the given - policy definition. - - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definition_versions_list_built_in_request( - policy_definition_name=policy_definition_name, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_management_group( - self, management_group_name: str, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyDefinitionVersion"]: - """Retrieve policy definition versions in a management group policy definition. - - This operation retrieves a list of all the policy definition versions for the given policy - definition in the given management group. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_definition_name: The name of the policy definition. Required. - :type policy_definition_name: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_definition_versions_list_by_management_group_request( - management_group_name=management_group_name, - policy_definition_name=policy_definition_name, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class PolicySetDefinitionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`policy_set_definitions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - policy_set_definition_name: str, - parameters: _models.PolicySetDefinition, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given subscription with the - given name. - - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - policy_set_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given subscription with the - given name. - - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO[bytes]], **kwargs: Any - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given subscription with the - given name. - - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Is either a PolicySetDefinition type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinition") - - _request = build_policy_set_definitions_create_or_update_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, policy_set_definition_name: str, **kwargs: Any - ) -> None: - """Deletes a policy set definition. - - This operation deletes the policy set definition in the given subscription with the given name. - - :param policy_set_definition_name: The name of the policy set definition to delete. Required. - :type policy_set_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_delete_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicySetDefinition: - """Retrieves a policy set definition. - - This operation retrieves the policy set definition in the given subscription with the given - name. - - :param policy_set_definition_name: The name of the policy set definition to get. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_get_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_built_in( - self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicySetDefinition: - """Retrieves a built in policy set definition. - - This operation retrieves the built-in policy set definition with the given name. - - :param policy_set_definition_name: The name of the policy set definition to get. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_get_built_in_request( - policy_set_definition_name=policy_set_definition_name, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicySetDefinition"]: - """Retrieves the policy set definitions for a subscription. - - This operation retrieves a list of all the policy set definitions in a given subscription that - match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType - -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list - includes all policy set definitions associated with the subscription, including those that - apply directly or from management groups that contain the given subscription. If - $filter=atExactScope() is provided, the returned list only includes all policy set definitions - that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned - list only includes all policy set definitions whose type match the {value}. Possible policyType - values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the - returned list only includes all policy set definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy set definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy set definitions whose type - match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy set - definitions whose category match the {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definitions_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicySetDefinition"]: - """Retrieves built-in policy set definitions. - - This operation retrieves a list of all the built-in policy set definitions that match the - optional given $filter. If $filter='category -eq {value}' is provided, the returned list only - includes all built-in policy set definitions whose category match the {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy set definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy set definitions whose type - match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy set - definitions whose category match the {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definitions_list_built_in_request( - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - policy_set_definition_name: str, - parameters: _models.PolicySetDefinition, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given management group with - the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - policy_set_definition_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given management group with - the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_management_group( - self, - management_group_id: str, - policy_set_definition_name: str, - parameters: Union[_models.PolicySetDefinition, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicySetDefinition: - """Creates or updates a policy set definition. - - This operation creates or updates a policy set definition in the given management group with - the given name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to create. Required. - :type policy_set_definition_name: str - :param parameters: The policy set definition properties. Is either a PolicySetDefinition type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinition") - - _request = build_policy_set_definitions_create_or_update_at_management_group_request( - management_group_id=management_group_id, - policy_set_definition_name=policy_set_definition_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_management_group( # pylint: disable=inconsistent-return-statements - self, management_group_id: str, policy_set_definition_name: str, **kwargs: Any - ) -> None: - """Deletes a policy set definition. - - This operation deletes the policy set definition in the given management group with the given - name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to delete. Required. - :type policy_set_definition_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_delete_at_management_group_request( - management_group_id=management_group_id, - policy_set_definition_name=policy_set_definition_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_management_group( - self, management_group_id: str, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicySetDefinition: - """Retrieves a policy set definition. - - This operation retrieves the policy set definition in the given management group with the given - name. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param policy_set_definition_name: The name of the policy set definition to get. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinition or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) - - _request = build_policy_set_definitions_get_at_management_group_request( - management_group_id=management_group_id, - policy_set_definition_name=policy_set_definition_name, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_management_group( - self, - management_group_id: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, - ) -> ItemPaged["_models.PolicySetDefinition"]: - """Retrieves all policy set definitions in management group. - - This operation retrieves a list of all the policy set definitions in a given management group - that match the optional given $filter. Valid values for $filter are: 'atExactScope()', - 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered - list includes all policy set definitions associated with the management group, including those - that apply directly or from management groups that contain the given management group. If - $filter=atExactScope() is provided, the returned list only includes all policy set definitions - that at the given management group. If $filter='policyType -eq {value}' is provided, the - returned list only includes all policy set definitions whose type match the {value}. Possible - policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is - provided, the returned list only includes all policy set definitions whose category match the - {value}. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: - 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list - only includes all policy set definitions that at the given scope. If $filter='policyType -eq - {value}' is provided, the returned list only includes all policy set definitions whose type - match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If - $filter='category -eq {value}' is provided, the returned list only includes all policy set - definitions whose category match the {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definitions_list_by_management_group_request( - management_group_id=management_group_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class PolicySetDefinitionVersionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`policy_set_definition_versions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_all_builtins(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: - """Lists all built-in policy set definition versions. - - This operation lists all the built-in policy set definition versions for all built-in policy - set definitions. - - :return: PolicySetDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_list_all_builtins_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_all_at_management_group( - self, management_group_name: str, **kwargs: Any - ) -> _models.PolicySetDefinitionVersionListResult: - """Lists all policy set definition versions at management group scope. - - This operation lists all the policy set definition versions for all policy set definitions at - the management group scope. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :return: PolicySetDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_list_all_at_management_group_request( - management_group_name=management_group_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_all(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: - """Lists all policy set definition versions within a subscription. - - This operation lists all the policy set definition versions for all policy set definitions - within a subscription. - - :return: PolicySetDefinitionVersionListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_list_all_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicySetDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given subscription - with the given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given subscription - with the given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given subscription - with the given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition properties. Is either a PolicySetDefinitionVersion - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") - - _request = build_policy_set_definition_versions_create_or_update_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> None: - """Deletes a policy set definition version. - - This operation deletes the policy set definition version in the given subscription with the - given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_delete_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, - policy_set_definition_name: str, - policy_definition_version: str, - expand: Optional[str] = None, - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Retrieves a policy set definition version. - - This operation retrieves the policy set definition version in the given subscription with the - given name and version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_get_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - subscription_id=self._config.subscription_id, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_built_in( - self, - policy_set_definition_name: str, - policy_definition_version: str, - expand: Optional[str] = None, - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Retrieves a built in policy set definition version. - - This operation retrieves the built-in policy set definition version with the given name and - version. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_get_built_in_request( - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: - """Retrieves the policy set definition versions for a given policy set definition in a - subscription. - - This operation retrieves a list of all the policy set definition versions for the given policy - set definition. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definition_versions_list_request( - policy_set_definition_name=policy_set_definition_name, - subscription_id=self._config.subscription_id, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_built_in( - self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: - """Retrieves built-in policy set definition versions. - - This operation retrieves a list of all the built-in policy set definition versions for the - given built-in policy set definition. - - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definition_versions_list_built_in_request( - policy_set_definition_name=policy_set_definition_name, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create_or_update_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: _models.PolicySetDefinitionVersion, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given management group - with the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition version properties. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given management group - with the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition version properties. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Creates or updates a policy set definition version. - - This operation creates or updates a policy set definition version in the given management group - with the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param parameters: The policy set definition version properties. Is either a - PolicySetDefinitionVersion type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") - - _request = build_policy_set_definition_versions_create_or_update_at_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_management_group( # pylint: disable=inconsistent-return-statements - self, management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any - ) -> None: - """Deletes a policy set definition version. - - This operation deletes the policy set definition version in the given management group with the - given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_delete_at_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_at_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - policy_definition_version: str, - expand: Optional[str] = None, - **kwargs: Any, - ) -> _models.PolicySetDefinitionVersion: - """Retrieves a policy set definition version. - - This operation retrieves the policy set definition version in the given management group with - the given name and version. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param policy_definition_version: The policy set definition version. The format is x.y.z where - x is the major version number, y is the minor version number, and z is the patch number. - Required. - :type policy_definition_version: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicySetDefinitionVersion or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) - - _request = build_policy_set_definition_versions_get_at_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - policy_definition_version=policy_definition_version, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_management_group( - self, - management_group_name: str, - policy_set_definition_name: str, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, - ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: - """Retrieves all policy set definition versions for a given policy set definition in a management - group. - - This operation retrieves a list of all the policy set definition versions for the given policy - set definition in a given management group. - - :param management_group_name: The name of the management group. The name is case insensitive. - Required. - :type management_group_name: str - :param policy_set_definition_name: The name of the policy set definition. Required. - :type policy_set_definition_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicySetDefinitionVersion or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_set_definition_versions_list_by_management_group_request( - management_group_name=management_group_name, - policy_set_definition_name=policy_set_definition_name, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class PolicyAssignmentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`policy_assignments` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: - """Deletes a policy assignment. - - This operation deletes a policy assignment, given its name and the scope it was created in. The - scope of a policy assignment is the part of its ID preceding - '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment to delete. Required. - :type policy_assignment_name: str - :return: PolicyAssignment or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) - - _request = build_policy_assignments_delete_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - scope: str, - policy_assignment_name: str, - parameters: _models.PolicyAssignment, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates a policy assignment with the given scope and name. Policy - assignments apply to all resources contained within their scope. For example, when you assign a - policy at resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for the policy assignment. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - scope: str, - policy_assignment_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates a policy assignment with the given scope and name. Policy - assignments apply to all resources contained within their scope. For example, when you assign a - policy at resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for the policy assignment. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - scope: str, - policy_assignment_name: str, - parameters: Union[_models.PolicyAssignment, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates a policy assignment with the given scope and name. Policy - assignments apply to all resources contained within their scope. For example, when you assign a - policy at resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignment") - - _request = build_policy_assignments_create_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get( - self, scope: str, policy_assignment_name: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicyAssignment: - """Retrieves a policy assignment. - - This operation retrieves a single policy assignment, given its name and the scope it was - created at. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment to get. Required. - :type policy_assignment_name: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - _request = build_policy_assignments_get_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update( - self, - scope: str, - policy_assignment_name: str, - parameters: _models.PolicyAssignmentUpdate, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates a policy assignment with the given scope and name. Policy assignments - apply to all resources contained within their scope. For example, when you assign a policy at - resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - scope: str, - policy_assignment_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates a policy assignment with the given scope and name. Policy assignments - apply to all resources contained within their scope. For example, when you assign a policy at - resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - scope: str, - policy_assignment_name: str, - parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates a policy assignment with the given scope and name. Policy assignments - apply to all resources contained within their scope. For example, when you assign a policy at - resource group scope, that policy applies to all resources in the group. - - :param scope: The scope of the policy assignment. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_assignment_name: The name of the policy assignment. Required. - :type policy_assignment_name: str - :param parameters: Parameters for policy assignment patch request. Is either a - PolicyAssignmentUpdate type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") - - _request = build_policy_assignments_update_request( - scope=scope, - policy_assignment_name=policy_assignment_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, - ) -> ItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a resource group. - - This operation retrieves the list of all policy assignments associated with the given resource - group in the given subscription that match the optional given $filter. Valid values for $filter - are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not - provided, the unfiltered list includes all policy assignments associated with the resource - group, including those that apply directly or apply from containing scopes, as well as any - applied to resources contained within the resource group. If $filter=atScope() is provided, the - returned list includes all policy assignments that apply to the resource group, which is - everything in the unfiltered list except those applied to resources contained within the - resource group. If $filter=atExactScope() is provided, the returned list only includes all - policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is - provided, the returned list includes all policy assignments of the policy definition whose id - is {value} that apply to the resource group. - - :param resource_group_name: The name of the resource group that contains policy assignments. - Required. - :type resource_group_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_for_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_resource( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, - ) -> ItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a resource. - - This operation retrieves the list of all policy assignments associated with the specified - resource in the given resource group and subscription that match the optional given $filter. - Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq - '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments - associated with the resource, including those that apply directly or from all containing - scopes, as well as any applied to resources contained within the resource. If $filter=atScope() - is provided, the returned list includes all policy assignments that apply to the resource, - which is everything in the unfiltered list except those applied to resources contained within - the resource. If $filter=atExactScope() is provided, the returned list only includes all policy - assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, - the returned list includes all policy assignments of the policy definition whose id is {value} - that apply to the resource. Three parameters plus the resource name are used to identify a - specific resource. If the resource is not part of a parent resource (the more common case), the - parent resource path should not be provided (or provided as ''). For example a web app could be - specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', - {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent - resource, then all parameters should be provided. For example a virtual machine DNS name could - be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == - 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == - 'MyComputerName'). A convenient alternative to providing the namespace and type name separately - is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', - {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == - 'MyWebApp'). - - :param resource_group_name: The name of the resource group containing the resource. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. For example, the - namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource path. Use empty string if there is none. - Required. - :type parent_resource_path: str - :param resource_type: The resource type name. For example the type name of a web app is 'sites' - (from Microsoft.Web/sites). Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_for_resource_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group( - self, - management_group_id: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any, - ) -> ItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a management group. - - This operation retrieves the list of all policy assignments applicable to the management group - that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or - 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes - all policy assignments that are assigned to the management group or the management group's - ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy - assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is - provided, the returned list includes all policy assignments of the policy definition whose id - is {value} that apply to the management group. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_for_management_group_request( - management_group_id=management_group_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list( - self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyAssignment"]: - """Retrieves all policy assignments that apply to a subscription. - - This operation retrieves the list of all policy assignments associated with the given - subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the - unfiltered list includes all policy assignments associated with the subscription, including - those that apply directly or from management groups that contain the given subscription, as - well as any applied to objects contained within the subscription. If $filter=atScope() is - provided, the returned list includes all policy assignments that apply to the subscription, - which is everything in the unfiltered list except those applied to objects contained within the - subscription. If $filter=atExactScope() is provided, the returned list only includes all policy - assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, - the returned list includes all policy assignments of the policy definition whose id is {value}. - - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering - is performed. If $filter=atScope() is provided, the returned list only includes all policy - assignments that apply to the scope, which is everything in the unfiltered list except those - applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, - the returned list only includes all policy assignments that at the given scope. If - $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy - assignments of the policy definition whose id is {value}. Default value is None. - :type filter: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :param top: Maximum number of records to return. When the $top filter is not provided, it will - return 500 records. Default value is None. - :type top: int - :return: An iterator like instance of either PolicyAssignment or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_assignments_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - expand=expand, - top=top, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: - """Deletes a policy assignment. - - This operation deletes the policy with the given ID. Policy assignment IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - formats for {scope} are: '/providers/Microsoft.Management/managementGroups/{managementGroup}' - (management group), '/subscriptions/{subscriptionId}' (subscription), - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' (resource group), or - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}' - (resource). - - :param policy_assignment_id: The ID of the policy assignment to delete. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :return: PolicyAssignment or None or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) - - _request = build_policy_assignments_delete_by_id_request( - policy_assignment_id=policy_assignment_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_by_id( - self, - policy_assignment_id: str, - parameters: _models.PolicyAssignment, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates the policy assignment with the given ID. Policy assignments - made on a scope apply to all resources contained in that scope. For example, when you assign a - policy to a resource group that policy applies to all resources in the group. Policy assignment - IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to create. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_by_id( - self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates the policy assignment with the given ID. Policy assignments - made on a scope apply to all resources contained in that scope. For example, when you assign a - policy to a resource group that policy applies to all resources in the group. Policy assignment - IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to create. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_by_id( - self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO[bytes]], **kwargs: Any - ) -> _models.PolicyAssignment: - """Creates or updates a policy assignment. - - This operation creates or updates the policy assignment with the given ID. Policy assignments - made on a scope apply to all resources contained in that scope. For example, when you assign a - policy to a resource group that policy applies to all resources in the group. Policy assignment - IDs have this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to create. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignment") - - _request = build_policy_assignments_create_by_id_request( - policy_assignment_id=policy_assignment_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_by_id( - self, policy_assignment_id: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.PolicyAssignment: - """Retrieves the policy assignment with the given ID. - - The operation retrieves the policy assignment with the given ID. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to get. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param expand: Comma-separated list of additional properties to be included in the response. - Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is - None. - :type expand: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - _request = build_policy_assignments_get_by_id_request( - policy_assignment_id=policy_assignment_id, - expand=expand, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update_by_id( - self, - policy_assignment_id: str, - parameters: _models.PolicyAssignmentUpdate, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates the policy assignment with the given ID. Policy assignments made on a - scope apply to all resources contained in that scope. For example, when you assign a policy to - a resource group that policy applies to all resources in the group. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to update. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_by_id( - self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates the policy assignment with the given ID. Policy assignments made on a - scope apply to all resources contained in that scope. For example, when you assign a policy to - a resource group that policy applies to all resources in the group. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to update. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment patch request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_by_id( - self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], **kwargs: Any - ) -> _models.PolicyAssignment: - """Updates a policy assignment. - - This operation updates the policy assignment with the given ID. Policy assignments made on a - scope apply to all resources contained in that scope. For example, when you assign a policy to - a resource group that policy applies to all resources in the group. Policy assignment IDs have - this format: - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid - scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - - :param policy_assignment_id: The ID of the policy assignment to update. Use the format - '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. - :type policy_assignment_id: str - :param parameters: Parameters for policy assignment patch request. Is either a - PolicyAssignmentUpdate type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] - :return: PolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") - - _request = build_policy_assignments_update_by_id_request( - policy_assignment_id=policy_assignment_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class PolicyExemptionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`policy_exemptions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, scope: str, policy_exemption_name: str, **kwargs: Any - ) -> None: - """Deletes a policy exemption. - - This operation deletes a policy exemption, given its name and the scope it was created in. The - scope of a policy exemption is the part of its ID preceding - '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_policy_exemptions_delete_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update( - self, - scope: str, - policy_exemption_name: str, - parameters: _models.PolicyExemption, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyExemption: - """Creates or updates a policy exemption. - - This operation creates or updates a policy exemption with the given scope and name. Policy - exemptions apply to all resources contained within their scope. For example, when you create a - policy exemption at resource group scope for a policy assignment at the same or above level, - the exemption exempts to all applicable resources in the resource group. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for the policy exemption. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - scope: str, - policy_exemption_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyExemption: - """Creates or updates a policy exemption. - - This operation creates or updates a policy exemption with the given scope and name. Policy - exemptions apply to all resources contained within their scope. For example, when you create a - policy exemption at resource group scope for a policy assignment at the same or above level, - the exemption exempts to all applicable resources in the resource group. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for the policy exemption. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - scope: str, - policy_exemption_name: str, - parameters: Union[_models.PolicyExemption, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyExemption: - """Creates or updates a policy exemption. - - This operation creates or updates a policy exemption with the given scope and name. Policy - exemptions apply to all resources contained within their scope. For example, when you create a - policy exemption at resource group scope for a policy assignment at the same or above level, - the exemption exempts to all applicable resources in the resource group. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for the policy exemption. Is either a PolicyExemption type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption or IO[bytes] - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyExemption") - - _request = build_policy_exemptions_create_or_update_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> _models.PolicyExemption: - """Retrieves a policy exemption. - - This operation retrieves a single policy exemption, given its name and the scope it was created - at. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) - - _request = build_policy_exemptions_get_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update( - self, - scope: str, - policy_exemption_name: str, - parameters: _models.PolicyExemptionUpdate, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyExemption: - """Updates a policy exemption. - - This operation updates a policy exemption with the given scope and name. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for policy exemption patch request. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - scope: str, - policy_exemption_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.PolicyExemption: - """Updates a policy exemption. - - This operation updates a policy exemption with the given scope and name. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for policy exemption patch request. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - scope: str, - policy_exemption_name: str, - parameters: Union[_models.PolicyExemptionUpdate, IO[bytes]], - **kwargs: Any, - ) -> _models.PolicyExemption: - """Updates a policy exemption. - - This operation updates a policy exemption with the given scope and name. - - :param scope: The scope of the policy exemption. Valid scopes are: management group (format: - '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: - '/subscriptions/{subscriptionId}'), resource group (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - Required. - :type scope: str - :param policy_exemption_name: The name of the policy exemption to delete. Required. - :type policy_exemption_name: str - :param parameters: Parameters for policy exemption patch request. Is either a - PolicyExemptionUpdate type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate or IO[bytes] - :return: PolicyExemption or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PolicyExemptionUpdate") - - _request = build_policy_exemptions_update_request( - scope=scope, - policy_exemption_name=policy_exemption_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a subscription. - - This operation retrieves the list of all policy exemptions associated with the given - subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, the unfiltered list includes all policy exemptions associated with the subscription, - including those that apply directly or from management groups that contain the given - subscription, as well as any applied to objects contained within the subscription. - - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_resource_group( - self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a resource group. - - This operation retrieves the list of all policy exemptions associated with the given resource - group in the given subscription that match the optional given $filter. Valid values for $filter - are: 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If - $filter is not provided, the unfiltered list includes all policy exemptions associated with the - resource group, including those that apply directly or apply from containing scopes, as well as - any applied to resources contained within the resource group. - - :param resource_group_name: The name of the resource group containing the resource. Required. - :type resource_group_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_for_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_resource( - self, - resource_group_name: str, - resource_provider_namespace: str, - parent_resource_path: str, - resource_type: str, - resource_name: str, - filter: Optional[str] = None, - **kwargs: Any, - ) -> ItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a resource. - - This operation retrieves the list of all policy exemptions associated with the specified - resource in the given resource group and subscription that match the optional given $filter. - Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or - 'policyAssignmentId eq '{value}''. If $filter is not provided, the unfiltered list includes all - policy exemptions associated with the resource, including those that apply directly or from all - containing scopes, as well as any applied to resources contained within the resource. Three - parameters plus the resource name are used to identify a specific resource. If the resource is - not part of a parent resource (the more common case), the parent resource path should not be - provided (or provided as ''). For example a web app could be specified as - ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == - 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all - parameters should be provided. For example a virtual machine DNS name could be specified as - ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == - 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == - 'MyComputerName'). A convenient alternative to providing the namespace and type name separately - is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', - {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == - 'MyWebApp'). - - :param resource_group_name: The name of the resource group containing the resource. Required. - :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. For example, the - namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - Required. - :type resource_provider_namespace: str - :param parent_resource_path: The parent resource path. Use empty string if there is none. - Required. - :type parent_resource_path: str - :param resource_type: The resource type name. For example the type name of a web app is 'sites' - (from Microsoft.Web/sites). Required. - :type resource_type: str - :param resource_name: The name of the resource. Required. - :type resource_name: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_for_resource_request( - resource_group_name=resource_group_name, - resource_provider_namespace=resource_provider_namespace, - parent_resource_path=parent_resource_path, - resource_type=resource_type, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group( - self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.PolicyExemption"]: - """Retrieves all policy exemptions that apply to a management group. - - This operation retrieves the list of all policy exemptions applicable to the management group - that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', - 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter=atScope() is provided, the - returned list includes all policy exemptions that are assigned to the management group or the - management group's ancestors. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', - 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not - provided, no filtering is performed. If $filter is not provided, the unfiltered list includes - all policy exemptions associated with the scope, including those that apply directly or apply - from containing scopes. If $filter=atScope() is provided, the returned list only includes all - policy exemptions that apply to the scope, which is everything in the unfiltered list except - those applied to sub scopes contained within the given scope. If $filter=atExactScope() is - provided, the returned list only includes all policy exemptions that at the given scope. If - $filter=excludeExpired() is provided, the returned list only includes all policy exemptions - that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq - '{value}' is provided. the returned list only includes all policy exemptions that are - associated with the give policyAssignmentId. Default value is None. - :type filter: str - :return: An iterator like instance of either PolicyExemption or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) - cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_policy_exemptions_list_for_management_group_request( - management_group_id=management_group_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class VariablesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`variables` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def delete(self, variable_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Deletes a variable. - - This operation deletes a variable, given its name and the subscription it was created in. The - scope of a variable is the part of its ID preceding - '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variables_delete_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update( - self, variable_name: str, parameters: _models.Variable, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given subscription and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, variable_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given subscription and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, variable_name: str, parameters: Union[_models.Variable, IO[bytes]], **kwargs: Any - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given subscription and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Variable") - - _request = build_variables_create_or_update_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, variable_name: str, **kwargs: Any) -> _models.Variable: - """Retrieves a variable. - - This operation retrieves a single variable, given its name and the subscription it was created - at. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - _request = build_variables_get_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_at_management_group( # pylint: disable=inconsistent-return-statements - self, management_group_id: str, variable_name: str, **kwargs: Any - ) -> None: - """Deletes a variable. - - This operation deletes a variable, given its name and the management group it was created in. - The scope of a variable is the part of its ID preceding - '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variables_delete_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - parameters: _models.Variable, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given management group and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given management group and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - parameters: Union[_models.Variable, IO[bytes]], - **kwargs: Any, - ) -> _models.Variable: - """Creates or updates a variable. - - This operation creates or updates a variable with the given management group and name. Policy - variables can only be used by a policy definition at the scope they are created or below. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Variable") - - _request = build_variables_create_or_update_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_at_management_group(self, management_group_id: str, variable_name: str, **kwargs: Any) -> _models.Variable: - """Retrieves a variable. - - This operation retrieves a single variable, given its name and the management group it was - created at. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: Variable or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.Variable - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.Variable] = kwargs.pop("cls", None) - - _request = build_variables_get_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Variable", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.Variable"]: - """Retrieves all variables that are at this subscription level. - - This operation retrieves the list of all variables associated with the given subscription. - - :return: An iterator like instance of either Variable or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.Variable] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variables_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("VariableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group(self, management_group_id: str, **kwargs: Any) -> ItemPaged["_models.Variable"]: - """Retrieves all variables that are at this management group level. - - This operation retrieves the list of all variables applicable to the management group. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :return: An iterator like instance of either Variable or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.Variable] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variables_list_for_management_group_request( - management_group_id=management_group_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("VariableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class VariableValuesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.policy.PolicyClient`'s - :attr:`variable_values` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, variable_name: str, variable_value_name: str, **kwargs: Any - ) -> None: - """Deletes a variable value. - - This operation deletes a variable value, given its name, the subscription it was created in, - and the variable it belongs to. The scope of a variable value is the part of its ID preceding - '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variable_values_delete_request( - variable_name=variable_name, - variable_value_name=variable_value_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update( - self, - variable_name: str, - variable_value_name: str, - parameters: _models.VariableValue, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given subscription and name for a - given variable. Variable values are scoped to the variable for which they are created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - variable_name: str, - variable_value_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given subscription and name for a - given variable. Variable values are scoped to the variable for which they are created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - variable_name: str, - variable_value_name: str, - parameters: Union[_models.VariableValue, IO[bytes]], - **kwargs: Any, - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given subscription and name for a - given variable. Variable values are scoped to the variable for which they are created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Is either a VariableValue type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "VariableValue") - - _request = build_variable_values_create_or_update_request( - variable_name=variable_name, - variable_value_name=variable_value_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> _models.VariableValue: - """Retrieves a variable value. - - This operation retrieves a single variable value; given its name, subscription it was created - at and the variable it's created for. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - _request = build_variable_values_get_request( - variable_name=variable_name, - variable_value_name=variable_value_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, variable_name: str, **kwargs: Any) -> ItemPaged["_models.VariableValue"]: - """List variable values for a variable. - - This operation retrieves the list of all variable values associated with the given variable - that is at a subscription level. - - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: An iterator like instance of either VariableValue or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.VariableValue] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variable_values_list_request( - variable_name=variable_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("VariableValueListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_for_management_group( - self, management_group_id: str, variable_name: str, **kwargs: Any - ) -> ItemPaged["_models.VariableValue"]: - """List variable values at management group level. - - This operation retrieves the list of all variable values applicable the variable indicated at - the management group scope. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :return: An iterator like instance of either VariableValue or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.VariableValue] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_variable_values_list_for_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - _request = HttpRequest("GET", next_link) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("VariableValueListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def delete_at_management_group( # pylint: disable=inconsistent-return-statements - self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any - ) -> None: - """Deletes a variable value. - - This operation deletes a variable value, given its name, the management group it was created - in, and the variable it belongs to. The scope of a variable value is the part of its ID - preceding '/providers/Microsoft.Authorization/variables/{variableName}'. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_variable_values_delete_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - variable_value_name=variable_value_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - variable_value_name: str, - parameters: _models.VariableValue, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given management group and name for - a given variable. Variable values are scoped to the variable for which they are created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - variable_value_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given management group and name for - a given variable. Variable values are scoped to the variable for which they are created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update_at_management_group( - self, - management_group_id: str, - variable_name: str, - variable_value_name: str, - parameters: Union[_models.VariableValue, IO[bytes]], - **kwargs: Any, - ) -> _models.VariableValue: - """Creates or updates a variable value. - - This operation creates or updates a variable value with the given management group and name for - a given variable. Variable values are scoped to the variable for which they are created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :param parameters: Parameters for the variable value. Is either a VariableValue type or a - IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "VariableValue") - - _request = build_variable_values_create_or_update_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - variable_value_name=variable_value_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_at_management_group( - self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any - ) -> _models.VariableValue: - """Retrieves a variable value. - - This operation retrieves a single variable value; given its name, management group it was - created at and the variable it's created for. - - :param management_group_id: The ID of the management group. Required. - :type management_group_id: str - :param variable_name: The name of the variable to operate on. Required. - :type variable_name: str - :param variable_value_name: The name of the variable value to operate on. Required. - :type variable_value_name: str - :return: VariableValue or the result of cls(response) - :rtype: ~azure.mgmt.resource.policy.models.VariableValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) - cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) - - _request = build_variable_values_get_at_management_group_request( - management_group_id=management_group_id, - variable_name=variable_name, - variable_value_name=variable_value_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("VariableValue", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/__init__.py deleted file mode 100644 index afa2f3e705c9..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._resource_private_link_client import ResourcePrivateLinkClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ResourcePrivateLinkClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_configuration.py deleted file mode 100644 index 895eb4b8a4a5..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ResourcePrivateLinkClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ResourcePrivateLinkClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2020-05-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_resource_private_link_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_resource_private_link_client.py deleted file mode 100644 index 63ef53af419e..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_resource_private_link_client.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import ResourcePrivateLinkClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import PrivateLinkAssociationOperations, ResourceManagementPrivateLinkOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class ResourcePrivateLinkClient: - """Provides operations for managing private link resources. - - :ivar private_link_association: PrivateLinkAssociationOperations operations - :vartype private_link_association: - azure.mgmt.resource.privatelinks.operations.PrivateLinkAssociationOperations - :ivar resource_management_private_link: ResourceManagementPrivateLinkOperations operations - :vartype resource_management_private_link: - azure.mgmt.resource.privatelinks.operations.ResourceManagementPrivateLinkOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ResourcePrivateLinkClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.private_link_association = PrivateLinkAssociationOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.resource_management_private_link = ResourceManagementPrivateLinkOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/__init__.py deleted file mode 100644 index bea0c4df00b3..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._resource_private_link_client import ResourcePrivateLinkClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ResourcePrivateLinkClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_configuration.py deleted file mode 100644 index ea26e9c2f6e1..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_configuration.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ResourcePrivateLinkClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ResourcePrivateLinkClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2020-05-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py deleted file mode 100644 index 3ac191d8e425..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/_resource_private_link_client.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import ResourcePrivateLinkClientConfiguration -from .operations import PrivateLinkAssociationOperations, ResourceManagementPrivateLinkOperations - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class ResourcePrivateLinkClient: - """Provides operations for managing private link resources. - - :ivar private_link_association: PrivateLinkAssociationOperations operations - :vartype private_link_association: - azure.mgmt.resource.privatelinks.aio.operations.PrivateLinkAssociationOperations - :ivar resource_management_private_link: ResourceManagementPrivateLinkOperations operations - :vartype resource_management_private_link: - azure.mgmt.resource.privatelinks.aio.operations.ResourceManagementPrivateLinkOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2020-05-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = ResourcePrivateLinkClientConfiguration( - credential=credential, - subscription_id=subscription_id, - cloud_setting=cloud_setting, - credential_scopes=credential_scopes, - **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.private_link_association = PrivateLinkAssociationOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.resource_management_private_link = ResourceManagementPrivateLinkOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/__init__.py deleted file mode 100644 index 39e87c00bee0..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import PrivateLinkAssociationOperations # type: ignore -from ._operations import ResourceManagementPrivateLinkOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "PrivateLinkAssociationOperations", - "ResourceManagementPrivateLinkOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_operations.py deleted file mode 100644 index f68acf267882..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_operations.py +++ /dev/null @@ -1,705 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import ( - build_private_link_association_delete_request, - build_private_link_association_get_request, - build_private_link_association_list_request, - build_private_link_association_put_request, - build_resource_management_private_link_delete_request, - build_resource_management_private_link_get_request, - build_resource_management_private_link_list_by_resource_group_request, - build_resource_management_private_link_list_request, - build_resource_management_private_link_put_request, -) -from .._configuration import ResourcePrivateLinkClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class PrivateLinkAssociationOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.privatelinks.aio.ResourcePrivateLinkClient`'s - :attr:`private_link_association` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def put( - self, - group_id: str, - pla_id: str, - parameters: _models.PrivateLinkAssociationObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateLinkAssociation: - """Create a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :param parameters: Parameters supplied to create the private link association. Required. - :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def put( - self, - group_id: str, - pla_id: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateLinkAssociation: - """Create a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :param parameters: Parameters supplied to create the private link association. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def put( - self, - group_id: str, - pla_id: str, - parameters: Union[_models.PrivateLinkAssociationObject, IO[bytes]], - **kwargs: Any - ) -> _models.PrivateLinkAssociation: - """Create a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :param parameters: Parameters supplied to create the private link association. Is either a - PrivateLinkAssociationObject type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject or - IO[bytes] - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PrivateLinkAssociationObject") - - _request = build_private_link_association_put_request( - group_id=group_id, - pla_id=pla_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, group_id: str, pla_id: str, **kwargs: Any) -> _models.PrivateLinkAssociation: - """Get a single private link association. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) - - _request = build_private_link_association_get_request( - group_id=group_id, - pla_id=pla_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, group_id: str, pla_id: str, **kwargs: Any) -> None: - """Delete a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_private_link_association_delete_request( - group_id=group_id, - pla_id=pla_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def list(self, group_id: str, **kwargs: Any) -> _models.PrivateLinkAssociationGetResult: - """Get a private link association for a management group scope. - - :param group_id: The management group ID. Required. - :type group_id: str - :return: PrivateLinkAssociationGetResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationGetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkAssociationGetResult] = kwargs.pop("cls", None) - - _request = build_private_link_association_list_request( - group_id=group_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkAssociationGetResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class ResourceManagementPrivateLinkOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.privatelinks.aio.ResourcePrivateLinkClient`'s - :attr:`resource_management_private_link` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def put( - self, - resource_group_name: str, - rmpl_name: str, - parameters: _models.ResourceManagementPrivateLinkLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Create a resource management group private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :param parameters: The region to create the Resource Management private link. Required. - :type parameters: - ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def put( - self, - resource_group_name: str, - rmpl_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Create a resource management group private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :param parameters: The region to create the Resource Management private link. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def put( - self, - resource_group_name: str, - rmpl_name: str, - parameters: Union[_models.ResourceManagementPrivateLinkLocation, IO[bytes]], - **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Create a resource management group private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :param parameters: The region to create the Resource Management private link. Is either a - ResourceManagementPrivateLinkLocation type or a IO[bytes] type. Required. - :type parameters: - ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation or IO[bytes] - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ResourceManagementPrivateLinkLocation") - - _request = build_resource_management_private_link_put_request( - resource_group_name=resource_group_name, - rmpl_name=rmpl_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, rmpl_name: str, **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Get a resource management private link(resource-level). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_get_request( - resource_group_name=resource_group_name, - rmpl_name=rmpl_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, resource_group_name: str, rmpl_name: str, **kwargs: Any) -> None: - """Delete a resource management private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_delete_request( - resource_group_name=resource_group_name, - rmpl_name=rmpl_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def list(self, **kwargs: Any) -> _models.ResourceManagementPrivateLinkListResult: - """Get all the resource management private links in a subscription. - - :return: ResourceManagementPrivateLinkListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> _models.ResourceManagementPrivateLinkListResult: - """Get all the resource management private links in a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: ResourceManagementPrivateLinkListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/__init__.py deleted file mode 100644 index f1a9ad64c7a5..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - ErrorAdditionalInfo, - ErrorResponse, - PrivateLinkAssociation, - PrivateLinkAssociationGetResult, - PrivateLinkAssociationObject, - PrivateLinkAssociationProperties, - PrivateLinkAssociationPropertiesExpanded, - ResourceManagementPrivateLink, - ResourceManagementPrivateLinkEndpointConnections, - ResourceManagementPrivateLinkListResult, - ResourceManagementPrivateLinkLocation, -) - -from ._resource_private_link_client_enums import ( # type: ignore - PublicNetworkAccessOptions, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ErrorAdditionalInfo", - "ErrorResponse", - "PrivateLinkAssociation", - "PrivateLinkAssociationGetResult", - "PrivateLinkAssociationObject", - "PrivateLinkAssociationProperties", - "PrivateLinkAssociationPropertiesExpanded", - "ResourceManagementPrivateLink", - "ResourceManagementPrivateLinkEndpointConnections", - "ResourceManagementPrivateLinkListResult", - "ResourceManagementPrivateLinkLocation", - "PublicNetworkAccessOptions", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_models_py3.py deleted file mode 100644 index 8a37e0dd1261..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_models_py3.py +++ /dev/null @@ -1,371 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.privatelinks.models.ErrorResponse] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.resource.privatelinks.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorResponse]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorResponse"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class PrivateLinkAssociation(_serialization.Model): - """PrivateLinkAssociation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar properties: The private link association properties. - :vartype properties: - ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationPropertiesExpanded - :ivar id: The plaResourceID. - :vartype id: str - :ivar type: The operation type. - :vartype type: str - :ivar name: The pla name. - :vartype name: str - """ - - _validation = { - "id": {"readonly": True}, - "type": {"readonly": True}, - "name": {"readonly": True}, - } - - _attribute_map = { - "properties": {"key": "properties", "type": "PrivateLinkAssociationPropertiesExpanded"}, - "id": {"key": "id", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - def __init__( - self, *, properties: Optional["_models.PrivateLinkAssociationPropertiesExpanded"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: The private link association properties. - :paramtype properties: - ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationPropertiesExpanded - """ - super().__init__(**kwargs) - self.properties = properties - self.id: Optional[str] = None - self.type: Optional[str] = None - self.name: Optional[str] = None - - -class PrivateLinkAssociationGetResult(_serialization.Model): - """Result of the request to get PLA for a MG scope. - - :ivar value: private link association information. - :vartype value: list[~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateLinkAssociation]"}, - } - - def __init__(self, *, value: Optional[list["_models.PrivateLinkAssociation"]] = None, **kwargs: Any) -> None: - """ - :keyword value: private link association information. - :paramtype value: list[~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation] - """ - super().__init__(**kwargs) - self.value = value - - -class PrivateLinkAssociationObject(_serialization.Model): - """PrivateLinkAssociationObject. - - :ivar properties: The properties of the PrivateLinkAssociation. - :vartype properties: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "PrivateLinkAssociationProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.PrivateLinkAssociationProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: The properties of the PrivateLinkAssociation. - :paramtype properties: - ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class PrivateLinkAssociationProperties(_serialization.Model): - """PrivateLinkAssociationProperties. - - :ivar private_link: The rmpl Resource ID. - :vartype private_link: str - :ivar public_network_access: Known values are: "Enabled" and "Disabled". - :vartype public_network_access: str or - ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions - """ - - _attribute_map = { - "private_link": {"key": "privateLink", "type": "str"}, - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - } - - def __init__( - self, - *, - private_link: Optional[str] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccessOptions"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword private_link: The rmpl Resource ID. - :paramtype private_link: str - :keyword public_network_access: Known values are: "Enabled" and "Disabled". - :paramtype public_network_access: str or - ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions - """ - super().__init__(**kwargs) - self.private_link = private_link - self.public_network_access = public_network_access - - -class PrivateLinkAssociationPropertiesExpanded(_serialization.Model): - """Private Link Association Properties. - - :ivar private_link: The rmpl Resource ID. - :vartype private_link: str - :ivar public_network_access: Known values are: "Enabled" and "Disabled". - :vartype public_network_access: str or - ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions - :ivar tenant_id: The TenantID. - :vartype tenant_id: str - :ivar scope: The scope of the private link association. - :vartype scope: str - """ - - _attribute_map = { - "private_link": {"key": "privateLink", "type": "str"}, - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - "tenant_id": {"key": "tenantID", "type": "str"}, - "scope": {"key": "scope", "type": "str"}, - } - - def __init__( - self, - *, - private_link: Optional[str] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccessOptions"]] = None, - tenant_id: Optional[str] = None, - scope: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword private_link: The rmpl Resource ID. - :paramtype private_link: str - :keyword public_network_access: Known values are: "Enabled" and "Disabled". - :paramtype public_network_access: str or - ~azure.mgmt.resource.privatelinks.models.PublicNetworkAccessOptions - :keyword tenant_id: The TenantID. - :paramtype tenant_id: str - :keyword scope: The scope of the private link association. - :paramtype scope: str - """ - super().__init__(**kwargs) - self.private_link = private_link - self.public_network_access = public_network_access - self.tenant_id = tenant_id - self.scope = scope - - -class ResourceManagementPrivateLink(_serialization.Model): - """ResourceManagementPrivateLink. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar properties: - :vartype properties: - ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkEndpointConnections - :ivar id: The rmplResourceID. - :vartype id: str - :ivar name: The rmpl Name. - :vartype name: str - :ivar type: The operation type. - :vartype type: str - :ivar location: the region of the rmpl. - :vartype location: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "properties": {"key": "properties", "type": "ResourceManagementPrivateLinkEndpointConnections"}, - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - } - - def __init__( - self, - *, - properties: Optional["_models.ResourceManagementPrivateLinkEndpointConnections"] = None, - location: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword properties: - :paramtype properties: - ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkEndpointConnections - :keyword location: the region of the rmpl. - :paramtype location: str - """ - super().__init__(**kwargs) - self.properties = properties - self.id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[str] = None - self.location = location - - -class ResourceManagementPrivateLinkEndpointConnections(_serialization.Model): # pylint: disable=name-too-long - """ResourceManagementPrivateLinkEndpointConnections. - - :ivar private_endpoint_connections: The private endpoint connections. - :vartype private_endpoint_connections: list[str] - """ - - _attribute_map = { - "private_endpoint_connections": {"key": "privateEndpointConnections", "type": "[str]"}, - } - - def __init__(self, *, private_endpoint_connections: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword private_endpoint_connections: The private endpoint connections. - :paramtype private_endpoint_connections: list[str] - """ - super().__init__(**kwargs) - self.private_endpoint_connections = private_endpoint_connections - - -class ResourceManagementPrivateLinkListResult(_serialization.Model): - """ResourceManagementPrivateLinkListResult. - - :ivar value: An array of resource management private links. - :vartype value: list[~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[ResourceManagementPrivateLink]"}, - } - - def __init__(self, *, value: Optional[list["_models.ResourceManagementPrivateLink"]] = None, **kwargs: Any) -> None: - """ - :keyword value: An array of resource management private links. - :paramtype value: list[~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink] - """ - super().__init__(**kwargs) - self.value = value - - -class ResourceManagementPrivateLinkLocation(_serialization.Model): - """ResourceManagementPrivateLinkLocation. - - :ivar location: the region to create private link association. - :vartype location: str - """ - - _attribute_map = { - "location": {"key": "location", "type": "str"}, - } - - def __init__(self, *, location: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword location: the region to create private link association. - :paramtype location: str - """ - super().__init__(**kwargs) - self.location = location diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py deleted file mode 100644 index bf713fd07ea6..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/models/_resource_private_link_client_enums.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class PublicNetworkAccessOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """PublicNetworkAccessOptions.""" - - ENABLED = "Enabled" - DISABLED = "Disabled" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/__init__.py deleted file mode 100644 index 39e87c00bee0..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import PrivateLinkAssociationOperations # type: ignore -from ._operations import ResourceManagementPrivateLinkOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "PrivateLinkAssociationOperations", - "ResourceManagementPrivateLinkOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_operations.py deleted file mode 100644 index d75648a21d51..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_operations.py +++ /dev/null @@ -1,985 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import ResourcePrivateLinkClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_private_link_association_put_request( # pylint: disable=name-too-long - group_id: str, pla_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations/{plaId}", - ) - path_format_arguments = { - "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), - "plaId": _SERIALIZER.url("pla_id", pla_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_private_link_association_get_request( # pylint: disable=name-too-long - group_id: str, pla_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations/{plaId}", - ) - path_format_arguments = { - "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), - "plaId": _SERIALIZER.url("pla_id", pla_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_private_link_association_delete_request( # pylint: disable=name-too-long - group_id: str, pla_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations/{plaId}", - ) - path_format_arguments = { - "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), - "plaId": _SERIALIZER.url("pla_id", pla_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_private_link_association_list_request( # pylint: disable=name-too-long - group_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Authorization/privateLinkAssociations", - ) - path_format_arguments = { - "groupId": _SERIALIZER.url("group_id", group_id, "str", max_length=90, min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_management_private_link_put_request( # pylint: disable=name-too-long - resource_group_name: str, rmpl_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks/{rmplName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "rmplName": _SERIALIZER.url("rmpl_name", rmpl_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_management_private_link_get_request( # pylint: disable=name-too-long - resource_group_name: str, rmpl_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks/{rmplName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "rmplName": _SERIALIZER.url("rmpl_name", rmpl_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_management_private_link_delete_request( # pylint: disable=name-too-long - resource_group_name: str, rmpl_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks/{rmplName}", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "rmplName": _SERIALIZER.url("rmpl_name", rmpl_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_management_private_link_list_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/resourceManagementPrivateLinks", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resource_management_private_link_list_by_resource_group_request( # pylint: disable=name-too-long - resource_group_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/resourceManagementPrivateLinks", - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PrivateLinkAssociationOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.privatelinks.ResourcePrivateLinkClient`'s - :attr:`private_link_association` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def put( - self, - group_id: str, - pla_id: str, - parameters: _models.PrivateLinkAssociationObject, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateLinkAssociation: - """Create a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :param parameters: Parameters supplied to create the private link association. Required. - :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def put( - self, - group_id: str, - pla_id: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateLinkAssociation: - """Create a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :param parameters: Parameters supplied to create the private link association. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def put( - self, - group_id: str, - pla_id: str, - parameters: Union[_models.PrivateLinkAssociationObject, IO[bytes]], - **kwargs: Any - ) -> _models.PrivateLinkAssociation: - """Create a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :param parameters: Parameters supplied to create the private link association. Is either a - PrivateLinkAssociationObject type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationObject or - IO[bytes] - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PrivateLinkAssociationObject") - - _request = build_private_link_association_put_request( - group_id=group_id, - pla_id=pla_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, group_id: str, pla_id: str, **kwargs: Any) -> _models.PrivateLinkAssociation: - """Get a single private link association. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :return: PrivateLinkAssociation or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociation - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkAssociation] = kwargs.pop("cls", None) - - _request = build_private_link_association_get_request( - group_id=group_id, - pla_id=pla_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkAssociation", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, group_id: str, pla_id: str, **kwargs: Any - ) -> None: - """Delete a PrivateLinkAssociation. - - :param group_id: The management group ID. Required. - :type group_id: str - :param pla_id: The ID of the PLA. Required. - :type pla_id: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_private_link_association_delete_request( - group_id=group_id, - pla_id=pla_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list(self, group_id: str, **kwargs: Any) -> _models.PrivateLinkAssociationGetResult: - """Get a private link association for a management group scope. - - :param group_id: The management group ID. Required. - :type group_id: str - :return: PrivateLinkAssociationGetResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.PrivateLinkAssociationGetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkAssociationGetResult] = kwargs.pop("cls", None) - - _request = build_private_link_association_list_request( - group_id=group_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkAssociationGetResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class ResourceManagementPrivateLinkOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.privatelinks.ResourcePrivateLinkClient`'s - :attr:`resource_management_private_link` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ResourcePrivateLinkClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def put( - self, - resource_group_name: str, - rmpl_name: str, - parameters: _models.ResourceManagementPrivateLinkLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Create a resource management group private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :param parameters: The region to create the Resource Management private link. Required. - :type parameters: - ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def put( - self, - resource_group_name: str, - rmpl_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Create a resource management group private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :param parameters: The region to create the Resource Management private link. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def put( - self, - resource_group_name: str, - rmpl_name: str, - parameters: Union[_models.ResourceManagementPrivateLinkLocation, IO[bytes]], - **kwargs: Any - ) -> _models.ResourceManagementPrivateLink: - """Create a resource management group private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :param parameters: The region to create the Resource Management private link. Is either a - ResourceManagementPrivateLinkLocation type or a IO[bytes] type. Required. - :type parameters: - ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkLocation or IO[bytes] - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ResourceManagementPrivateLinkLocation") - - _request = build_resource_management_private_link_put_request( - resource_group_name=resource_group_name, - rmpl_name=rmpl_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, resource_group_name: str, rmpl_name: str, **kwargs: Any) -> _models.ResourceManagementPrivateLink: - """Get a resource management private link(resource-level). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :return: ResourceManagementPrivateLink or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLink - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceManagementPrivateLink] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_get_request( - resource_group_name=resource_group_name, - rmpl_name=rmpl_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLink", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rmpl_name: str, **kwargs: Any - ) -> None: - """Delete a resource management private link. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param rmpl_name: The name of the resource management private link. Required. - :type rmpl_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_delete_request( - resource_group_name=resource_group_name, - rmpl_name=rmpl_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> _models.ResourceManagementPrivateLinkListResult: - """Get all the resource management private links in a subscription. - - :return: ResourceManagementPrivateLinkListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> _models.ResourceManagementPrivateLinkListResult: - """Get all the resource management private links in a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: ResourceManagementPrivateLinkListResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.privatelinks.models.ResourceManagementPrivateLinkListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ResourceManagementPrivateLinkListResult] = kwargs.pop("cls", None) - - _request = build_resource_management_private_link_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ResourceManagementPrivateLinkListResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/privatelinks/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_patch.py index 8bcb627aa475..2be8919280c2 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_patch.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_patch.py @@ -3,6 +3,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_resource_management_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_resource_management_client.py index 623158791f3a..8c44056c5a8c 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_resource_management_client.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_resource_management_client.py @@ -35,7 +35,7 @@ class ResourceManagementClient: - """Provides operations for working with resources and resource groups. + """ResourceManagement Client. :ivar operations: Operations operations :vartype operations: azure.mgmt.resource.resources.operations.Operations diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_version.py index fe295d036e47..e67545fce879 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_version.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_version.py @@ -5,4 +5,5 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "25.0.0b1" + +VERSION = "25.0.0" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_patch.py index 8bcb627aa475..2be8919280c2 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_patch.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_patch.py @@ -3,6 +3,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_resource_management_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_resource_management_client.py index 372dff878296..2c707cb24a6d 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_resource_management_client.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/_resource_management_client.py @@ -35,7 +35,7 @@ class ResourceManagementClient: - """Provides operations for working with resources and resource groups. + """ResourceManagement Client. :ivar operations: Operations operations :vartype operations: azure.mgmt.resource.resources.aio.operations.Operations diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/operations/_patch.py index 8bcb627aa475..2be8919280c2 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/operations/_patch.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/aio/operations/_patch.py @@ -3,6 +3,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/models/_patch.py index 8bcb627aa475..2be8919280c2 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/models/_patch.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/models/_patch.py @@ -3,6 +3,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/operations/_patch.py index 8bcb627aa475..2be8919280c2 100644 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/operations/_patch.py +++ b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/operations/_patch.py @@ -3,6 +3,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/__init__.py deleted file mode 100644 index 2ce2c3a5dd64..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._subscription_client import SubscriptionClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SubscriptionClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_configuration.py deleted file mode 100644 index abbc99125078..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_configuration.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class SubscriptionClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SubscriptionClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, credential: "TokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2022-12-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_subscription_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_subscription_client.py deleted file mode 100644 index 8872841d0d80..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_subscription_client.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.settings import settings -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from . import models as _models -from ._configuration import SubscriptionClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import Operations, SubscriptionsOperations, TenantsOperations, _SubscriptionClientOperationsMixin - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials import TokenCredential - - -class SubscriptionClient(_SubscriptionClientOperationsMixin): - """All resource groups and resources exist within subscriptions. These operation enable you get - information about your subscriptions and tenants. A tenant is a dedicated instance of Azure - Active Directory (Azure AD) for your organization. - - :ivar operations: Operations operations - :vartype operations: azure.mgmt.resource.subscriptions.operations.Operations - :ivar subscriptions: SubscriptionsOperations operations - :vartype subscriptions: azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations - :ivar tenants: TenantsOperations operations - :vartype tenants: azure.mgmt.resource.subscriptions.operations.TenantsOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "TokenCredential", - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = SubscriptionClientConfiguration( - credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.subscriptions = SubscriptionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.tenants = TenantsOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/__init__.py deleted file mode 100644 index 0af9b28f6607..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/serialization.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/serialization.py deleted file mode 100644 index 6da830e0cf4a..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/utils.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/utils.py deleted file mode 100644 index 39b612f39a9b..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_utils/utils.py +++ /dev/null @@ -1,25 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Generic, TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .serialization import Deserializer, Serializer - - -TClient = TypeVar("TClient") -TConfig = TypeVar("TConfig") - - -class ClientMixinABC(ABC, Generic[TClient, TConfig]): - """DO NOT use this class. It is for internal typing use only.""" - - _client: TClient - _config: TConfig - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_version.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_version.py deleted file mode 100644 index fe295d036e47..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_version.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -VERSION = "25.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/__init__.py deleted file mode 100644 index bb5ad1b4e042..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._subscription_client import SubscriptionClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SubscriptionClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_configuration.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_configuration.py deleted file mode 100644 index 20b07a4acaf0..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_configuration.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class SubscriptionClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SubscriptionClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :type cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, credential: "AsyncTokenCredential", cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2022-12-01") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - self.cloud_setting = cloud_setting - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_subscription_client.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_subscription_client.py deleted file mode 100644 index 76155b4948d3..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/_subscription_client.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.settings import settings -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from azure.mgmt.core.tools import get_arm_endpoints - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import SubscriptionClientConfiguration -from .operations import Operations, SubscriptionsOperations, TenantsOperations, _SubscriptionClientOperationsMixin - -if TYPE_CHECKING: - from azure.core import AzureClouds - from azure.core.credentials_async import AsyncTokenCredential - - -class SubscriptionClient(_SubscriptionClientOperationsMixin): - """All resource groups and resources exist within subscriptions. These operation enable you get - information about your subscriptions and tenants. A tenant is a dedicated instance of Azure - Active Directory (Azure AD) for your organization. - - :ivar operations: Operations operations - :vartype operations: azure.mgmt.resource.subscriptions.aio.operations.Operations - :ivar subscriptions: SubscriptionsOperations operations - :vartype subscriptions: - azure.mgmt.resource.subscriptions.aio.operations.SubscriptionsOperations - :ivar tenants: TenantsOperations operations - :vartype tenants: azure.mgmt.resource.subscriptions.aio.operations.TenantsOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param base_url: Service URL. Default value is None. - :type base_url: str - :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is - None. - :paramtype cloud_setting: ~azure.core.AzureClouds - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - base_url: Optional[str] = None, - *, - cloud_setting: Optional["AzureClouds"] = None, - **kwargs: Any - ) -> None: - _cloud = cloud_setting or settings.current.azure_cloud # type: ignore - _endpoints = get_arm_endpoints(_cloud) - if not base_url: - base_url = _endpoints["resource_manager"] - credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) - self._config = SubscriptionClientConfiguration( - credential=credential, cloud_setting=cloud_setting, credential_scopes=credential_scopes, **kwargs - ) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( - base_url=cast(str, base_url), policies=_policies, **kwargs - ) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.subscriptions = SubscriptionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.tenants = TenantsOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/__init__.py deleted file mode 100644 index d43f10f233ab..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import Operations # type: ignore -from ._operations import SubscriptionsOperations # type: ignore -from ._operations import TenantsOperations # type: ignore -from ._operations import _SubscriptionClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Operations", - "SubscriptionsOperations", - "TenantsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_operations.py deleted file mode 100644 index e89f7bbedb58..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_operations.py +++ /dev/null @@ -1,702 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ..._utils.utils import ClientMixinABC -from ...operations._operations import ( - build_operations_list_request, - build_subscription_check_resource_name_request, - build_subscriptions_check_zone_peers_request, - build_subscriptions_get_request, - build_subscriptions_list_locations_request, - build_subscriptions_list_request, - build_tenants_list_request, -) -from .._configuration import SubscriptionClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class Operations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.subscriptions.aio.SubscriptionClient`'s - :attr:`operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Resources REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_operations_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class SubscriptionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.subscriptions.aio.SubscriptionClient`'s - :attr:`subscriptions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_locations( - self, subscription_id: str, include_extended_locations: Optional[bool] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.Location"]: - """Gets all available geo-locations. - - This operation provides all the locations that are available for resource providers; however, - each resource provider may support a subset of this list. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param include_extended_locations: Whether to include extended locations. Default value is - None. - :type include_extended_locations: bool - :return: An iterator like instance of either Location or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.Location] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscriptions_list_locations_request( - subscription_id=subscription_id, - include_extended_locations=include_extended_locations, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("LocationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: - """Gets details about a specified subscription. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :return: Subscription or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.Subscription - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) - - _request = build_subscriptions_get_request( - subscription_id=subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Subscription", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Subscription"]: - """Gets all subscriptions for a tenant. - - :return: An iterator like instance of either Subscription or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.Subscription] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscriptions_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SubscriptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def check_zone_peers( - self, - subscription_id: str, - parameters: _models.CheckZonePeersRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CheckZonePeersResult: - """Compares a subscriptions logical zone mapping. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param parameters: Parameters for checking zone peers. Required. - :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckZonePeersResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def check_zone_peers( - self, subscription_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CheckZonePeersResult: - """Compares a subscriptions logical zone mapping. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param parameters: Parameters for checking zone peers. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckZonePeersResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def check_zone_peers( - self, subscription_id: str, parameters: Union[_models.CheckZonePeersRequest, IO[bytes]], **kwargs: Any - ) -> _models.CheckZonePeersResult: - """Compares a subscriptions logical zone mapping. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param parameters: Parameters for checking zone peers. Is either a CheckZonePeersRequest type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest or IO[bytes] - :return: CheckZonePeersResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CheckZonePeersResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "CheckZonePeersRequest") - - _request = build_subscriptions_check_zone_peers_request( - subscription_id=subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponseAutoGenerated, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CheckZonePeersResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class TenantsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.subscriptions.aio.SubscriptionClient`'s - :attr:`tenants` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.TenantIdDescription"]: - """Gets the tenants for your account. - - :return: An iterator like instance of either TenantIdDescription or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TenantListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_tenants_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("TenantListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class _SubscriptionClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SubscriptionClientConfiguration] -): - - @overload - async def check_resource_name( - self, - resource_name_definition: Optional[_models.ResourceName] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CheckResourceNameResult: - """Checks resource name validity. - - A resource name is valid if it is not a reserved word, does not contains a reserved word and - does not start with a reserved word. - - :param resource_name_definition: Resource object with values for resource name and resource - type. Default value is None. - :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckResourceNameResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def check_resource_name( - self, - resource_name_definition: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CheckResourceNameResult: - """Checks resource name validity. - - A resource name is valid if it is not a reserved word, does not contains a reserved word and - does not start with a reserved word. - - :param resource_name_definition: Resource object with values for resource name and resource - type. Default value is None. - :type resource_name_definition: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckResourceNameResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def check_resource_name( - self, resource_name_definition: Optional[Union[_models.ResourceName, IO[bytes]]] = None, **kwargs: Any - ) -> _models.CheckResourceNameResult: - """Checks resource name validity. - - A resource name is valid if it is not a reserved word, does not contains a reserved word and - does not start with a reserved word. - - :param resource_name_definition: Resource object with values for resource name and resource - type. Is either a ResourceName type or a IO[bytes] type. Default value is None. - :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName or - IO[bytes] - :return: CheckResourceNameResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if resource_name_definition else None - cls: ClsType[_models.CheckResourceNameResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if resource_name_definition else None - _json = None - _content = None - if isinstance(resource_name_definition, (IOBase, bytes)): - _content = resource_name_definition - else: - if resource_name_definition is not None: - _json = self._serialize.body(resource_name_definition, "ResourceName") - else: - _json = None - - _request = build_subscription_check_resource_name_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CheckResourceNameResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/__init__.py deleted file mode 100644 index 58d161b82e76..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/__init__.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AvailabilityZoneMappings, - AvailabilityZonePeers, - CheckResourceNameResult, - CheckZonePeersRequest, - CheckZonePeersResult, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - ErrorResponseAutoGenerated, - Location, - LocationListResult, - LocationMetadata, - ManagedByTenant, - Operation, - OperationAutoGenerated, - OperationDisplay, - OperationDisplayAutoGenerated, - OperationListResult, - OperationListResultAutoGenerated, - PairedRegion, - Peers, - ResourceName, - Subscription, - SubscriptionListResult, - SubscriptionPolicies, - TenantIdDescription, - TenantListResult, -) - -from ._subscription_client_enums import ( # type: ignore - ActionType, - LocationType, - Origin, - RegionCategory, - RegionType, - ResourceNameStatus, - SpendingLimit, - SubscriptionState, - TenantCategory, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AvailabilityZoneMappings", - "AvailabilityZonePeers", - "CheckResourceNameResult", - "CheckZonePeersRequest", - "CheckZonePeersResult", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "ErrorResponseAutoGenerated", - "Location", - "LocationListResult", - "LocationMetadata", - "ManagedByTenant", - "Operation", - "OperationAutoGenerated", - "OperationDisplay", - "OperationDisplayAutoGenerated", - "OperationListResult", - "OperationListResultAutoGenerated", - "PairedRegion", - "Peers", - "ResourceName", - "Subscription", - "SubscriptionListResult", - "SubscriptionPolicies", - "TenantIdDescription", - "TenantListResult", - "ActionType", - "LocationType", - "Origin", - "RegionCategory", - "RegionType", - "ResourceNameStatus", - "SpendingLimit", - "SubscriptionState", - "TenantCategory", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_models_py3.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_models_py3.py deleted file mode 100644 index 15679dba0bee..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_models_py3.py +++ /dev/null @@ -1,1112 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class AvailabilityZoneMappings(_serialization.Model): - """Availability zone mappings for the region. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar logical_zone: The logical zone id for the availability zone. - :vartype logical_zone: str - :ivar physical_zone: The fully qualified physical zone id of availability zone to which logical - zone id is mapped to. - :vartype physical_zone: str - """ - - _validation = { - "logical_zone": {"readonly": True}, - "physical_zone": {"readonly": True}, - } - - _attribute_map = { - "logical_zone": {"key": "logicalZone", "type": "str"}, - "physical_zone": {"key": "physicalZone", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.logical_zone: Optional[str] = None - self.physical_zone: Optional[str] = None - - -class AvailabilityZonePeers(_serialization.Model): - """List of availability zones shared by the subscriptions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar availability_zone: The availabilityZone. - :vartype availability_zone: str - :ivar peers: Details of shared availability zone. - :vartype peers: list[~azure.mgmt.resource.subscriptions.models.Peers] - """ - - _validation = { - "availability_zone": {"readonly": True}, - } - - _attribute_map = { - "availability_zone": {"key": "availabilityZone", "type": "str"}, - "peers": {"key": "peers", "type": "[Peers]"}, - } - - def __init__(self, *, peers: Optional[list["_models.Peers"]] = None, **kwargs: Any) -> None: - """ - :keyword peers: Details of shared availability zone. - :paramtype peers: list[~azure.mgmt.resource.subscriptions.models.Peers] - """ - super().__init__(**kwargs) - self.availability_zone: Optional[str] = None - self.peers = peers - - -class CheckResourceNameResult(_serialization.Model): - """Resource Name valid if not a reserved word, does not contain a reserved word and does not start - with a reserved word. - - :ivar name: Name of Resource. - :vartype name: str - :ivar type: Type of Resource. - :vartype type: str - :ivar status: Is the resource name Allowed or Reserved. Known values are: "Allowed" and - "Reserved". - :vartype status: str or ~azure.mgmt.resource.subscriptions.models.ResourceNameStatus - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "status": {"key": "status", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - type: Optional[str] = None, - status: Optional[Union[str, "_models.ResourceNameStatus"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Name of Resource. - :paramtype name: str - :keyword type: Type of Resource. - :paramtype type: str - :keyword status: Is the resource name Allowed or Reserved. Known values are: "Allowed" and - "Reserved". - :paramtype status: str or ~azure.mgmt.resource.subscriptions.models.ResourceNameStatus - """ - super().__init__(**kwargs) - self.name = name - self.type = type - self.status = status - - -class CheckZonePeersRequest(_serialization.Model): - """Check zone peers request parameters. - - :ivar location: The Microsoft location. - :vartype location: str - :ivar subscription_ids: The peer Microsoft Azure subscription ID. - :vartype subscription_ids: list[str] - """ - - _attribute_map = { - "location": {"key": "location", "type": "str"}, - "subscription_ids": {"key": "subscriptionIds", "type": "[str]"}, - } - - def __init__( - self, *, location: Optional[str] = None, subscription_ids: Optional[list[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword location: The Microsoft location. - :paramtype location: str - :keyword subscription_ids: The peer Microsoft Azure subscription ID. - :paramtype subscription_ids: list[str] - """ - super().__init__(**kwargs) - self.location = location - self.subscription_ids = subscription_ids - - -class CheckZonePeersResult(_serialization.Model): - """Result of the Check zone peers operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar subscription_id: The subscription ID. - :vartype subscription_id: str - :ivar location: the location of the subscription. - :vartype location: str - :ivar availability_zone_peers: The Availability Zones shared by the subscriptions. - :vartype availability_zone_peers: - list[~azure.mgmt.resource.subscriptions.models.AvailabilityZonePeers] - """ - - _validation = { - "subscription_id": {"readonly": True}, - } - - _attribute_map = { - "subscription_id": {"key": "subscriptionId", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "availability_zone_peers": {"key": "availabilityZonePeers", "type": "[AvailabilityZonePeers]"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - availability_zone_peers: Optional[list["_models.AvailabilityZonePeers"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: the location of the subscription. - :paramtype location: str - :keyword availability_zone_peers: The Availability Zones shared by the subscriptions. - :paramtype availability_zone_peers: - list[~azure.mgmt.resource.subscriptions.models.AvailabilityZonePeers] - """ - super().__init__(**kwargs) - self.subscription_id: Optional[str] = None - self.location = location - self.availability_zone_peers = availability_zone_peers - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.subscriptions.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.resource.subscriptions.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.resource.subscriptions.models.ErrorResponse] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.resource.subscriptions.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorResponse]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorResponse"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponseAutoGenerated(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.resource.subscriptions.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.resource.subscriptions.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class Location(_serialization.Model): - """Location information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The fully qualified ID of the location. For example, - /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - :vartype id: str - :ivar subscription_id: The subscription ID. - :vartype subscription_id: str - :ivar name: The location name. - :vartype name: str - :ivar type: The location type. Known values are: "Region" and "EdgeZone". - :vartype type: str or ~azure.mgmt.resource.subscriptions.models.LocationType - :ivar display_name: The display name of the location. - :vartype display_name: str - :ivar regional_display_name: The display name of the location and its region. - :vartype regional_display_name: str - :ivar metadata: Metadata of the location, such as lat/long, paired region, and others. - :vartype metadata: ~azure.mgmt.resource.subscriptions.models.LocationMetadata - :ivar availability_zone_mappings: The availability zone mappings for this region. - :vartype availability_zone_mappings: - list[~azure.mgmt.resource.subscriptions.models.AvailabilityZoneMappings] - """ - - _validation = { - "id": {"readonly": True}, - "subscription_id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "display_name": {"readonly": True}, - "regional_display_name": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "subscription_id": {"key": "subscriptionId", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - "regional_display_name": {"key": "regionalDisplayName", "type": "str"}, - "metadata": {"key": "metadata", "type": "LocationMetadata"}, - "availability_zone_mappings": {"key": "availabilityZoneMappings", "type": "[AvailabilityZoneMappings]"}, - } - - def __init__( - self, - *, - metadata: Optional["_models.LocationMetadata"] = None, - availability_zone_mappings: Optional[list["_models.AvailabilityZoneMappings"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword metadata: Metadata of the location, such as lat/long, paired region, and others. - :paramtype metadata: ~azure.mgmt.resource.subscriptions.models.LocationMetadata - :keyword availability_zone_mappings: The availability zone mappings for this region. - :paramtype availability_zone_mappings: - list[~azure.mgmt.resource.subscriptions.models.AvailabilityZoneMappings] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.subscription_id: Optional[str] = None - self.name: Optional[str] = None - self.type: Optional[Union[str, "_models.LocationType"]] = None - self.display_name: Optional[str] = None - self.regional_display_name: Optional[str] = None - self.metadata = metadata - self.availability_zone_mappings = availability_zone_mappings - - -class LocationListResult(_serialization.Model): - """Location list operation response. - - :ivar value: An array of locations. - :vartype value: list[~azure.mgmt.resource.subscriptions.models.Location] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[Location]"}, - } - - def __init__(self, *, value: Optional[list["_models.Location"]] = None, **kwargs: Any) -> None: - """ - :keyword value: An array of locations. - :paramtype value: list[~azure.mgmt.resource.subscriptions.models.Location] - """ - super().__init__(**kwargs) - self.value = value - - -class LocationMetadata(_serialization.Model): - """Location metadata information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar region_type: The type of the region. Known values are: "Physical" and "Logical". - :vartype region_type: str or ~azure.mgmt.resource.subscriptions.models.RegionType - :ivar region_category: The category of the region. Known values are: "Recommended", "Extended", - and "Other". - :vartype region_category: str or ~azure.mgmt.resource.subscriptions.models.RegionCategory - :ivar geography: The geography of the location. - :vartype geography: str - :ivar geography_group: The geography group of the location. - :vartype geography_group: str - :ivar longitude: The longitude of the location. - :vartype longitude: str - :ivar latitude: The latitude of the location. - :vartype latitude: str - :ivar physical_location: The physical location of the Azure location. - :vartype physical_location: str - :ivar paired_region: The regions paired to this region. - :vartype paired_region: list[~azure.mgmt.resource.subscriptions.models.PairedRegion] - :ivar home_location: The home location of an edge zone. - :vartype home_location: str - """ - - _validation = { - "region_type": {"readonly": True}, - "region_category": {"readonly": True}, - "geography": {"readonly": True}, - "geography_group": {"readonly": True}, - "longitude": {"readonly": True}, - "latitude": {"readonly": True}, - "physical_location": {"readonly": True}, - "home_location": {"readonly": True}, - } - - _attribute_map = { - "region_type": {"key": "regionType", "type": "str"}, - "region_category": {"key": "regionCategory", "type": "str"}, - "geography": {"key": "geography", "type": "str"}, - "geography_group": {"key": "geographyGroup", "type": "str"}, - "longitude": {"key": "longitude", "type": "str"}, - "latitude": {"key": "latitude", "type": "str"}, - "physical_location": {"key": "physicalLocation", "type": "str"}, - "paired_region": {"key": "pairedRegion", "type": "[PairedRegion]"}, - "home_location": {"key": "homeLocation", "type": "str"}, - } - - def __init__(self, *, paired_region: Optional[list["_models.PairedRegion"]] = None, **kwargs: Any) -> None: - """ - :keyword paired_region: The regions paired to this region. - :paramtype paired_region: list[~azure.mgmt.resource.subscriptions.models.PairedRegion] - """ - super().__init__(**kwargs) - self.region_type: Optional[Union[str, "_models.RegionType"]] = None - self.region_category: Optional[Union[str, "_models.RegionCategory"]] = None - self.geography: Optional[str] = None - self.geography_group: Optional[str] = None - self.longitude: Optional[str] = None - self.latitude: Optional[str] = None - self.physical_location: Optional[str] = None - self.paired_region = paired_region - self.home_location: Optional[str] = None - - -class ManagedByTenant(_serialization.Model): - """Information about a tenant managing the subscription. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar tenant_id: The tenant ID of the managing tenant. This is a GUID. - :vartype tenant_id: str - """ - - _validation = { - "tenant_id": {"readonly": True}, - } - - _attribute_map = { - "tenant_id": {"key": "tenantId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.tenant_id: Optional[str] = None - - -class Operation(_serialization.Model): - """Details of a REST API operation, returned from the Resource Provider Operations API. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: - "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". - :vartype name: str - :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for - data-plane operations and "false" for ARM/control-plane operations. - :vartype is_data_action: bool - :ivar display: Localized display information for this particular operation. - :vartype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplay - :ivar origin: The intended executor of the operation; as in Resource Based Access Control - (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", - and "user,system". - :vartype origin: str or ~azure.mgmt.resource.subscriptions.models.Origin - :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for - internal only APIs. "Internal" - :vartype action_type: str or ~azure.mgmt.resource.subscriptions.models.ActionType - """ - - _validation = { - "name": {"readonly": True}, - "is_data_action": {"readonly": True}, - "origin": {"readonly": True}, - "action_type": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "is_data_action": {"key": "isDataAction", "type": "bool"}, - "display": {"key": "display", "type": "OperationDisplay"}, - "origin": {"key": "origin", "type": "str"}, - "action_type": {"key": "actionType", "type": "str"}, - } - - def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: - """ - :keyword display: Localized display information for this particular operation. - :paramtype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.is_data_action: Optional[bool] = None - self.display = display - self.origin: Optional[Union[str, "_models.Origin"]] = None - self.action_type: Optional[Union[str, "_models.ActionType"]] = None - - -class OperationAutoGenerated(_serialization.Model): - """Details of a REST API operation, returned from the Resource Provider Operations API. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for - data-plane operations and "false" for ARM/control-plane operations. - :vartype is_data_action: bool - :ivar display: Localized display information for this particular operation. - :vartype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplayAutoGenerated - :ivar origin: The intended executor of the operation; as in Resource Based Access Control - (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", - and "user,system". - :vartype origin: str or ~azure.mgmt.resource.subscriptions.models.Origin - :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for - internal only APIs. "Internal" - :vartype action_type: str or ~azure.mgmt.resource.subscriptions.models.ActionType - """ - - _validation = { - "is_data_action": {"readonly": True}, - "origin": {"readonly": True}, - "action_type": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "is_data_action": {"key": "isDataAction", "type": "bool"}, - "display": {"key": "display", "type": "OperationDisplayAutoGenerated"}, - "origin": {"key": "origin", "type": "str"}, - "action_type": {"key": "actionType", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - display: Optional["_models.OperationDisplayAutoGenerated"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: Localized display information for this particular operation. - :paramtype display: ~azure.mgmt.resource.subscriptions.models.OperationDisplayAutoGenerated - """ - super().__init__(**kwargs) - self.name = name - self.is_data_action: Optional[bool] = None - self.display = display - self.origin: Optional[Union[str, "_models.Origin"]] = None - self.action_type: Optional[Union[str, "_models.ActionType"]] = None - - -class OperationDisplay(_serialization.Model): - """Localized display information for this particular operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft - Monitoring Insights" or "Microsoft Compute". - :vartype provider: str - :ivar resource: The localized friendly name of the resource type related to this operation. - E.g. "Virtual Machines" or "Job Schedule Collections". - :vartype resource: str - :ivar operation: The concise, localized friendly name for the operation; suitable for - dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". - :vartype operation: str - :ivar description: The short, localized friendly description of the operation; suitable for - tool tips and detailed views. - :vartype description: str - """ - - _validation = { - "provider": {"readonly": True}, - "resource": {"readonly": True}, - "operation": {"readonly": True}, - "description": {"readonly": True}, - } - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.provider: Optional[str] = None - self.resource: Optional[str] = None - self.operation: Optional[str] = None - self.description: Optional[str] = None - - -class OperationDisplayAutoGenerated(_serialization.Model): - """Localized display information for this particular operation. - - :ivar provider: Service provider: Microsoft.Resources. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - :ivar description: Description of the operation. - :vartype description: str - """ - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Service provider: Microsoft.Resources. - :paramtype provider: str - :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. - :paramtype resource: str - :keyword operation: Operation type: Read, write, delete, etc. - :paramtype operation: str - :keyword description: Description of the operation. - :paramtype description: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - self.description = description - - -class OperationListResult(_serialization.Model): - """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link - to get the next set of results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of operations supported by the resource provider. - :vartype value: list[~azure.mgmt.resource.subscriptions.models.Operation] - :ivar next_link: URL to get the next set of operation list results (if there are any). - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value: Optional[list["_models.Operation"]] = None - self.next_link: Optional[str] = None - - -class OperationListResultAutoGenerated(_serialization.Model): - """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link - to get the next set of results. - - :ivar value: List of operations supported by the resource provider. - :vartype value: list[~azure.mgmt.resource.subscriptions.models.OperationAutoGenerated] - :ivar next_link: URL to get the next set of operation list results (if there are any). - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[OperationAutoGenerated]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[list["_models.OperationAutoGenerated"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: List of operations supported by the resource provider. - :paramtype value: list[~azure.mgmt.resource.subscriptions.models.OperationAutoGenerated] - :keyword next_link: URL to get the next set of operation list results (if there are any). - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PairedRegion(_serialization.Model): - """Information regarding paired region. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the paired region. - :vartype name: str - :ivar id: The fully qualified ID of the location. For example, - /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - :vartype id: str - :ivar subscription_id: The subscription ID. - :vartype subscription_id: str - """ - - _validation = { - "name": {"readonly": True}, - "id": {"readonly": True}, - "subscription_id": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "subscription_id": {"key": "subscriptionId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.id: Optional[str] = None - self.subscription_id: Optional[str] = None - - -class Peers(_serialization.Model): - """Information about shared availability zone. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar subscription_id: The subscription ID. - :vartype subscription_id: str - :ivar availability_zone: The availabilityZone. - :vartype availability_zone: str - """ - - _validation = { - "subscription_id": {"readonly": True}, - "availability_zone": {"readonly": True}, - } - - _attribute_map = { - "subscription_id": {"key": "subscriptionId", "type": "str"}, - "availability_zone": {"key": "availabilityZone", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.subscription_id: Optional[str] = None - self.availability_zone: Optional[str] = None - - -class ResourceName(_serialization.Model): - """Name and Type of the Resource. - - All required parameters must be populated in order to send to server. - - :ivar name: Name of the resource. Required. - :vartype name: str - :ivar type: The type of the resource. Required. - :vartype type: str - """ - - _validation = { - "name": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, name: str, type: str, **kwargs: Any) -> None: - """ - :keyword name: Name of the resource. Required. - :paramtype name: str - :keyword type: The type of the resource. Required. - :paramtype type: str - """ - super().__init__(**kwargs) - self.name = name - self.type = type - - -class Subscription(_serialization.Model): - """Subscription information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The fully qualified ID for the subscription. For example, - /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74. - :vartype id: str - :ivar subscription_id: The subscription ID. - :vartype subscription_id: str - :ivar display_name: The subscription display name. - :vartype display_name: str - :ivar tenant_id: The subscription tenant ID. - :vartype tenant_id: str - :ivar state: The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, - and Deleted. Known values are: "Enabled", "Warned", "PastDue", "Disabled", and "Deleted". - :vartype state: str or ~azure.mgmt.resource.subscriptions.models.SubscriptionState - :ivar subscription_policies: The subscription policies. - :vartype subscription_policies: ~azure.mgmt.resource.subscriptions.models.SubscriptionPolicies - :ivar authorization_source: The authorization source of the request. Valid values are one or - more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, - RoleBased'. - :vartype authorization_source: str - :ivar managed_by_tenants: An array containing the tenants managing the subscription. - :vartype managed_by_tenants: list[~azure.mgmt.resource.subscriptions.models.ManagedByTenant] - :ivar tags: The tags attached to the subscription. - :vartype tags: dict[str, str] - """ - - _validation = { - "id": {"readonly": True}, - "subscription_id": {"readonly": True}, - "display_name": {"readonly": True}, - "tenant_id": {"readonly": True}, - "state": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "subscription_id": {"key": "subscriptionId", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "state": {"key": "state", "type": "str"}, - "subscription_policies": {"key": "subscriptionPolicies", "type": "SubscriptionPolicies"}, - "authorization_source": {"key": "authorizationSource", "type": "str"}, - "managed_by_tenants": {"key": "managedByTenants", "type": "[ManagedByTenant]"}, - "tags": {"key": "tags", "type": "{str}"}, - } - - def __init__( - self, - *, - subscription_policies: Optional["_models.SubscriptionPolicies"] = None, - authorization_source: Optional[str] = None, - managed_by_tenants: Optional[list["_models.ManagedByTenant"]] = None, - tags: Optional[dict[str, str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword subscription_policies: The subscription policies. - :paramtype subscription_policies: - ~azure.mgmt.resource.subscriptions.models.SubscriptionPolicies - :keyword authorization_source: The authorization source of the request. Valid values are one or - more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, - RoleBased'. - :paramtype authorization_source: str - :keyword managed_by_tenants: An array containing the tenants managing the subscription. - :paramtype managed_by_tenants: list[~azure.mgmt.resource.subscriptions.models.ManagedByTenant] - :keyword tags: The tags attached to the subscription. - :paramtype tags: dict[str, str] - """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.subscription_id: Optional[str] = None - self.display_name: Optional[str] = None - self.tenant_id: Optional[str] = None - self.state: Optional[Union[str, "_models.SubscriptionState"]] = None - self.subscription_policies = subscription_policies - self.authorization_source = authorization_source - self.managed_by_tenants = managed_by_tenants - self.tags = tags - - -class SubscriptionListResult(_serialization.Model): - """Subscription list operation response. - - All required parameters must be populated in order to send to server. - - :ivar value: An array of subscriptions. - :vartype value: list[~azure.mgmt.resource.subscriptions.models.Subscription] - :ivar next_link: The URL to get the next set of results. Required. - :vartype next_link: str - """ - - _validation = { - "next_link": {"required": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Subscription]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, next_link: str, value: Optional[list["_models.Subscription"]] = None, **kwargs: Any) -> None: - """ - :keyword value: An array of subscriptions. - :paramtype value: list[~azure.mgmt.resource.subscriptions.models.Subscription] - :keyword next_link: The URL to get the next set of results. Required. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class SubscriptionPolicies(_serialization.Model): - """Subscription policies. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar location_placement_id: The subscription location placement ID. The ID indicates which - regions are visible for a subscription. For example, a subscription with a location placement - Id of Public_2014-09-01 has access to Azure public regions. - :vartype location_placement_id: str - :ivar quota_id: The subscription quota ID. - :vartype quota_id: str - :ivar spending_limit: The subscription spending limit. Known values are: "On", "Off", and - "CurrentPeriodOff". - :vartype spending_limit: str or ~azure.mgmt.resource.subscriptions.models.SpendingLimit - """ - - _validation = { - "location_placement_id": {"readonly": True}, - "quota_id": {"readonly": True}, - "spending_limit": {"readonly": True}, - } - - _attribute_map = { - "location_placement_id": {"key": "locationPlacementId", "type": "str"}, - "quota_id": {"key": "quotaId", "type": "str"}, - "spending_limit": {"key": "spendingLimit", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.location_placement_id: Optional[str] = None - self.quota_id: Optional[str] = None - self.spending_limit: Optional[Union[str, "_models.SpendingLimit"]] = None - - -class TenantIdDescription(_serialization.Model): - """Tenant Id information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The fully qualified ID of the tenant. For example, - /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - :vartype id: str - :ivar tenant_id: The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - :vartype tenant_id: str - :ivar tenant_category: Category of the tenant. Known values are: "Home", "ProjectedBy", and - "ManagedBy". - :vartype tenant_category: str or ~azure.mgmt.resource.subscriptions.models.TenantCategory - :ivar country: Country/region name of the address for the tenant. - :vartype country: str - :ivar country_code: Country/region abbreviation for the tenant. - :vartype country_code: str - :ivar display_name: The display name of the tenant. - :vartype display_name: str - :ivar domains: The list of domains for the tenant. - :vartype domains: list[str] - :ivar default_domain: The default domain for the tenant. - :vartype default_domain: str - :ivar tenant_type: The tenant type. Only available for 'Home' tenant category. - :vartype tenant_type: str - :ivar tenant_branding_logo_url: The tenant's branding logo URL. Only available for 'Home' - tenant category. - :vartype tenant_branding_logo_url: str - """ - - _validation = { - "id": {"readonly": True}, - "tenant_id": {"readonly": True}, - "tenant_category": {"readonly": True}, - "country": {"readonly": True}, - "country_code": {"readonly": True}, - "display_name": {"readonly": True}, - "domains": {"readonly": True}, - "default_domain": {"readonly": True}, - "tenant_type": {"readonly": True}, - "tenant_branding_logo_url": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "tenant_category": {"key": "tenantCategory", "type": "str"}, - "country": {"key": "country", "type": "str"}, - "country_code": {"key": "countryCode", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - "domains": {"key": "domains", "type": "[str]"}, - "default_domain": {"key": "defaultDomain", "type": "str"}, - "tenant_type": {"key": "tenantType", "type": "str"}, - "tenant_branding_logo_url": {"key": "tenantBrandingLogoUrl", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id: Optional[str] = None - self.tenant_id: Optional[str] = None - self.tenant_category: Optional[Union[str, "_models.TenantCategory"]] = None - self.country: Optional[str] = None - self.country_code: Optional[str] = None - self.display_name: Optional[str] = None - self.domains: Optional[list[str]] = None - self.default_domain: Optional[str] = None - self.tenant_type: Optional[str] = None - self.tenant_branding_logo_url: Optional[str] = None - - -class TenantListResult(_serialization.Model): - """Tenant Ids information. - - All required parameters must be populated in order to send to server. - - :ivar value: An array of tenants. - :vartype value: list[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] - :ivar next_link: The URL to use for getting the next set of results. Required. - :vartype next_link: str - """ - - _validation = { - "next_link": {"required": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[TenantIdDescription]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, next_link: str, value: Optional[list["_models.TenantIdDescription"]] = None, **kwargs: Any - ) -> None: - """ - :keyword value: An array of tenants. - :paramtype value: list[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] - :keyword next_link: The URL to use for getting the next set of results. Required. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py deleted file mode 100644 index 610e41a85c9f..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/models/_subscription_client_enums.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" - - INTERNAL = "Internal" - - -class LocationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The location type.""" - - REGION = "Region" - EDGE_ZONE = "EdgeZone" - - -class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit - logs UX. Default value is "user,system". - """ - - USER = "user" - SYSTEM = "system" - USER_SYSTEM = "user,system" - - -class RegionCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The category of the region.""" - - RECOMMENDED = "Recommended" - EXTENDED = "Extended" - OTHER = "Other" - - -class RegionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of the region.""" - - PHYSICAL = "Physical" - LOGICAL = "Logical" - - -class ResourceNameStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Is the resource name Allowed or Reserved.""" - - ALLOWED = "Allowed" - RESERVED = "Reserved" - - -class SpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The subscription spending limit.""" - - ON = "On" - OFF = "Off" - CURRENT_PERIOD_OFF = "CurrentPeriodOff" - - -class SubscriptionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted.""" - - ENABLED = "Enabled" - WARNED = "Warned" - PAST_DUE = "PastDue" - DISABLED = "Disabled" - DELETED = "Deleted" - - -class TenantCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Category of the tenant.""" - - HOME = "Home" - PROJECTED_BY = "ProjectedBy" - MANAGED_BY = "ManagedBy" diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/__init__.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/__init__.py deleted file mode 100644 index d43f10f233ab..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import Operations # type: ignore -from ._operations import SubscriptionsOperations # type: ignore -from ._operations import TenantsOperations # type: ignore -from ._operations import _SubscriptionClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Operations", - "SubscriptionsOperations", - "TenantsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_operations.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_operations.py deleted file mode 100644 index b5675187f526..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_operations.py +++ /dev/null @@ -1,853 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._configuration import SubscriptionClientConfiguration -from .._utils.serialization import Deserializer, Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_operations_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscriptions_list_locations_request( # pylint: disable=name-too-long - subscription_id: str, *, include_extended_locations: Optional[bool] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/locations") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if include_extended_locations is not None: - _params["includeExtendedLocations"] = _SERIALIZER.query( - "include_extended_locations", include_extended_locations, "bool" - ) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscriptions_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscriptions_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscriptions_check_zone_peers_request( # pylint: disable=name-too-long - subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/checkZonePeers/") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_tenants_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/tenants") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_subscription_check_resource_name_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/checkResourceName") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class Operations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.subscriptions.SubscriptionClient`'s - :attr:`operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: - """Lists all of the available Microsoft.Resources REST API operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_operations_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class SubscriptionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.subscriptions.SubscriptionClient`'s - :attr:`subscriptions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_locations( - self, subscription_id: str, include_extended_locations: Optional[bool] = None, **kwargs: Any - ) -> ItemPaged["_models.Location"]: - """Gets all available geo-locations. - - This operation provides all the locations that are available for resource providers; however, - each resource provider may support a subset of this list. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param include_extended_locations: Whether to include extended locations. Default value is - None. - :type include_extended_locations: bool - :return: An iterator like instance of either Location or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.Location] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscriptions_list_locations_request( - subscription_id=subscription_id, - include_extended_locations=include_extended_locations, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("LocationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: - """Gets details about a specified subscription. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :return: Subscription or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.Subscription - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) - - _request = build_subscriptions_get_request( - subscription_id=subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Subscription", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.Subscription"]: - """Gets all subscriptions for a tenant. - - :return: An iterator like instance of either Subscription or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.Subscription] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SubscriptionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_subscriptions_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SubscriptionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def check_zone_peers( - self, - subscription_id: str, - parameters: _models.CheckZonePeersRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CheckZonePeersResult: - """Compares a subscriptions logical zone mapping. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param parameters: Parameters for checking zone peers. Required. - :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckZonePeersResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def check_zone_peers( - self, subscription_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CheckZonePeersResult: - """Compares a subscriptions logical zone mapping. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param parameters: Parameters for checking zone peers. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckZonePeersResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def check_zone_peers( - self, subscription_id: str, parameters: Union[_models.CheckZonePeersRequest, IO[bytes]], **kwargs: Any - ) -> _models.CheckZonePeersResult: - """Compares a subscriptions logical zone mapping. - - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param parameters: Parameters for checking zone peers. Is either a CheckZonePeersRequest type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersRequest or IO[bytes] - :return: CheckZonePeersResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckZonePeersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CheckZonePeersResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "CheckZonePeersRequest") - - _request = build_subscriptions_check_zone_peers_request( - subscription_id=subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponseAutoGenerated, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CheckZonePeersResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class TenantsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.resource.subscriptions.SubscriptionClient`'s - :attr:`tenants` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SubscriptionClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.TenantIdDescription"]: - """Gets the tenants for your account. - - :return: An iterator like instance of either TenantIdDescription or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.resource.subscriptions.models.TenantIdDescription] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TenantListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_tenants_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("TenantListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class _SubscriptionClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SubscriptionClientConfiguration] -): - - @overload - def check_resource_name( - self, - resource_name_definition: Optional[_models.ResourceName] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CheckResourceNameResult: - """Checks resource name validity. - - A resource name is valid if it is not a reserved word, does not contains a reserved word and - does not start with a reserved word. - - :param resource_name_definition: Resource object with values for resource name and resource - type. Default value is None. - :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckResourceNameResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def check_resource_name( - self, - resource_name_definition: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CheckResourceNameResult: - """Checks resource name validity. - - A resource name is valid if it is not a reserved word, does not contains a reserved word and - does not start with a reserved word. - - :param resource_name_definition: Resource object with values for resource name and resource - type. Default value is None. - :type resource_name_definition: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: CheckResourceNameResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def check_resource_name( - self, resource_name_definition: Optional[Union[_models.ResourceName, IO[bytes]]] = None, **kwargs: Any - ) -> _models.CheckResourceNameResult: - """Checks resource name validity. - - A resource name is valid if it is not a reserved word, does not contains a reserved word and - does not start with a reserved word. - - :param resource_name_definition: Resource object with values for resource name and resource - type. Is either a ResourceName type or a IO[bytes] type. Default value is None. - :type resource_name_definition: ~azure.mgmt.resource.subscriptions.models.ResourceName or - IO[bytes] - :return: CheckResourceNameResult or the result of cls(response) - :rtype: ~azure.mgmt.resource.subscriptions.models.CheckResourceNameResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if resource_name_definition else None - cls: ClsType[_models.CheckResourceNameResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if resource_name_definition else None - _json = None - _content = None - if isinstance(resource_name_definition, (IOBase, bytes)): - _content = resource_name_definition - else: - if resource_name_definition is not None: - _json = self._serialize.body(resource_name_definition, "ResourceName") - else: - _json = None - - _request = build_subscription_check_resource_name_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CheckResourceNameResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_patch.py b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/py.typed b/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/changes/get_change.py b/sdk/resources/azure-mgmt-resource/generated_samples/changes/get_change.py deleted file mode 100644 index 5e31f10bd849..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/changes/get_change.py +++ /dev/null @@ -1,46 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.changes import ChangesClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_change.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ChangesClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId1", - ) - - response = client.changes.get( - resource_group_name="resourceGroup1", - resource_provider_namespace="resourceProvider1", - resource_type="resourceType1", - resource_name="resourceName1", - change_resource_id="1d58d72f-0719-4a48-9228-b7ea682885bf", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-05-01/examples/GetChange.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/changes/list_changes.py b/sdk/resources/azure-mgmt-resource/generated_samples/changes/list_changes.py deleted file mode 100644 index 2a5eecaccddd..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/changes/list_changes.py +++ /dev/null @@ -1,46 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.changes import ChangesClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_changes.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ChangesClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId1", - ) - - response = client.changes.list( - resource_group_name="resourceGroup1", - resource_provider_namespace="resourceProvider1", - resource_type="resourceType1", - resource_name="resourceName1", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-05-01/examples/ListChanges.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_scoped_data_boundary.py b/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_scoped_data_boundary.py deleted file mode 100644 index b9cb5560637f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_scoped_data_boundary.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_scoped_data_boundary.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = DataBoundaryMgmtClient( - credential=DefaultAzureCredential(), - ) - - response = client.data_boundaries.get_scope( - scope="subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group", - default="default", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-08-01/examples/GetScopedDataBoundary.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_tenant_data_boundary.py b/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_tenant_data_boundary.py deleted file mode 100644 index 9df50f89cc25..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/get_tenant_data_boundary.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_tenant_data_boundary.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = DataBoundaryMgmtClient( - credential=DefaultAzureCredential(), - ) - - response = client.data_boundaries.get_tenant( - default="default", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-08-01/examples/GetTenantDataBoundary.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/put_data_boundary.py b/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/put_data_boundary.py deleted file mode 100644 index d4a292bf6685..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/databoundaries/put_data_boundary.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python put_data_boundary.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = DataBoundaryMgmtClient( - credential=DefaultAzureCredential(), - ) - - response = client.data_boundaries.put( - default="default", - data_boundary_definition={"properties": {"dataBoundary": "EU"}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-08-01/examples/PutDataBoundary.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_delete.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_delete.py deleted file mode 100644 index b26a4327f751..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_delete.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python subscription_feature_registration_delete.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-1111-2222-3333-444444444444", - ) - - client.subscription_feature_registrations.delete( - provider_namespace="subscriptionFeatureRegistrationGroupTestRG", - feature_name="testFeature", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationDELETE.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_get.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_get.py deleted file mode 100644 index 2933da7e33a4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_get.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python subscription_feature_registration_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-1111-2222-3333-444444444444", - ) - - response = client.subscription_feature_registrations.get( - provider_namespace="subscriptionFeatureRegistrationGroupTestRG", - feature_name="testFeature", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationGET.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_list.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_list.py deleted file mode 100644 index 663b1880ef09..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_list.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python subscription_feature_registration_list.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-1111-2222-3333-444444444444", - ) - - response = client.subscription_feature_registrations.list_by_subscription( - provider_namespace="subscriptionFeatureRegistrationGroupTestRG", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationLIST.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_listall.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_listall.py deleted file mode 100644 index 2480718e3f7a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_listall.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python subscription_feature_registration_listall.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-1111-2222-3333-444444444444", - ) - - response = client.subscription_feature_registrations.list_all_by_subscription() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationLISTALL.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_put.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_put.py deleted file mode 100644 index 0dae2bc962ec..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/feature_registration/subscription_feature_registration_put.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python subscription_feature_registration_put.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-1111-2222-3333-444444444444", - ) - - response = client.subscription_feature_registrations.create_or_update( - provider_namespace="subscriptionFeatureRegistrationGroupTestRG", - feature_name="testFeature", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/FeatureRegistration/SubscriptionFeatureRegistrationPUT.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/get_feature.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/get_feature.py deleted file mode 100644 index 138d09ea65c2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/get_feature.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_feature.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.features.get( - resource_provider_namespace="Resource Provider Namespace", - feature_name="feature", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/getFeature.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/list_features_operations.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/list_features_operations.py deleted file mode 100644 index e848c80d1129..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/list_features_operations.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_features_operations.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.list_operations() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/listFeaturesOperations.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/list_provider_features.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/list_provider_features.py deleted file mode 100644 index 345d9640f23d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/list_provider_features.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_provider_features.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.features.list( - resource_provider_namespace="Resource Provider Namespace", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/listProviderFeatures.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/list_subscription_features.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/list_subscription_features.py deleted file mode 100644 index 7e7d6dd32711..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/list_subscription_features.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_subscription_features.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.features.list_all() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/listSubscriptionFeatures.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/register_feature.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/register_feature.py deleted file mode 100644 index 8176386f03ef..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/register_feature.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python register_feature.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.features.register( - resource_provider_namespace="Resource Provider Namespace", - feature_name="feature", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/registerFeature.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/features/unregister_feature.py b/sdk/resources/azure-mgmt-resource/generated_samples/features/unregister_feature.py deleted file mode 100644 index c825de583f98..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/features/unregister_feature.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.features import FeatureClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python unregister_feature.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = FeatureClient( - credential=DefaultAzureCredential(), - subscription_id="ff23096b-f5a2-46ea-bd62-59c3e93fef9a", - ) - - response = client.features.unregister( - resource_provider_namespace="Resource Provider Namespace", - feature_name="feature", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/unregisterFeature.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/list_provider_operations.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/list_provider_operations.py deleted file mode 100644 index c213122b299b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/list_provider_operations.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_provider_operations.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.authorization_operations.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ListProviderOperations.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_group_level.py deleted file mode 100644 index 335b17e362df..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_group_level.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_create_or_update_at_resource_group_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.create_or_update_at_resource_group_level( - resource_group_name="resourcegroupname", - lock_name="testlock", - parameters={"properties": {"level": "ReadOnly"}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtResourceGroupLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_level.py deleted file mode 100644 index b07c056ee896..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_resource_level.py +++ /dev/null @@ -1,48 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_create_or_update_at_resource_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.create_or_update_at_resource_level( - resource_group_name="resourcegroupname", - resource_provider_namespace="Microsoft.Storage", - parent_resource_path="parentResourcePath", - resource_type="storageAccounts", - resource_name="teststorageaccount", - lock_name="testlock", - parameters={"properties": {"level": "ReadOnly"}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtResourceLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_scope.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_scope.py deleted file mode 100644 index e152638e3e62..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_scope.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_create_or_update_at_scope.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.management_locks.create_or_update_by_scope( - scope="subscriptions/subscriptionId", - lock_name="testlock", - parameters={"properties": {"level": "ReadOnly"}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtScope.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_subscription_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_subscription_level.py deleted file mode 100644 index 30eedef0d32a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_create_or_update_at_subscription_level.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_create_or_update_at_subscription_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.create_or_update_at_subscription_level( - lock_name="testlock", - parameters={"properties": {"level": "ReadOnly"}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_CreateOrUpdateAtSubscriptionLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_group_level.py deleted file mode 100644 index 52ef58c437d8..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_group_level.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_delete_at_resource_group_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.management_locks.delete_at_resource_group_level( - resource_group_name="resourcegroupname", - lock_name="testlock", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_DeleteAtResourceGroupLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_level.py deleted file mode 100644 index c498141e6273..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_resource_level.py +++ /dev/null @@ -1,46 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_delete_at_resource_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.management_locks.delete_at_resource_level( - resource_group_name="resourcegroupname", - resource_provider_namespace="Microsoft.Storage", - parent_resource_path="parentResourcePath", - resource_type="storageAccounts", - resource_name="teststorageaccount", - lock_name="testlock", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_DeleteAtResourceLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_scope.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_scope.py deleted file mode 100644 index a69e6238a9b4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_scope.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_delete_at_scope.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.management_locks.delete_by_scope( - scope="subscriptions/subscriptionId", - lock_name="testlock", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_DeleteAtScope.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_subscription_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_subscription_level.py deleted file mode 100644 index d678d21c874d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_delete_at_subscription_level.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_delete_at_subscription_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.management_locks.delete_at_subscription_level( - lock_name="testlock", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_DeleteAtSubscriptionLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_group_level.py deleted file mode 100644 index e378f4146848..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_group_level.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_get_at_resource_group_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.get_at_resource_group_level( - resource_group_name="resourcegroupname", - lock_name="testlock", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_GetAtResourceGroupLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_level.py deleted file mode 100644 index 8c6a22154892..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_resource_level.py +++ /dev/null @@ -1,47 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_get_at_resource_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.get_at_resource_level( - resource_group_name="resourcegroupname", - resource_provider_namespace="Microsoft.Storage", - parent_resource_path="parentResourcePath", - resource_type="storageAccounts", - resource_name="teststorageaccount", - lock_name="testlock", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_GetAtResourceLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_scope.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_scope.py deleted file mode 100644 index ca50563039e2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_scope.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_get_at_scope.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.management_locks.get_by_scope( - scope="subscriptions/subscriptionId", - lock_name="testlock", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_GetAtScope.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_subscription_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_subscription_level.py deleted file mode 100644 index f772e9332237..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_get_at_subscription_level.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_get_at_subscription_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.get_at_subscription_level( - lock_name="testlock", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_GetAtSubscriptionLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_group_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_group_level.py deleted file mode 100644 index a12263206cc2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_group_level.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_list_at_resource_group_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.list_at_resource_group_level( - resource_group_name="resourcegroupname", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_ListAtResourceGroupLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_level.py deleted file mode 100644 index c0bc2f7cbea6..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_resource_level.py +++ /dev/null @@ -1,47 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_list_at_resource_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.list_at_resource_level( - resource_group_name="resourcegroupname", - resource_provider_namespace="Microsoft.Storage", - parent_resource_path="parentResourcePath", - resource_type="storageAccounts", - resource_name="teststorageaccount", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_ListAtResourceLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_scope.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_scope.py deleted file mode 100644 index 6539d6327a54..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_scope.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_list_at_scope.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.management_locks.list_by_scope( - scope="subscriptions/subscriptionId", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_ListAtScope.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_subscription_level.py b/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_subscription_level.py deleted file mode 100644 index 9a7f51b83c6b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/locks/management_locks_list_at_subscription_level.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.locks import ManagementLockClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python management_locks_list_at_subscription_level.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ManagementLockClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.management_locks.list_at_subscription_level() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/examples/ManagementLocks_ListAtSubscriptionLevel.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application.py deleted file mode 100644 index 74e93150ebfe..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application.py +++ /dev/null @@ -1,51 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_application.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.applications.begin_create_or_update( - resource_group_name="rg", - application_name="myManagedApplication", - parameters={ - "kind": "ServiceCatalog", - "location": "East US 2", - "properties": { - "applicationDefinitionId": "/subscriptions/subid/resourceGroups/rg/providers/Microsoft.Solutions/applicationDefinitions/myAppDef", - "managedResourceGroupId": "/subscriptions/subid/resourceGroups/myManagedRG", - }, - }, - ).result() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/createOrUpdateApplication.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application_definition.py deleted file mode 100644 index d6ce15758ea3..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/create_or_update_application_definition.py +++ /dev/null @@ -1,53 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_application_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.application_definitions.begin_create_or_update( - resource_group_name="rg", - application_definition_name="myManagedApplicationDef", - parameters={ - "location": "East US 2", - "properties": { - "authorizations": [{"principalId": "validprincipalguid", "roleDefinitionId": "validroleguid"}], - "description": "myManagedApplicationDef description", - "displayName": "myManagedApplicationDef", - "lockLevel": "None", - "packageFileUri": "https://path/to/packagezipfile", - }, - }, - ).result() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/createOrUpdateApplicationDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/delete_application_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/delete_application_definition.py deleted file mode 100644 index b5e88b527e4e..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/delete_application_definition.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_application_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - client.application_definitions.begin_delete_by_id( - resource_group_name="rg", - application_definition_name="myManagedApplicationDef", - ).result() - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/deleteApplicationDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application.py deleted file mode 100644 index 3dd4f98a533c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_application.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.applications.get( - resource_group_name="rg", - application_name="myManagedApplication", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/getApplication.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application_definition.py deleted file mode 100644 index 8289a3fdc0e4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/get_application_definition.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_application_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.application_definitions.get( - resource_group_name="rg", - application_definition_name="myManagedApplicationDef", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/getApplicationDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_application_definitions_by_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_application_definitions_by_resource_group.py deleted file mode 100644 index 6f79996e5b36..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_application_definitions_by_resource_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_application_definitions_by_resource_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.application_definitions.list_by_resource_group( - resource_group_name="rg", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/listApplicationDefinitionsByResourceGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_applications_by_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_applications_by_resource_group.py deleted file mode 100644 index 754f51c11a4f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_applications_by_resource_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_applications_by_resource_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.applications.list_by_resource_group( - resource_group_name="rg", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/listApplicationsByResourceGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_solutions_operations.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_solutions_operations.py deleted file mode 100644 index 6187adc8ccd5..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/list_solutions_operations.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_solutions_operations.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.list_operations() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/listSolutionsOperations.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/update_application.py b/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/update_application.py deleted file mode 100644 index fd7454a41bbd..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/managedapplications/update_application.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.managedapplications import ApplicationClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_application.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ApplicationClient( - credential=DefaultAzureCredential(), - subscription_id="subid", - ) - - response = client.applications.update( - resource_group_name="rg", - application_name="myManagedApplication", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Solutions/stable/2019-07-01/examples/updateApplication.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition.py deleted file mode 100644 index f4d82bc507d6..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition.py +++ /dev/null @@ -1,66 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definitions.create_or_update( - policy_definition_name="ResourceNaming", - parameters={ - "properties": { - "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", - "displayName": "Enforce resource naming convention", - "metadata": {"category": "Naming"}, - "mode": "All", - "parameters": { - "prefix": { - "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, - "type": "String", - }, - "suffix": { - "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, - "type": "String", - }, - }, - "policyRule": { - "if": { - "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} - }, - "then": {"effect": "deny"}, - }, - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicyDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_advanced_params.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_advanced_params.py deleted file mode 100644 index 318ba57e2df7..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_advanced_params.py +++ /dev/null @@ -1,82 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_definition_advanced_params.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definitions.create_or_update( - policy_definition_name="EventHubDiagnosticLogs", - parameters={ - "properties": { - "description": "Audit enabling of logs and retain them up to a year. This enables recreation of activity trails for investigation purposes when a security incident occurs or your network is compromised", - "displayName": "Event Hubs should have diagnostic logging enabled", - "metadata": {"category": "Event Hub"}, - "mode": "Indexed", - "parameters": { - "requiredRetentionDays": { - "allowedValues": [0, 30, 90, 180, 365], - "defaultValue": 365, - "metadata": { - "description": "The required diagnostic logs retention in days", - "displayName": "Required retention (days)", - }, - "type": "Integer", - } - }, - "policyRule": { - "if": {"equals": "Microsoft.EventHub/namespaces", "field": "type"}, - "then": { - "details": { - "existenceCondition": { - "allOf": [ - { - "equals": "true", - "field": "Microsoft.Insights/diagnosticSettings/logs[*].retentionPolicy.enabled", - }, - { - "equals": "[parameters('requiredRetentionDays')]", - "field": "Microsoft.Insights/diagnosticSettings/logs[*].retentionPolicy.days", - }, - ] - }, - "type": "Microsoft.Insights/diagnosticSettings", - }, - "effect": "AuditIfNotExists", - }, - }, - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionAdvancedParams.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_at_management_group.py deleted file mode 100644 index 67b904cf2413..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_at_management_group.py +++ /dev/null @@ -1,67 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_definition_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definitions.create_or_update_at_management_group( - management_group_id="MyManagementGroup", - policy_definition_name="ResourceNaming", - parameters={ - "properties": { - "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", - "displayName": "Enforce resource naming convention", - "metadata": {"category": "Naming"}, - "mode": "All", - "parameters": { - "prefix": { - "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, - "type": "String", - }, - "suffix": { - "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, - "type": "String", - }, - }, - "policyRule": { - "if": { - "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} - }, - "then": {"effect": "deny"}, - }, - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version.py deleted file mode 100644 index 44becf8b972e..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version.py +++ /dev/null @@ -1,68 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definition_versions.create_or_update( - policy_definition_name="ResourceNaming", - policy_definition_version="1.2.1", - parameters={ - "properties": { - "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", - "displayName": "Enforce resource naming convention", - "metadata": {"category": "Naming"}, - "mode": "All", - "parameters": { - "prefix": { - "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, - "type": "String", - }, - "suffix": { - "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, - "type": "String", - }, - }, - "policyRule": { - "if": { - "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} - }, - "then": {"effect": "deny"}, - }, - "version": "1.2.1", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version_at_management_group.py deleted file mode 100644 index 6d639b2f867b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_definition_version_at_management_group.py +++ /dev/null @@ -1,69 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_definition_version_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definition_versions.create_or_update_at_management_group( - management_group_name="MyManagementGroup", - policy_definition_name="ResourceNaming", - policy_definition_version="1.2.1", - parameters={ - "properties": { - "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", - "displayName": "Enforce resource naming convention", - "metadata": {"category": "Naming"}, - "mode": "All", - "parameters": { - "prefix": { - "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, - "type": "String", - }, - "suffix": { - "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, - "type": "String", - }, - }, - "policyRule": { - "if": { - "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} - }, - "then": {"effect": "deny"}, - }, - "version": "1.2.1", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionVersionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption.py deleted file mode 100644 index cde2e8516496..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption.py +++ /dev/null @@ -1,53 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_exemption.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_exemptions.create_or_update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", - policy_exemption_name="DemoExpensiveVM", - parameters={ - "properties": { - "description": "Exempt demo cluster from limit sku", - "displayName": "Exempt demo cluster", - "exemptionCategory": "Waiver", - "metadata": {"reason": "Temporary exemption for a expensive VM demo"}, - "policyAssignmentId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement", - "policyDefinitionReferenceIds": ["Limit_Skus"], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/createOrUpdatePolicyExemption.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption_with_resource_selectors.py deleted file mode 100644 index 2cd7a697fbe2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_exemption_with_resource_selectors.py +++ /dev/null @@ -1,60 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_exemption_with_resource_selectors.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_exemptions.create_or_update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", - policy_exemption_name="DemoExpensiveVM", - parameters={ - "properties": { - "assignmentScopeValidation": "Default", - "description": "Exempt demo cluster from limit sku", - "displayName": "Exempt demo cluster", - "exemptionCategory": "Waiver", - "metadata": {"reason": "Temporary exemption for a expensive VM demo"}, - "policyAssignmentId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement", - "policyDefinitionReferenceIds": ["Limit_Skus"], - "resourceSelectors": [ - { - "name": "SDPRegions", - "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], - } - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/createOrUpdatePolicyExemptionWithResourceSelectors.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition.py deleted file mode 100644 index 354b54f5ea96..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition.py +++ /dev/null @@ -1,68 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_set_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definitions.create_or_update( - policy_set_definition_name="CostManagement", - parameters={ - "properties": { - "description": "Policies to enforce low cost storage SKUs", - "displayName": "Cost Management", - "metadata": {"category": "Cost Management"}, - "parameters": { - "namePrefix": { - "defaultValue": "myPrefix", - "metadata": {"displayName": "Prefix to enforce on resource names"}, - "type": "String", - } - }, - "policyDefinitions": [ - { - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - "policyDefinitionReferenceId": "Limit_Skus", - }, - { - "parameters": {"prefix": {"value": "[parameters('namePrefix')]"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - "policyDefinitionReferenceId": "Resource_Naming", - }, - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicySetDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_at_management_group.py deleted file mode 100644 index c75448b67665..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_at_management_group.py +++ /dev/null @@ -1,62 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_set_definition_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definitions.create_or_update_at_management_group( - management_group_id="MyManagementGroup", - policy_set_definition_name="CostManagement", - parameters={ - "properties": { - "description": "Policies to enforce low cost storage SKUs", - "displayName": "Cost Management", - "metadata": {"category": "Cost Management"}, - "policyDefinitions": [ - { - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - "policyDefinitionReferenceId": "Limit_Skus", - }, - { - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - "policyDefinitionReferenceId": "Resource_Naming", - }, - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version.py deleted file mode 100644 index eab3aed03cb9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version.py +++ /dev/null @@ -1,70 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_set_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definition_versions.create_or_update( - policy_set_definition_name="CostManagement", - policy_definition_version="1.2.1", - parameters={ - "properties": { - "description": "Policies to enforce low cost storage SKUs", - "displayName": "Cost Management", - "metadata": {"category": "Cost Management"}, - "parameters": { - "namePrefix": { - "defaultValue": "myPrefix", - "metadata": {"displayName": "Prefix to enforce on resource names"}, - "type": "String", - } - }, - "policyDefinitions": [ - { - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - "policyDefinitionReferenceId": "Limit_Skus", - }, - { - "parameters": {"prefix": {"value": "[parameters('namePrefix')]"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - "policyDefinitionReferenceId": "Resource_Naming", - }, - ], - "version": "1.2.1", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version_at_management_group.py deleted file mode 100644 index 6b34288fb4ec..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_version_at_management_group.py +++ /dev/null @@ -1,64 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_set_definition_version_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.create_or_update_at_management_group( - management_group_name="MyManagementGroup", - policy_set_definition_name="CostManagement", - policy_definition_version="1.2.1", - parameters={ - "properties": { - "description": "Policies to enforce low cost storage SKUs", - "displayName": "Cost Management", - "metadata": {"category": "Cost Management"}, - "policyDefinitions": [ - { - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - "policyDefinitionReferenceId": "Limit_Skus", - }, - { - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - "policyDefinitionReferenceId": "Resource_Naming", - }, - ], - "version": "1.2.1", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionVersionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups.py deleted file mode 100644 index dbfbf078adac..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups.py +++ /dev/null @@ -1,77 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_set_definition_with_groups.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definitions.create_or_update( - policy_set_definition_name="CostManagement", - parameters={ - "properties": { - "description": "Policies to enforce low cost storage SKUs", - "displayName": "Cost Management", - "metadata": {"category": "Cost Management"}, - "policyDefinitionGroups": [ - { - "description": "Policies designed to control spend within a subscription.", - "displayName": "Cost Management Policies", - "name": "CostSaving", - }, - { - "description": "Policies that help enforce resource organization standards within a subscription.", - "displayName": "Organizational Policies", - "name": "Organizational", - }, - ], - "policyDefinitions": [ - { - "definitionVersion": "1.*.*", - "groupNames": ["CostSaving"], - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - "policyDefinitionReferenceId": "Limit_Skus", - }, - { - "definitionVersion": "1.*.*", - "groupNames": ["Organizational"], - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - "policyDefinitionReferenceId": "Resource_Naming", - }, - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionWithGroups.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups_at_management_group.py deleted file mode 100644 index 589300e0c744..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_policy_set_definition_with_groups_at_management_group.py +++ /dev/null @@ -1,76 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_policy_set_definition_with_groups_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definitions.create_or_update_at_management_group( - management_group_id="MyManagementGroup", - policy_set_definition_name="CostManagement", - parameters={ - "properties": { - "description": "Policies to enforce low cost storage SKUs", - "displayName": "Cost Management", - "metadata": {"category": "Cost Management"}, - "policyDefinitionGroups": [ - { - "description": "Policies designed to control spend within a subscription.", - "displayName": "Cost Management Policies", - "name": "CostSaving", - }, - { - "description": "Policies that help enforce resource organization standards within a subscription.", - "displayName": "Organizational Policies", - "name": "Organizational", - }, - ], - "policyDefinitions": [ - { - "groupNames": ["CostSaving"], - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - "policyDefinitionReferenceId": "Limit_Skus", - }, - { - "groupNames": ["Organizational"], - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - "policyDefinitionReferenceId": "Resource_Naming", - }, - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionWithGroupsAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable.py deleted file mode 100644 index 39dd72b54dd4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_variable.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.variables.create_or_update( - variable_name="DemoTestVariable", - parameters={"properties": {"columns": [{"columnName": "TestColumn"}]}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/createOrUpdateVariable.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_at_management_group.py deleted file mode 100644 index 5d89499f05ff..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_at_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_variable_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.variables.create_or_update_at_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - parameters={"properties": {"columns": [{"columnName": "TestColumn"}]}}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/createOrUpdateVariableAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value.py deleted file mode 100644 index 6fd220fd84de..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value.py +++ /dev/null @@ -1,51 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_variable_value.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.variable_values.create_or_update( - variable_name="DemoTestVariable", - variable_value_name="TestValue", - parameters={ - "properties": { - "values": [ - {"columnName": "StringColumn", "columnValue": "SampleValue"}, - {"columnName": "IntegerColumn", "columnValue": 10}, - ] - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/createOrUpdateVariableValue.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value_at_management_group.py deleted file mode 100644 index 8fca45ba8f77..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_or_update_variable_value_at_management_group.py +++ /dev/null @@ -1,52 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_or_update_variable_value_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.variable_values.create_or_update_at_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - variable_value_name="TestValue", - parameters={ - "properties": { - "values": [ - {"columnName": "StringColumn", "columnValue": "SampleValue"}, - {"columnName": "IntegerColumn", "columnValue": 10}, - ] - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/createOrUpdateVariableValueAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment.py deleted file mode 100644 index 4cb2bcbe4fe7..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment.py +++ /dev/null @@ -1,53 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - parameters={ - "properties": { - "description": "Force resource names to begin with given DeptA and end with -LC", - "displayName": "Enforce resource naming rules", - "metadata": {"assignedBy": "Special Someone"}, - "nonComplianceMessages": [{"message": "Resource names must start with 'DeptA' and end with '-LC'."}], - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignment.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_by_id.py deleted file mode 100644 index d7098f2552f2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_by_id.py +++ /dev/null @@ -1,53 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_by_id.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create_by_id( - policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", - parameters={ - "properties": { - "definitionVersion": "1.*.*", - "description": "Allow only storage accounts of SKU Standard_GRS or Standard_LRS to be created", - "displayName": "Enforce storage account SKU", - "enforcementMode": "Default", - "metadata": {"assignedBy": "Cheapskate Boss"}, - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentById.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_non_compliance_messages.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_non_compliance_messages.py deleted file mode 100644 index caac83f7c185..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_non_compliance_messages.py +++ /dev/null @@ -1,62 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_non_compliance_messages.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="securityInitAssignment", - parameters={ - "properties": { - "displayName": "Enforce security policies", - "nonComplianceMessages": [ - { - "message": "Resources must comply with all internal security policies. See for more info." - }, - { - "message": "Resource names must start with 'DeptA' and end with '-LC'.", - "policyDefinitionReferenceId": "10420126870854049575", - }, - { - "message": "Storage accounts must have firewall rules configured.", - "policyDefinitionReferenceId": "8572513655450389710", - }, - ], - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentNonComplianceMessages.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity.py deleted file mode 100644 index 795fe7ee632c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity.py +++ /dev/null @@ -1,55 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_with_identity.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - parameters={ - "identity": {"type": "SystemAssigned"}, - "location": "eastus", - "properties": { - "description": "Force resource names to begin with given DeptA and end with -LC", - "displayName": "Enforce resource naming rules", - "enforcementMode": "Default", - "metadata": {"assignedBy": "Foo Bar"}, - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - }, - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithIdentity.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity_by_id.py deleted file mode 100644 index f57a35ed8877..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_identity_by_id.py +++ /dev/null @@ -1,55 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_with_identity_by_id.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create_by_id( - policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", - parameters={ - "identity": {"type": "SystemAssigned"}, - "location": "eastus", - "properties": { - "definitionVersion": "1.*.*", - "description": "Allow only storage accounts of SKU Standard_GRS or Standard_LRS to be created", - "displayName": "Enforce storage account SKU", - "enforcementMode": "Default", - "metadata": {"assignedBy": "Cheapskate Boss"}, - "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, - "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", - }, - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithIdentityById.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_overrides.py deleted file mode 100644 index 3dd04efa7305..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_overrides.py +++ /dev/null @@ -1,58 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_with_overrides.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="CostManagement", - parameters={ - "properties": { - "description": "Limit the resource location and resource SKU", - "displayName": "Limit the resource location and resource SKU", - "metadata": {"assignedBy": "Special Someone"}, - "overrides": [ - { - "kind": "policyEffect", - "selectors": [{"in": ["Limit_Skus", "Limit_Locations"], "kind": "policyDefinitionReferenceId"}], - "value": "Audit", - } - ], - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithOverrides.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_resource_selectors.py deleted file mode 100644 index 718e489cfa46..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_resource_selectors.py +++ /dev/null @@ -1,57 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_with_resource_selectors.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="CostManagement", - parameters={ - "properties": { - "description": "Limit the resource location and resource SKU", - "displayName": "Limit the resource location and resource SKU", - "metadata": {"assignedBy": "Special Someone"}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement", - "resourceSelectors": [ - { - "name": "SDPRegions", - "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], - } - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithResourceSelectors.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_user_assigned_identity.py deleted file mode 100644 index 35462bc3b2ac..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_with_user_assigned_identity.py +++ /dev/null @@ -1,60 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_with_user_assigned_identity.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - parameters={ - "identity": { - "type": "UserAssigned", - "userAssignedIdentities": { - "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {} - }, - }, - "location": "eastus", - "properties": { - "description": "Force resource names to begin with given DeptA and end with -LC", - "displayName": "Enforce resource naming rules", - "enforcementMode": "Default", - "metadata": {"assignedBy": "Foo Bar"}, - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - }, - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithUserAssignedIdentity.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_without_enforcement.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_without_enforcement.py deleted file mode 100644 index 3e6449190c2e..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/create_policy_assignment_without_enforcement.py +++ /dev/null @@ -1,53 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python create_policy_assignment_without_enforcement.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.create( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - parameters={ - "properties": { - "description": "Force resource names to begin with given DeptA and end with -LC", - "displayName": "Enforce resource naming rules", - "enforcementMode": "DoNotEnforce", - "metadata": {"assignedBy": "Special Someone"}, - "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, - "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithoutEnforcement.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment.py deleted file mode 100644 index 2c2ee4855552..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_assignment.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.delete( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicyAssignment.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment_by_id.py deleted file mode 100644 index 5bf5885d81a9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_assignment_by_id.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_assignment_by_id.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.delete_by_id( - policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicyAssignmentById.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition.py deleted file mode 100644 index 72e7bdf33e71..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - client.policy_definitions.delete( - policy_definition_name="ResourceNaming", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicyDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_at_management_group.py deleted file mode 100644 index 5a9fa553adee..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_at_management_group.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_definition_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.policy_definitions.delete_at_management_group( - management_group_id="MyManagementGroup", - policy_definition_name="ResourceNaming", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicyDefinitionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version.py deleted file mode 100644 index f4e20dbd111f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - client.policy_definition_versions.delete( - policy_definition_name="ResourceNaming", - policy_definition_version="1.2.1", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicyDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version_at_management_group.py deleted file mode 100644 index 4703cbac4369..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_definition_version_at_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_definition_version_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.policy_definition_versions.delete_at_management_group( - management_group_name="MyManagementGroup", - policy_definition_name="ResourceNaming", - policy_definition_version="1.2.1", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicyDefinitionVersionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_exemption.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_exemption.py deleted file mode 100644 index 3144bc4d712f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_exemption.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_exemption.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.policy_exemptions.delete( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", - policy_exemption_name="DemoExpensiveVM", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/deletePolicyExemption.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition.py deleted file mode 100644 index 5db264528e83..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_set_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - client.policy_set_definitions.delete( - policy_set_definition_name="CostManagement", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicySetDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_at_management_group.py deleted file mode 100644 index 1ae8a6aef702..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_at_management_group.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_set_definition_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.policy_set_definitions.delete_at_management_group( - management_group_id="MyManagementGroup", - policy_set_definition_name="CostManagement", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicySetDefinitionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version.py deleted file mode 100644 index e11c5fb86c2b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_set_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - client.policy_set_definition_versions.delete( - policy_set_definition_name="CostManagement", - policy_definition_version="1.2.1", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicySetDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version_at_management_group.py deleted file mode 100644 index 6d90538ca979..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_policy_set_definition_version_at_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_policy_set_definition_version_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.policy_set_definition_versions.delete_at_management_group( - management_group_name="MyManagementGroup", - policy_set_definition_name="CostManagement", - policy_definition_version="1.2.1", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/deletePolicySetDefinitionVersionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable.py deleted file mode 100644 index ee4ea2262e93..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_variable.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - client.variables.delete( - variable_name="DemoTestVariable", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/deleteVariable.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_at_management_group.py deleted file mode 100644 index f1d54da5954e..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_at_management_group.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_variable_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.variables.delete_at_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/deleteVariableAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value.py deleted file mode 100644 index 1a2ecab2fd6f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_variable_value.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - client.variable_values.delete( - variable_name="DemoTestVariable", - variable_value_name="TestValue", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/deleteVariableValue.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value_at_management_group.py deleted file mode 100644 index 8869b5b8904d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/delete_variable_value_at_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_variable_value_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.variable_values.delete_at_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - variable_value_name="TestValue", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/deleteVariableValueAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition.py deleted file mode 100644 index d830ae62d364..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_built_in_policy_set_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definitions.get_built_in( - policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getBuiltInPolicySetDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition_version.py deleted file mode 100644 index 9ab7e9cf9e40..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_built_in_policy_set_definition_version.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_built_in_policy_set_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.get_built_in( - policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", - policy_definition_version="1.2.1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getBuiltInPolicySetDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition.py deleted file mode 100644 index c11c16a040d8..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_builtin_policy_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definitions.get_built_in( - policy_definition_name="7433c107-6db4-4ad1-b57a-a76dce0154a1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getBuiltinPolicyDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition_version.py deleted file mode 100644 index 5a0c37bb4f0b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_builtin_policy_definition_version.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_builtin_policy_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definition_versions.get_built_in( - policy_definition_name="7433c107-6db4-4ad1-b57a-a76dce0154a1", - policy_definition_version="1.2.1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getBuiltinPolicyDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_data_policy_manifest.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_data_policy_manifest.py deleted file mode 100644 index 77bd912af85f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_data_policy_manifest.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_data_policy_manifest.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.data_policy_manifests.get_by_policy_mode( - policy_mode="Microsoft.KeyVault.Data", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/getDataPolicyManifest.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment.py deleted file mode 100644 index d02eecab80d1..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignment.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_by_id.py deleted file mode 100644 index ce56f0813b82..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_by_id.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment_by_id.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get_by_id( - policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignmentById.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity.py deleted file mode 100644 index fb3dcfce48e2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment_with_identity.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignmentWithIdentity.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity_by_id.py deleted file mode 100644 index f5008645d4a3..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_identity_by_id.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment_with_identity_by_id.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get_by_id( - policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignmentWithIdentityById.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_overrides.py deleted file mode 100644 index 6aca9523edd9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_overrides.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment_with_overrides.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="CostManagement", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignmentWithOverrides.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_resource_selectors.py deleted file mode 100644 index d5a911d62c3c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_resource_selectors.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment_with_resource_selectors.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="CostManagement", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignmentWithResourceSelectors.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_user_assigned_identity.py deleted file mode 100644 index bca8f1ddf3bc..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_user_assigned_identity.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_assignment_with_user_assigned_identity.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyAssignmentWithUserAssignedIdentity.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition.py deleted file mode 100644 index 914edda19d54..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definitions.get( - policy_definition_name="ResourceNaming", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_at_management_group.py deleted file mode 100644 index 6bd860483442..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_at_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_definition_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definitions.get_at_management_group( - management_group_id="MyManagementGroup", - policy_definition_name="ResourceNaming", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyDefinitionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version.py deleted file mode 100644 index 686fd743e73d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definition_versions.get( - policy_definition_name="ResourceNaming", - policy_definition_version="1.2.1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version_at_management_group.py deleted file mode 100644 index 8145cf5e10e4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_definition_version_at_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_definition_version_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definition_versions.get_at_management_group( - management_group_name="MyManagementGroup", - policy_definition_name="ResourceNaming", - policy_definition_version="1.2.1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicyDefinitionVersionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption.py deleted file mode 100644 index 596dd9c04c75..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_exemption.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_exemptions.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", - policy_exemption_name="DemoExpensiveVM", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/getPolicyExemption.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption_with_resource_selectors.py deleted file mode 100644 index abec44ddeef7..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_exemption_with_resource_selectors.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_exemption_with_resource_selectors.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_exemptions.get( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", - policy_exemption_name="DemoExpensiveVM", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/getPolicyExemptionWithResourceSelectors.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition.py deleted file mode 100644 index 3432e2f2fee4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_set_definition.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definitions.get( - policy_set_definition_name="CostManagement", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicySetDefinition.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_at_management_group.py deleted file mode 100644 index 847a2b90eb37..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_at_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_set_definition_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definitions.get_at_management_group( - management_group_id="MyManagementGroup", - policy_set_definition_name="CostManagement", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicySetDefinitionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version.py deleted file mode 100644 index d2e9f8d8069c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_set_definition_version.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definition_versions.get( - policy_set_definition_name="CostManagement", - policy_definition_version="1.2.1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicySetDefinitionVersion.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version_at_management_group.py deleted file mode 100644 index acdadd88059a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_set_definition_version_at_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_policy_set_definition_version_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.get_at_management_group( - management_group_name="MyManagementGroup", - policy_set_definition_name="CostManagement", - policy_definition_version="1.2.1", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/getPolicySetDefinitionVersionAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable.py deleted file mode 100644 index 08cad1949977..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_variable.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.variables.get( - variable_name="DemoTestVariable", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/getVariable.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_at_management_group.py deleted file mode 100644 index 9caa129273c9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_at_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_variable_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.variables.get_at_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/getVariableAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value.py deleted file mode 100644 index 68e0904c2112..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_variable_value.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.variable_values.get( - variable_name="DemoTestVariable", - variable_value_name="TestValue", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/getVariableValue.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value_at_management_group.py deleted file mode 100644 index 8d1d974344bc..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_variable_value_at_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_variable_value_at_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.variable_values.get_at_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - variable_value_name="TestValue", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/getVariableValueAtManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_definition_versions.py deleted file mode 100644 index 89b4c5ec8569..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_definition_versions.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_all_built_in_policy_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definition_versions.list_all_builtins() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listAllBuiltInPolicyDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_set_definition_versions.py deleted file mode 100644 index f564ff15ab60..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_built_in_policy_set_definition_versions.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_all_built_in_policy_set_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.list_all_builtins() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listAllBuiltInPolicySetDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions.py deleted file mode 100644 index de09ec2d8358..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_all_policy_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definition_versions.list_all() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listAllPolicyDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions_by_management_group.py deleted file mode 100644 index 4daddd0eca35..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_definition_versions_by_management_group.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_all_policy_definition_versions_by_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definition_versions.list_all_at_management_group( - management_group_name="MyManagementGroup", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listAllPolicyDefinitionVersionsByManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions.py deleted file mode 100644 index 872e036e782d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_all_policy_set_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definition_versions.list_all() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listAllPolicySetDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions_by_management_group.py deleted file mode 100644 index d8feb555a399..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_all_policy_set_definition_versions_by_management_group.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_all_policy_set_definition_versions_by_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.list_all_at_management_group( - management_group_name="MyManagementGroup", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listAllPolicySetDefinitionVersionsByManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definition_versions.py deleted file mode 100644 index f574e4d0c46f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definition_versions.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_built_in_policy_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definition_versions.list_built_in( - policy_definition_name="06a78e20-9358-41c9-923c-fb736d382a12", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listBuiltInPolicyDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definitions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definitions.py deleted file mode 100644 index bf1ff62a6a72..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_definitions.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_built_in_policy_definitions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definitions.list_built_in() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listBuiltInPolicyDefinitions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definition_versions.py deleted file mode 100644 index 7b5288627cff..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definition_versions.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_built_in_policy_set_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.list_built_in( - policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listBuiltInPolicySetDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definitions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definitions.py deleted file mode 100644 index 6486bbaa4b48..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_built_in_policy_set_definitions.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_built_in_policy_set_definitions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definitions.list_built_in() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listBuiltInPolicySetDefinitions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests.py deleted file mode 100644 index 1339bb7d636d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_data_policy_manifests.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.data_policy_manifests.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/listDataPolicyManifests.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests_namespace_filter.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests_namespace_filter.py deleted file mode 100644 index bc9786ac38d7..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_data_policy_manifests_namespace_filter.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_data_policy_manifests_namespace_filter.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.data_policy_manifests.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/listDataPolicyManifestsNamespaceFilter.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments.py deleted file mode 100644 index db113a69e648..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_assignments.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_assignments.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyAssignments.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_management_group.py deleted file mode 100644 index f3170ac5ce14..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_assignments_for_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.list_for_management_group( - management_group_id="TestManagementGroup", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyAssignmentsForManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource.py deleted file mode 100644 index 98f075ea7828..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource.py +++ /dev/null @@ -1,47 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_assignments_for_resource.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_assignments.list_for_resource( - resource_group_name="TestResourceGroup", - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="virtualMachines/MyTestVm", - resource_type="domainNames", - resource_name="MyTestComputer.cloudapp.net", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyAssignmentsForResource.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource_group.py deleted file mode 100644 index 80185bbfa9d9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_assignments_for_resource_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_assignments_for_resource_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_assignments.list_for_resource_group( - resource_group_name="TestResourceGroup", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyAssignmentsForResourceGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions.py deleted file mode 100644 index 48895f445b39..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definition_versions.list( - policy_definition_name="ResourceNaming", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions_by_management_group.py deleted file mode 100644 index 47f7ff929ef6..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definition_versions_by_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_definition_versions_by_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definition_versions.list_by_management_group( - management_group_name="MyManagementGroup", - policy_definition_name="ResourceNaming", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyDefinitionVersionsByManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions.py deleted file mode 100644 index 7b6c618f08e2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_definitions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_definitions.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyDefinitions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions_by_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions_by_management_group.py deleted file mode 100644 index 8b017fddc80a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_definitions_by_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_definitions_by_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_definitions.list_by_management_group( - management_group_id="MyManagementGroup", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicyDefinitionsByManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_management_group.py deleted file mode 100644 index 034dfac42912..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_exemptions_for_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_exemptions.list_for_management_group( - management_group_id="DevOrg", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/listPolicyExemptionsForManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource.py deleted file mode 100644 index f253e08b634f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource.py +++ /dev/null @@ -1,47 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_exemptions_for_resource.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_exemptions.list_for_resource( - resource_group_name="TestResourceGroup", - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="virtualMachines/MyTestVm", - resource_type="domainNames", - resource_name="MyTestComputer.cloudapp.net", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/listPolicyExemptionsForResource.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource_group.py deleted file mode 100644 index b0c73ea2a5e9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_resource_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_exemptions_for_resource_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_exemptions.list_for_resource_group( - resource_group_name="TestResourceGroup", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/listPolicyExemptionsForResourceGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_subscription.py deleted file mode 100644 index 762ef7372382..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_exemptions_for_subscription.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_exemptions_for_subscription.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_exemptions.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/listPolicyExemptionsForSubscription.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions.py deleted file mode 100644 index fd3ec7db9149..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_set_definition_versions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definition_versions.list( - policy_set_definition_name="CostManagement", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicySetDefinitionVersions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions_by_management_group.py deleted file mode 100644 index cd7987fbabf3..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definition_versions_by_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_set_definition_versions_by_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definition_versions.list_by_management_group( - management_group_name="MyManagementGroup", - policy_set_definition_name="CostManagement", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicySetDefinitionVersionsByManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions.py deleted file mode 100644 index b28fe0dd35ba..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_set_definitions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.policy_set_definitions.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicySetDefinitions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions_by_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions_by_management_group.py deleted file mode 100644 index a70e6c3fdd9c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_policy_set_definitions_by_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_policy_set_definitions_by_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_set_definitions.list_by_management_group( - management_group_id="MyManagementGroup", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/listPolicySetDefinitionsByManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_management_group.py deleted file mode 100644 index d60263450abe..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_management_group.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_variable_values_for_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.variable_values.list_for_management_group( - management_group_id="DevOrg", - variable_name="DemoTestVariable", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/listVariableValuesForManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_subscription.py deleted file mode 100644 index cc1570eb3d03..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variable_values_for_subscription.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_variable_values_for_subscription.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.variable_values.list( - variable_name="DemoTestVariable", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/listVariableValuesForSubscription.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_management_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_management_group.py deleted file mode 100644 index b85c126b748f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_management_group.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_variables_for_management_group.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.variables.list_for_management_group( - management_group_id="DevOrg", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/listVariablesForManagementGroup.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_subscription.py deleted file mode 100644 index 40a66d4910a7..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/list_variables_for_subscription.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_variables_for_subscription.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - ) - - response = client.variables.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-08-01-preview/examples/listVariablesForSubscription.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity.py deleted file mode 100644 index 056971b9ab87..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_policy_assignment_with_identity.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - parameters={"identity": {"type": "SystemAssigned"}, "location": "eastus"}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/updatePolicyAssignmentWithIdentity.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity_by_id.py deleted file mode 100644 index e640db370a5b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_identity_by_id.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_policy_assignment_with_identity_by_id.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.update_by_id( - policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", - parameters={"identity": {"type": "SystemAssigned"}, "location": "eastus"}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/updatePolicyAssignmentWithIdentityById.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_overrides.py deleted file mode 100644 index 36aba01614ee..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_overrides.py +++ /dev/null @@ -1,54 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_policy_assignment_with_overrides.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="CostManagement", - parameters={ - "properties": { - "overrides": [ - { - "kind": "policyEffect", - "selectors": [{"in": ["Limit_Skus", "Limit_Locations"], "kind": "policyDefinitionReferenceId"}], - "value": "Audit", - } - ] - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/updatePolicyAssignmentWithOverrides.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_resource_selectors.py deleted file mode 100644 index acd5e48d22be..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_resource_selectors.py +++ /dev/null @@ -1,53 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_policy_assignment_with_resource_selectors.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="CostManagement", - parameters={ - "properties": { - "resourceSelectors": [ - { - "name": "SDPRegions", - "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], - } - ] - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/updatePolicyAssignmentWithResourceSelectors.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_user_assigned_identity.py deleted file mode 100644 index 4b01f94e4faa..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_assignment_with_user_assigned_identity.py +++ /dev/null @@ -1,52 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_policy_assignment_with_user_assigned_identity.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_assignments.update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", - policy_assignment_name="EnforceNaming", - parameters={ - "identity": { - "type": "UserAssigned", - "userAssignedIdentities": { - "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {} - }, - }, - "location": "eastus", - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/updatePolicyAssignmentWithUserAssignedIdentity.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_exemption_with_resource_selectors.py deleted file mode 100644 index 16baa8ef3817..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/policy/update_policy_exemption_with_resource_selectors.py +++ /dev/null @@ -1,54 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.policy import PolicyClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python update_policy_exemption_with_resource_selectors.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = PolicyClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.policy_exemptions.update( - scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", - policy_exemption_name="DemoExpensiveVM", - parameters={ - "properties": { - "assignmentScopeValidation": "Default", - "resourceSelectors": [ - { - "name": "SDPRegions", - "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], - } - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/preview/2022-07-01-preview/examples/updatePolicyExemptionWithResourceSelectors.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_private_link_association.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_private_link_association.py deleted file mode 100644 index b15d60945e5b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_private_link_association.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_private_link_association.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - client.private_link_association.delete( - group_id="my-management-group", - pla_id="00000000-0000-0000-0000-000000000000", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/DeletePrivateLinkAssociation.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_resource_management_private_link.py deleted file mode 100644 index 47212d1342ae..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/delete_resource_management_private_link.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python delete_resource_management_private_link.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", - ) - - client.resource_management_private_link.delete( - resource_group_name="my-resource-group", - rmpl_name="my-rmplName", - ) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/DeleteResourceManagementPrivateLink.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_private_link_association.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_private_link_association.py deleted file mode 100644 index 2f5abcb8b064..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_private_link_association.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_private_link_association.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.private_link_association.get( - group_id="my-management-group", - pla_id="00000000-0000-0000-0000-000000000000", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/GetPrivateLinkAssociation.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_resource_management_private_link.py deleted file mode 100644 index 0d659c567195..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/get_resource_management_private_link.py +++ /dev/null @@ -1,43 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_resource_management_private_link.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", - ) - - response = client.resource_management_private_link.get( - resource_group_name="my-resource-group", - rmpl_name="my-rmplName", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/GetResourceManagementPrivateLink.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_private_link_association.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_private_link_association.py deleted file mode 100644 index 87fa0340a2be..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_private_link_association.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_private_link_association.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.private_link_association.list( - group_id="my-management-group", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/ListPrivateLinkAssociation.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_resource_group_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_resource_group_resource_management_private_link.py deleted file mode 100644 index 2f07a1d93103..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_resource_group_resource_management_private_link.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_resource_group_resource_management_private_link.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", - ) - - response = client.resource_management_private_link.list_by_resource_group( - resource_group_name="my-resource-group", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/ListResourceGroupResourceManagementPrivateLink.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_subscription_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_subscription_resource_management_private_link.py deleted file mode 100644 index 95cceb44d423..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/list_subscription_resource_management_private_link.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python list_subscription_resource_management_private_link.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", - ) - - response = client.resource_management_private_link.list() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/ListSubscriptionResourceManagementPrivateLink.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_private_link_association.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_private_link_association.py deleted file mode 100644 index 71604197be1d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_private_link_association.py +++ /dev/null @@ -1,46 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python put_private_link_association.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="SUBSCRIPTION_ID", - ) - - response = client.private_link_association.put( - group_id="my-management-group", - pla_id="00000000-0000-0000-0000-000000000000", - parameters={ - "properties": {"privateLink": "00000000-0000-0000-0000-000000000000", "publicNetworkAccess": "Enabled"} - }, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/PutPrivateLinkAssociation.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_resource_management_private_link.py b/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_resource_management_private_link.py deleted file mode 100644 index 9e1e2b027e21..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/privatelinks/put_resource_management_private_link.py +++ /dev/null @@ -1,44 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python put_resource_management_private_link.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = ResourcePrivateLinkClient( - credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", - ) - - response = client.resource_management_private_link.put( - resource_group_name="my-resource-group", - rmpl_name="my-rmplName", - parameters={"location": "eastus"}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/examples/PutResourceManagementPrivateLink.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/create_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/create_resource_group.py index 88dfc91cfd16..34a901800905 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/create_resource_group.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/create_resource_group.py @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/CreateResourceGroup.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/CreateResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_resource.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_resource.py index d0d158523896..83985fe4c81d 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_resource.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_resource.py @@ -36,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/DeleteTagsResource.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/DeleteTagsResource.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_subscription.py index 17e4a46f1092..0549b8e17bf9 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_subscription.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/delete_tags_subscription.py @@ -36,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/DeleteTagsSubscription.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/DeleteTagsSubscription.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group.py index 62e00b78339c..852ea6428601 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group.py @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/ExportResourceGroup.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/ExportResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_as_bicep.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_as_bicep.py index de85490d85e2..864717d214fa 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_as_bicep.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_as_bicep.py @@ -42,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/ExportResourceGroupAsBicep.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/ExportResourceGroupAsBicep.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_with_filtering.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_with_filtering.py index d27144d1f044..8706c7813eb1 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_with_filtering.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/export_resource_group_with_filtering.py @@ -43,6 +43,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/ExportResourceGroupWithFiltering.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/ExportResourceGroupWithFiltering.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_and_vmss_in_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_and_vmss_in_resource_group.py index 4cf0f9a34466..ee44eec281b4 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_and_vmss_in_resource_group.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_and_vmss_in_resource_group.py @@ -36,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/ForceDeleteVMsAndVMSSInResourceGroup.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/ForceDeleteVMsAndVMSSInResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_in_resource_group.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_in_resource_group.py index 082f8e3bf7c8..3b88b5f37b2b 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_in_resource_group.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/force_delete_vms_in_resource_group.py @@ -36,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/ForceDeleteVMsInResourceGroup.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/ForceDeleteVMsInResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_named_provider_at_tenant.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_named_provider_at_tenant.py index 41137bb8079b..0c5d8d1d8db9 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_named_provider_at_tenant.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_named_provider_at_tenant.py @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetNamedProviderAtTenant.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetNamedProviderAtTenant.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider.py index 011dad0fe5cf..1a59e0aed0c3 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider.py @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetProvider.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetProvider.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_permissions.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_permissions.py index 7af5835ca564..49768879b50e 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_permissions.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_permissions.py @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetProviderPermissions.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetProviderPermissions.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_resource_types.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_resource_types.py index b11323e2b866..09b79e84918f 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_resource_types.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_provider_resource_types.py @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetProviderResourceTypes.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetProviderResourceTypes.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_providers.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_providers.py index c665811e27d3..45cd0c24f0b0 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_providers.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_providers.py @@ -36,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetProviders.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetProviders.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_resource.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_resource.py index 8df361212d80..da345eced31d 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_resource.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_resource.py @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetTagsResource.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetTagsResource.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_subscription.py index 2fc891d5cfeb..96a34449d125 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_subscription.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/get_tags_subscription.py @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/GetTagsSubscription.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/GetTagsSubscription.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_resource.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_resource.py index 6de067b276f7..b417ea491133 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_resource.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_resource.py @@ -41,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/PatchTagsResource.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/PatchTagsResource.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_subscription.py index da7f203f3b9b..e37b8be07295 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_subscription.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/patch_tags_subscription.py @@ -41,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/PatchTagsSubscription.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/PatchTagsSubscription.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_resource.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_resource.py index 0041fd7575d2..3e707043612f 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_resource.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_resource.py @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/PutTagsResource.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/PutTagsResource.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_subscription.py index df6c24ac6c39..256e10804d90 100644 --- a/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_subscription.py +++ b/sdk/resources/azure-mgmt-resource/generated_samples/resources/put_tags_subscription.py @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2025-04-01/examples/PutTagsSubscription.json +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/resources/stable/2025-04-01/examples/PutTagsSubscription.json if __name__ == "__main__": main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/check_resource_name.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/check_resource_name.py deleted file mode 100644 index 88bb098797ff..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/check_resource_name.py +++ /dev/null @@ -1,39 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python check_resource_name.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.check_resource_name() - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/CheckResourceName.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations.py deleted file mode 100644 index 20489c61d78a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_locations.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.subscriptions.list_locations( - subscription_id="a1ffc958-d2c7-493e-9f1e-125a0477f536", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/GetLocations.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations_with_extended_locations.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations_with_extended_locations.py deleted file mode 100644 index c1289baa5d87..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_locations_with_extended_locations.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_locations_with_extended_locations.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.subscriptions.list_locations( - subscription_id="a1ffc958-d2c7-493e-9f1e-125a0477f536", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/GetLocationsWithExtendedLocations.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscription.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscription.py deleted file mode 100644 index 478eff74d346..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscription.py +++ /dev/null @@ -1,41 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_subscription.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.subscriptions.get( - subscription_id="291bba3f-e0a5-47bc-a099-3bdcb2a50a05", - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/GetSubscription.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscriptions.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscriptions.py deleted file mode 100644 index 9d307feaf99d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_subscriptions.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_subscriptions.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.subscriptions.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/GetSubscriptions.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_tenants.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_tenants.py deleted file mode 100644 index 76ea272e0bdc..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/get_tenants.py +++ /dev/null @@ -1,40 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python get_tenants.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.tenants.list() - for item in response: - print(item) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/GetTenants.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/post_check_zone_peers.py b/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/post_check_zone_peers.py deleted file mode 100644 index 3fb9be0f2970..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_samples/subscriptions/post_check_zone_peers.py +++ /dev/null @@ -1,42 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.resource.subscriptions import SubscriptionClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-resource -# USAGE - python post_check_zone_peers.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = SubscriptionClient( - credential=DefaultAzureCredential(), - ) - - response = client.subscriptions.check_zone_peers( - subscription_id="8d65815f-a5b6-402f-9298-045155da7d74", - parameters={"location": "eastus", "subscriptionIds": ["subscriptions/11111111-1111-1111-1111-111111111111"]}, - ) - print(response) - - -# x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/examples/PostCheckZonePeers.json -if __name__ == "__main__": - main() diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource/generated_tests/conftest.py index d0a3b52e198a..82b5f79fbbd0 100644 --- a/sdk/resources/azure-mgmt-resource/generated_tests/conftest.py +++ b/sdk/resources/azure-mgmt-resource/generated_tests/conftest.py @@ -21,14 +21,14 @@ # For security, please avoid record sensitive identity information in recordings @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): - databoundarymgmt_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - databoundarymgmt_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") - databoundarymgmt_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - databoundarymgmt_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=databoundarymgmt_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=databoundarymgmt_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=databoundarymgmt_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=databoundarymgmt_client_secret, value="00000000-0000-0000-0000-000000000000") + resourcemanagement_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + resourcemanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + resourcemanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + resourcemanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourcemanagement_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourcemanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourcemanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=resourcemanagement_client_secret, value="00000000-0000-0000-0000-000000000000") add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") add_header_regex_sanitizer(key="Cookie", value="cookie;") diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application.py deleted file mode 100644 index 0377b67b0be3..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplication(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_list_operations(self, resource_group): - response = self.client.list_operations( - api_version="2019-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations.py deleted file mode 100644 index d5a6643fae79..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations.py +++ /dev/null @@ -1,148 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationApplicationDefinitionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_get(self, resource_group): - response = self.client.application_definitions.get( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_begin_delete(self, resource_group): - response = self.client.application_definitions.begin_delete( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_begin_create_or_update(self, resource_group): - response = self.client.application_definitions.begin_create_or_update( - resource_group_name=resource_group.name, - application_definition_name="str", - parameters={ - "lockLevel": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "createUiDefinition": {}, - "deploymentPolicy": {"deploymentMode": "str"}, - "description": "str", - "displayName": "str", - "id": "str", - "isEnabled": bool, - "location": "str", - "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, - "mainTemplate": {}, - "managedBy": "str", - "managementPolicy": {"mode": "str"}, - "name": "str", - "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, - "packageFileUri": "str", - "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], - "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, - "tags": {"str": "str"}, - "type": "str", - }, - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_list_by_resource_group(self, resource_group): - response = self.client.application_definitions.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2019-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_get_by_id(self, resource_group): - response = self.client.application_definitions.get_by_id( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_begin_delete_by_id(self, resource_group): - response = self.client.application_definitions.begin_delete_by_id( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_application_definitions_begin_create_or_update_by_id(self, resource_group): - response = self.client.application_definitions.begin_create_or_update_by_id( - resource_group_name=resource_group.name, - application_definition_name="str", - parameters={ - "lockLevel": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "createUiDefinition": {}, - "deploymentPolicy": {"deploymentMode": "str"}, - "description": "str", - "displayName": "str", - "id": "str", - "isEnabled": bool, - "location": "str", - "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, - "mainTemplate": {}, - "managedBy": "str", - "managementPolicy": {"mode": "str"}, - "name": "str", - "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, - "packageFileUri": "str", - "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], - "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, - "tags": {"str": "str"}, - "type": "str", - }, - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations_async.py deleted file mode 100644 index 780a831d1008..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_application_definitions_operations_async.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications.aio import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationApplicationDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_get(self, resource_group): - response = await self.client.application_definitions.get( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_begin_delete(self, resource_group): - response = await ( - await self.client.application_definitions.begin_delete( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_begin_create_or_update(self, resource_group): - response = await ( - await self.client.application_definitions.begin_create_or_update( - resource_group_name=resource_group.name, - application_definition_name="str", - parameters={ - "lockLevel": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "createUiDefinition": {}, - "deploymentPolicy": {"deploymentMode": "str"}, - "description": "str", - "displayName": "str", - "id": "str", - "isEnabled": bool, - "location": "str", - "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, - "mainTemplate": {}, - "managedBy": "str", - "managementPolicy": {"mode": "str"}, - "name": "str", - "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, - "packageFileUri": "str", - "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], - "sku": { - "name": "str", - "capacity": 0, - "family": "str", - "model": "str", - "size": "str", - "tier": "str", - }, - "tags": {"str": "str"}, - "type": "str", - }, - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_list_by_resource_group(self, resource_group): - response = self.client.application_definitions.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2019-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_get_by_id(self, resource_group): - response = await self.client.application_definitions.get_by_id( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_begin_delete_by_id(self, resource_group): - response = await ( - await self.client.application_definitions.begin_delete_by_id( - resource_group_name=resource_group.name, - application_definition_name="str", - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_application_definitions_begin_create_or_update_by_id(self, resource_group): - response = await ( - await self.client.application_definitions.begin_create_or_update_by_id( - resource_group_name=resource_group.name, - application_definition_name="str", - parameters={ - "lockLevel": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "createUiDefinition": {}, - "deploymentPolicy": {"deploymentMode": "str"}, - "description": "str", - "displayName": "str", - "id": "str", - "isEnabled": bool, - "location": "str", - "lockingPolicy": {"allowedActions": ["str"], "allowedDataActions": ["str"]}, - "mainTemplate": {}, - "managedBy": "str", - "managementPolicy": {"mode": "str"}, - "name": "str", - "notificationPolicy": {"notificationEndpoints": [{"uri": "str"}]}, - "packageFileUri": "str", - "policies": [{"name": "str", "parameters": "str", "policyDefinitionId": "str"}], - "sku": { - "name": "str", - "capacity": 0, - "family": "str", - "model": "str", - "size": "str", - "tier": "str", - }, - "tags": {"str": "str"}, - "type": "str", - }, - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations.py deleted file mode 100644 index 59b1d04354c2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations.py +++ /dev/null @@ -1,218 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationApplicationsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_get(self, resource_group): - response = self.client.applications.get( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_begin_delete(self, resource_group): - response = self.client.applications.begin_delete( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_begin_create_or_update(self, resource_group): - response = self.client.applications.begin_create_or_update( - resource_group_name=resource_group.name, - application_name="str", - parameters={ - "kind": "str", - "applicationDefinitionId": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "billingDetails": {"resourceUsageId": "str"}, - "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, - }, - "jitAccessPolicy": { - "jitAccessEnabled": bool, - "jitApprovalMode": "str", - "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], - "maximumJitAccessDuration": "str", - }, - "location": "str", - "managedBy": "str", - "managedResourceGroupId": "str", - "managementMode": "str", - "name": "str", - "outputs": {}, - "parameters": {}, - "plan": {"name": "str", "product": "str", "publisher": "str", "version": "str", "promotionCode": "str"}, - "provisioningState": "str", - "publisherTenantId": "str", - "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, - "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, - "tags": {"str": "str"}, - "type": "str", - "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - }, - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_update(self, resource_group): - response = self.client.applications.update( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_list_by_resource_group(self, resource_group): - response = self.client.applications.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2019-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_list_by_subscription(self, resource_group): - response = self.client.applications.list_by_subscription( - api_version="2019-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_get_by_id(self, resource_group): - response = self.client.applications.get_by_id( - application_id="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_begin_delete_by_id(self, resource_group): - response = self.client.applications.begin_delete_by_id( - application_id="str", - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_begin_create_or_update_by_id(self, resource_group): - response = self.client.applications.begin_create_or_update_by_id( - application_id="str", - parameters={ - "kind": "str", - "applicationDefinitionId": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "billingDetails": {"resourceUsageId": "str"}, - "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, - }, - "jitAccessPolicy": { - "jitAccessEnabled": bool, - "jitApprovalMode": "str", - "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], - "maximumJitAccessDuration": "str", - }, - "location": "str", - "managedBy": "str", - "managedResourceGroupId": "str", - "managementMode": "str", - "name": "str", - "outputs": {}, - "parameters": {}, - "plan": {"name": "str", "product": "str", "publisher": "str", "version": "str", "promotionCode": "str"}, - "provisioningState": "str", - "publisherTenantId": "str", - "sku": {"name": "str", "capacity": 0, "family": "str", "model": "str", "size": "str", "tier": "str"}, - "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, - "tags": {"str": "str"}, - "type": "str", - "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - }, - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_update_by_id(self, resource_group): - response = self.client.applications.update_by_id( - application_id="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_applications_begin_refresh_permissions(self, resource_group): - response = self.client.applications.begin_refresh_permissions( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations_async.py deleted file mode 100644 index 41cfb021e04d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_applications_operations_async.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications.aio import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationApplicationsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_get(self, resource_group): - response = await self.client.applications.get( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_begin_delete(self, resource_group): - response = await ( - await self.client.applications.begin_delete( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_begin_create_or_update(self, resource_group): - response = await ( - await self.client.applications.begin_create_or_update( - resource_group_name=resource_group.name, - application_name="str", - parameters={ - "kind": "str", - "applicationDefinitionId": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "billingDetails": {"resourceUsageId": "str"}, - "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, - }, - "jitAccessPolicy": { - "jitAccessEnabled": bool, - "jitApprovalMode": "str", - "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], - "maximumJitAccessDuration": "str", - }, - "location": "str", - "managedBy": "str", - "managedResourceGroupId": "str", - "managementMode": "str", - "name": "str", - "outputs": {}, - "parameters": {}, - "plan": { - "name": "str", - "product": "str", - "publisher": "str", - "version": "str", - "promotionCode": "str", - }, - "provisioningState": "str", - "publisherTenantId": "str", - "sku": { - "name": "str", - "capacity": 0, - "family": "str", - "model": "str", - "size": "str", - "tier": "str", - }, - "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, - "tags": {"str": "str"}, - "type": "str", - "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - }, - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_update(self, resource_group): - response = await self.client.applications.update( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_list_by_resource_group(self, resource_group): - response = self.client.applications.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2019-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_list_by_subscription(self, resource_group): - response = self.client.applications.list_by_subscription( - api_version="2019-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_get_by_id(self, resource_group): - response = await self.client.applications.get_by_id( - application_id="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_begin_delete_by_id(self, resource_group): - response = await ( - await self.client.applications.begin_delete_by_id( - application_id="str", - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_begin_create_or_update_by_id(self, resource_group): - response = await ( - await self.client.applications.begin_create_or_update_by_id( - application_id="str", - parameters={ - "kind": "str", - "applicationDefinitionId": "str", - "artifacts": [{"name": "str", "type": "str", "uri": "str"}], - "authorizations": [{"principalId": "str", "roleDefinitionId": "str"}], - "billingDetails": {"resourceUsageId": "str"}, - "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - "customerSupport": {"email": "str", "phone": "str", "contactName": "str"}, - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"principalId": "str", "tenantId": "str"}}, - }, - "jitAccessPolicy": { - "jitAccessEnabled": bool, - "jitApprovalMode": "str", - "jitApprovers": [{"id": "str", "displayName": "str", "type": "str"}], - "maximumJitAccessDuration": "str", - }, - "location": "str", - "managedBy": "str", - "managedResourceGroupId": "str", - "managementMode": "str", - "name": "str", - "outputs": {}, - "parameters": {}, - "plan": { - "name": "str", - "product": "str", - "publisher": "str", - "version": "str", - "promotionCode": "str", - }, - "provisioningState": "str", - "publisherTenantId": "str", - "sku": { - "name": "str", - "capacity": 0, - "family": "str", - "model": "str", - "size": "str", - "tier": "str", - }, - "supportUrls": {"governmentCloud": "str", "publicAzure": "str"}, - "tags": {"str": "str"}, - "type": "str", - "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - }, - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_update_by_id(self, resource_group): - response = await self.client.applications.update_by_id( - application_id="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_applications_begin_refresh_permissions(self, resource_group): - response = await ( - await self.client.applications.begin_refresh_permissions( - resource_group_name=resource_group.name, - application_name="str", - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_async.py deleted file mode 100644 index df72803a5f39..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications.aio import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_list_operations(self, resource_group): - response = self.client.list_operations( - api_version="2019-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations.py deleted file mode 100644 index f0cd26e49228..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations.py +++ /dev/null @@ -1,108 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationJitRequestsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_jit_requests_get(self, resource_group): - response = self.client.jit_requests.get( - resource_group_name=resource_group.name, - jit_request_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_jit_requests_begin_create_or_update(self, resource_group): - response = self.client.jit_requests.begin_create_or_update( - resource_group_name=resource_group.name, - jit_request_name="str", - parameters={ - "applicationResourceId": "str", - "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - "id": "str", - "jitAuthorizationPolicies": [{"principalId": "str", "roleDefinitionId": "str"}], - "jitRequestState": "str", - "jitSchedulingPolicy": { - "duration": "1 day, 0:00:00", - "startTime": "2020-02-20 00:00:00", - "type": "str", - }, - "location": "str", - "name": "str", - "provisioningState": "str", - "publisherTenantId": "str", - "tags": {"str": "str"}, - "type": "str", - "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - }, - api_version="2019-07-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_jit_requests_update(self, resource_group): - response = self.client.jit_requests.update( - resource_group_name=resource_group.name, - jit_request_name="str", - parameters={"tags": {"str": "str"}}, - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_jit_requests_delete(self, resource_group): - response = self.client.jit_requests.delete( - resource_group_name=resource_group.name, - jit_request_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_jit_requests_list_by_subscription(self, resource_group): - response = self.client.jit_requests.list_by_subscription( - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_jit_requests_list_by_resource_group(self, resource_group): - response = self.client.jit_requests.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations_async.py deleted file mode 100644 index dbcafcf74cbe..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_application_jit_requests_operations_async.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.managedapplications.aio import ApplicationClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestApplicationJitRequestsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_jit_requests_get(self, resource_group): - response = await self.client.jit_requests.get( - resource_group_name=resource_group.name, - jit_request_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_jit_requests_begin_create_or_update(self, resource_group): - response = await ( - await self.client.jit_requests.begin_create_or_update( - resource_group_name=resource_group.name, - jit_request_name="str", - parameters={ - "applicationResourceId": "str", - "createdBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - "id": "str", - "jitAuthorizationPolicies": [{"principalId": "str", "roleDefinitionId": "str"}], - "jitRequestState": "str", - "jitSchedulingPolicy": { - "duration": "1 day, 0:00:00", - "startTime": "2020-02-20 00:00:00", - "type": "str", - }, - "location": "str", - "name": "str", - "provisioningState": "str", - "publisherTenantId": "str", - "tags": {"str": "str"}, - "type": "str", - "updatedBy": {"applicationId": "str", "oid": "str", "puid": "str"}, - }, - api_version="2019-07-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_jit_requests_update(self, resource_group): - response = await self.client.jit_requests.update( - resource_group_name=resource_group.name, - jit_request_name="str", - parameters={"tags": {"str": "str"}}, - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_jit_requests_delete(self, resource_group): - response = await self.client.jit_requests.delete( - resource_group_name=resource_group.name, - jit_request_name="str", - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_jit_requests_list_by_subscription(self, resource_group): - response = await self.client.jit_requests.list_by_subscription( - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_jit_requests_list_by_resource_group(self, resource_group): - response = await self.client.jit_requests.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2019-07-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations.py deleted file mode 100644 index 8b735a43fbf2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.changes import ChangesClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestChangesChangesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ChangesClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_changes_list(self, resource_group): - response = self.client.changes.list( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - resource_type="str", - resource_name="str", - api_version="2022-05-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_changes_get(self, resource_group): - response = self.client.changes.get( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - resource_type="str", - resource_name="str", - change_resource_id="str", - api_version="2022-05-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations_async.py deleted file mode 100644 index 3ed263a8c02b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_changes_changes_operations_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.changes.aio import ChangesClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestChangesChangesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ChangesClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_changes_list(self, resource_group): - response = self.client.changes.list( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - resource_type="str", - resource_name="str", - api_version="2022-05-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_changes_get(self, resource_group): - response = await self.client.changes.get( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - resource_type="str", - resource_name="str", - change_resource_id="str", - api_version="2022-05-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations.py deleted file mode 100644 index 68bde5f416b7..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.databoundaries import DataBoundary - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestDataBoundaryDataBoundariesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(DataBoundary) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_boundaries_put(self, resource_group): - response = self.client.data_boundaries.put( - default="str", - data_boundary_definition={ - "id": "str", - "name": "str", - "properties": {"dataBoundary": "str", "provisioningState": "str"}, - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_boundaries_get_tenant(self, resource_group): - response = self.client.data_boundaries.get_tenant( - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_boundaries_get_scope(self, resource_group): - response = self.client.data_boundaries.get_scope( - scope="str", - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations_async.py deleted file mode 100644 index 46340e9d215c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_data_boundaries_operations_async.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.databoundaries.aio import DataBoundary - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestDataBoundaryDataBoundariesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(DataBoundary, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_boundaries_put(self, resource_group): - response = await self.client.data_boundaries.put( - default="str", - data_boundary_definition={ - "id": "str", - "name": "str", - "properties": {"dataBoundary": "str", "provisioningState": "str"}, - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_boundaries_get_tenant(self, resource_group): - response = await self.client.data_boundaries.get_tenant( - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_boundaries_get_scope(self, resource_group): - response = await self.client.data_boundaries.get_scope( - scope="str", - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py deleted file mode 100644 index 34eac057d847..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestDataBoundaryMgmtDataBoundariesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(DataBoundaryMgmtClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_boundaries_put(self, resource_group): - response = self.client.data_boundaries.put( - default="str", - data_boundary_definition={ - "id": "str", - "name": "str", - "properties": {"dataBoundary": "str", "provisioningState": "str"}, - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_boundaries_get_tenant(self, resource_group): - response = self.client.data_boundaries.get_tenant( - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_boundaries_get_scope(self, resource_group): - response = self.client.data_boundaries.get_scope( - scope="str", - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py deleted file mode 100644 index ca7627519d79..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_data_boundary_mgmt_data_boundaries_operations_async.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.databoundaries.aio import DataBoundaryMgmtClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestDataBoundaryMgmtDataBoundariesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(DataBoundaryMgmtClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_boundaries_put(self, resource_group): - response = await self.client.data_boundaries.put( - default="str", - data_boundary_definition={ - "id": "str", - "name": "str", - "properties": {"dataBoundary": "str", "provisioningState": "str"}, - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_boundaries_get_tenant(self, resource_group): - response = await self.client.data_boundaries.get_tenant( - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_boundaries_get_scope(self, resource_group): - response = await self.client.data_boundaries.get_scope( - scope="str", - default="str", - api_version="2024-08-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_feature.py deleted file mode 100644 index 3e8c2f19b93b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.features import FeatureClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestFeature(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_list_operations(self, resource_group): - response = self.client.list_operations( - api_version="2021-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_async.py deleted file mode 100644 index b74a3e8e12ad..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.features.aio import FeatureClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestFeatureAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_list_operations(self, resource_group): - response = self.client.list_operations( - api_version="2021-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations.py deleted file mode 100644 index 378bbf66d7aa..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.features import FeatureClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestFeatureFeaturesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_features_list_all(self, resource_group): - response = self.client.features.list_all( - api_version="2021-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_features_list(self, resource_group): - response = self.client.features.list( - resource_provider_namespace="str", - api_version="2021-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_features_get(self, resource_group): - response = self.client.features.get( - resource_provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_features_register(self, resource_group): - response = self.client.features.register( - resource_provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_features_unregister(self, resource_group): - response = self.client.features.unregister( - resource_provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations_async.py deleted file mode 100644 index df7789e0065b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_features_operations_async.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.features.aio import FeatureClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestFeatureFeaturesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_features_list_all(self, resource_group): - response = self.client.features.list_all( - api_version="2021-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_features_list(self, resource_group): - response = self.client.features.list( - resource_provider_namespace="str", - api_version="2021-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_features_get(self, resource_group): - response = await self.client.features.get( - resource_provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_features_register(self, resource_group): - response = await self.client.features.register( - resource_provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_features_unregister(self, resource_group): - response = await self.client.features.unregister( - resource_provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations.py deleted file mode 100644 index 767f142ac401..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.features import FeatureClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestFeatureSubscriptionFeatureRegistrationsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscription_feature_registrations_get(self, resource_group): - response = self.client.subscription_feature_registrations.get( - provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscription_feature_registrations_create_or_update(self, resource_group): - response = self.client.subscription_feature_registrations.create_or_update( - provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscription_feature_registrations_delete(self, resource_group): - response = self.client.subscription_feature_registrations.delete( - provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscription_feature_registrations_list_by_subscription(self, resource_group): - response = self.client.subscription_feature_registrations.list_by_subscription( - provider_namespace="str", - api_version="2021-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscription_feature_registrations_list_all_by_subscription(self, resource_group): - response = self.client.subscription_feature_registrations.list_all_by_subscription( - api_version="2021-07-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations_async.py deleted file mode 100644 index 2f75a84cec6c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_feature_subscription_feature_registrations_operations_async.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.features.aio import FeatureClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestFeatureSubscriptionFeatureRegistrationsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscription_feature_registrations_get(self, resource_group): - response = await self.client.subscription_feature_registrations.get( - provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscription_feature_registrations_create_or_update(self, resource_group): - response = await self.client.subscription_feature_registrations.create_or_update( - provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscription_feature_registrations_delete(self, resource_group): - response = await self.client.subscription_feature_registrations.delete( - provider_namespace="str", - feature_name="str", - api_version="2021-07-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscription_feature_registrations_list_by_subscription(self, resource_group): - response = self.client.subscription_feature_registrations.list_by_subscription( - provider_namespace="str", - api_version="2021-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscription_feature_registrations_list_all_by_subscription(self, resource_group): - response = self.client.subscription_feature_registrations.list_all_by_subscription( - api_version="2021-07-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations.py deleted file mode 100644 index e267f119cb12..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.links import ManagementLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLinkOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLinkClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_operations_list(self, resource_group): - response = self.client.operations.list( - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations_async.py deleted file mode 100644 index 1a27683f3d5c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_operations_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.links.aio import ManagementLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLinkOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLinkClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_operations_list(self, resource_group): - response = self.client.operations.list( - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations.py deleted file mode 100644 index 73e3130d31c8..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.links import ManagementLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLinkResourceLinksOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLinkClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_links_delete(self, resource_group): - response = self.client.resource_links.delete( - link_id="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_links_create_or_update(self, resource_group): - response = self.client.resource_links.create_or_update( - link_id="str", - parameters={ - "id": "str", - "name": "str", - "properties": {"targetId": "str", "notes": "str", "sourceId": "str"}, - "type": {}, - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_links_get(self, resource_group): - response = self.client.resource_links.get( - link_id="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_links_list_at_subscription(self, resource_group): - response = self.client.resource_links.list_at_subscription( - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_links_list_at_source_scope(self, resource_group): - response = self.client.resource_links.list_at_source_scope( - scope="str", - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations_async.py deleted file mode 100644 index 291bf615cf33..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_link_resource_links_operations_async.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.links.aio import ManagementLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLinkResourceLinksOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLinkClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_links_delete(self, resource_group): - response = await self.client.resource_links.delete( - link_id="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_links_create_or_update(self, resource_group): - response = await self.client.resource_links.create_or_update( - link_id="str", - parameters={ - "id": "str", - "name": "str", - "properties": {"targetId": "str", "notes": "str", "sourceId": "str"}, - "type": {}, - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_links_get(self, resource_group): - response = await self.client.resource_links.get( - link_id="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_links_list_at_subscription(self, resource_group): - response = self.client.resource_links.list_at_subscription( - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_links_list_at_source_scope(self, resource_group): - response = self.client.resource_links.list_at_source_scope( - scope="str", - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations.py deleted file mode 100644 index 887ea3a8f653..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.locks import ManagementLockClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLockAuthorizationOperationsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLockClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_authorization_operations_list(self, resource_group): - response = self.client.authorization_operations.list( - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations_async.py deleted file mode 100644 index 1e0b09f2ed97..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_authorization_operations_operations_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.locks.aio import ManagementLockClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLockAuthorizationOperationsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLockClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_authorization_operations_list(self, resource_group): - response = self.client.authorization_operations.list( - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations.py deleted file mode 100644 index b636617fc4f0..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.locks import ManagementLockClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLockManagementLocksOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLockClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_create_or_update_at_resource_group_level(self, resource_group): - response = self.client.management_locks.create_or_update_at_resource_group_level( - resource_group_name=resource_group.name, - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_delete_at_resource_group_level(self, resource_group): - response = self.client.management_locks.delete_at_resource_group_level( - resource_group_name=resource_group.name, - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_get_at_resource_group_level(self, resource_group): - response = self.client.management_locks.get_at_resource_group_level( - resource_group_name=resource_group.name, - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_create_or_update_by_scope(self, resource_group): - response = self.client.management_locks.create_or_update_by_scope( - scope="str", - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_delete_by_scope(self, resource_group): - response = self.client.management_locks.delete_by_scope( - scope="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_get_by_scope(self, resource_group): - response = self.client.management_locks.get_by_scope( - scope="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_create_or_update_at_resource_level(self, resource_group): - response = self.client.management_locks.create_or_update_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_delete_at_resource_level(self, resource_group): - response = self.client.management_locks.delete_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_get_at_resource_level(self, resource_group): - response = self.client.management_locks.get_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_create_or_update_at_subscription_level(self, resource_group): - response = self.client.management_locks.create_or_update_at_subscription_level( - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_delete_at_subscription_level(self, resource_group): - response = self.client.management_locks.delete_at_subscription_level( - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_get_at_subscription_level(self, resource_group): - response = self.client.management_locks.get_at_subscription_level( - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_list_at_resource_group_level(self, resource_group): - response = self.client.management_locks.list_at_resource_group_level( - resource_group_name=resource_group.name, - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_list_at_resource_level(self, resource_group): - response = self.client.management_locks.list_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_list_at_subscription_level(self, resource_group): - response = self.client.management_locks.list_at_subscription_level( - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_management_locks_list_by_scope(self, resource_group): - response = self.client.management_locks.list_by_scope( - scope="str", - api_version="2016-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations_async.py deleted file mode 100644 index 986fda779d7e..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_management_lock_management_locks_operations_async.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.locks.aio import ManagementLockClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestManagementLockManagementLocksOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLockClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_create_or_update_at_resource_group_level(self, resource_group): - response = await self.client.management_locks.create_or_update_at_resource_group_level( - resource_group_name=resource_group.name, - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_delete_at_resource_group_level(self, resource_group): - response = await self.client.management_locks.delete_at_resource_group_level( - resource_group_name=resource_group.name, - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_get_at_resource_group_level(self, resource_group): - response = await self.client.management_locks.get_at_resource_group_level( - resource_group_name=resource_group.name, - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_create_or_update_by_scope(self, resource_group): - response = await self.client.management_locks.create_or_update_by_scope( - scope="str", - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_delete_by_scope(self, resource_group): - response = await self.client.management_locks.delete_by_scope( - scope="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_get_by_scope(self, resource_group): - response = await self.client.management_locks.get_by_scope( - scope="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_create_or_update_at_resource_level(self, resource_group): - response = await self.client.management_locks.create_or_update_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_delete_at_resource_level(self, resource_group): - response = await self.client.management_locks.delete_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_get_at_resource_level(self, resource_group): - response = await self.client.management_locks.get_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_create_or_update_at_subscription_level(self, resource_group): - response = await self.client.management_locks.create_or_update_at_subscription_level( - lock_name="str", - parameters={ - "level": "str", - "id": "str", - "name": "str", - "notes": "str", - "owners": [{"applicationId": "str"}], - "type": "str", - }, - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_delete_at_subscription_level(self, resource_group): - response = await self.client.management_locks.delete_at_subscription_level( - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_get_at_subscription_level(self, resource_group): - response = await self.client.management_locks.get_at_subscription_level( - lock_name="str", - api_version="2016-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_list_at_resource_group_level(self, resource_group): - response = self.client.management_locks.list_at_resource_group_level( - resource_group_name=resource_group.name, - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_list_at_resource_level(self, resource_group): - response = self.client.management_locks.list_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_list_at_subscription_level(self, resource_group): - response = self.client.management_locks.list_at_subscription_level( - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_management_locks_list_by_scope(self, resource_group): - response = self.client.management_locks.list_by_scope( - scope="str", - api_version="2016-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations.py deleted file mode 100644 index 43e4371bb1ae..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyDataPolicyManifestsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_policy_manifests_get_by_policy_mode(self, resource_group): - response = self.client.data_policy_manifests.get_by_policy_mode( - policy_mode="str", - api_version="2020-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_data_policy_manifests_list(self, resource_group): - response = self.client.data_policy_manifests.list( - api_version="2020-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations_async.py deleted file mode 100644 index d6bebc8340f6..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_data_policy_manifests_operations_async.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyDataPolicyManifestsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_policy_manifests_get_by_policy_mode(self, resource_group): - response = await self.client.data_policy_manifests.get_by_policy_mode( - policy_mode="str", - api_version="2020-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_data_policy_manifests_list(self, resource_group): - response = self.client.data_policy_manifests.list( - api_version="2020-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations.py deleted file mode 100644 index 57b128e19c3b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations.py +++ /dev/null @@ -1,256 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyAssignmentsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_delete(self, resource_group): - response = self.client.policy_assignments.delete( - scope="str", - policy_assignment_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_create(self, resource_group): - response = self.client.policy_assignments.create( - scope="str", - policy_assignment_name="str", - parameters={ - "definitionVersion": "str", - "description": "str", - "displayName": "str", - "effectiveDefinitionVersion": "str", - "enforcementMode": "Default", - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "latestDefinitionVersion": "str", - "location": "str", - "metadata": {}, - "name": "str", - "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], - "notScopes": ["str"], - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "parameters": {"str": {"value": {}}}, - "policyDefinitionId": "str", - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - "scope": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_get(self, resource_group): - response = self.client.policy_assignments.get( - scope="str", - policy_assignment_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_update(self, resource_group): - response = self.client.policy_assignments.update( - scope="str", - policy_assignment_name="str", - parameters={ - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "location": "str", - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_list_for_resource_group(self, resource_group): - response = self.client.policy_assignments.list_for_resource_group( - resource_group_name=resource_group.name, - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_list_for_resource(self, resource_group): - response = self.client.policy_assignments.list_for_resource( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_list_for_management_group(self, resource_group): - response = self.client.policy_assignments.list_for_management_group( - management_group_id="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_list(self, resource_group): - response = self.client.policy_assignments.list( - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_delete_by_id(self, resource_group): - response = self.client.policy_assignments.delete_by_id( - policy_assignment_id="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_create_by_id(self, resource_group): - response = self.client.policy_assignments.create_by_id( - policy_assignment_id="str", - parameters={ - "definitionVersion": "str", - "description": "str", - "displayName": "str", - "effectiveDefinitionVersion": "str", - "enforcementMode": "Default", - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "latestDefinitionVersion": "str", - "location": "str", - "metadata": {}, - "name": "str", - "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], - "notScopes": ["str"], - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "parameters": {"str": {"value": {}}}, - "policyDefinitionId": "str", - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - "scope": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_get_by_id(self, resource_group): - response = self.client.policy_assignments.get_by_id( - policy_assignment_id="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_update_by_id(self, resource_group): - response = self.client.policy_assignments.update_by_id( - policy_assignment_id="str", - parameters={ - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "location": "str", - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations_async.py deleted file mode 100644 index 4dc457727160..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_assignments_operations_async.py +++ /dev/null @@ -1,257 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyAssignmentsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_delete(self, resource_group): - response = await self.client.policy_assignments.delete( - scope="str", - policy_assignment_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_create(self, resource_group): - response = await self.client.policy_assignments.create( - scope="str", - policy_assignment_name="str", - parameters={ - "definitionVersion": "str", - "description": "str", - "displayName": "str", - "effectiveDefinitionVersion": "str", - "enforcementMode": "Default", - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "latestDefinitionVersion": "str", - "location": "str", - "metadata": {}, - "name": "str", - "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], - "notScopes": ["str"], - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "parameters": {"str": {"value": {}}}, - "policyDefinitionId": "str", - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - "scope": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_get(self, resource_group): - response = await self.client.policy_assignments.get( - scope="str", - policy_assignment_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_update(self, resource_group): - response = await self.client.policy_assignments.update( - scope="str", - policy_assignment_name="str", - parameters={ - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "location": "str", - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_list_for_resource_group(self, resource_group): - response = self.client.policy_assignments.list_for_resource_group( - resource_group_name=resource_group.name, - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_list_for_resource(self, resource_group): - response = self.client.policy_assignments.list_for_resource( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_list_for_management_group(self, resource_group): - response = self.client.policy_assignments.list_for_management_group( - management_group_id="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_list(self, resource_group): - response = self.client.policy_assignments.list( - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_delete_by_id(self, resource_group): - response = await self.client.policy_assignments.delete_by_id( - policy_assignment_id="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_create_by_id(self, resource_group): - response = await self.client.policy_assignments.create_by_id( - policy_assignment_id="str", - parameters={ - "definitionVersion": "str", - "description": "str", - "displayName": "str", - "effectiveDefinitionVersion": "str", - "enforcementMode": "Default", - "id": "str", - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "latestDefinitionVersion": "str", - "location": "str", - "metadata": {}, - "name": "str", - "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], - "notScopes": ["str"], - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "parameters": {"str": {"value": {}}}, - "policyDefinitionId": "str", - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - "scope": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_get_by_id(self, resource_group): - response = await self.client.policy_assignments.get_by_id( - policy_assignment_id="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_update_by_id(self, resource_group): - response = await self.client.policy_assignments.update_by_id( - policy_assignment_id="str", - parameters={ - "identity": { - "principalId": "str", - "tenantId": "str", - "type": "str", - "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, - }, - "location": "str", - "overrides": [ - {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} - ], - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations.py deleted file mode 100644 index 784e7081ae10..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations.py +++ /dev/null @@ -1,239 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyDefinitionVersionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_list_all_builtins(self, resource_group): - response = self.client.policy_definition_versions.list_all_builtins( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_list_all_at_management_group(self, resource_group): - response = self.client.policy_definition_versions.list_all_at_management_group( - management_group_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_list_all(self, resource_group): - response = self.client.policy_definition_versions.list_all( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_create_or_update(self, resource_group): - response = self.client.policy_definition_versions.create_or_update( - policy_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_delete(self, resource_group): - response = self.client.policy_definition_versions.delete( - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_get(self, resource_group): - response = self.client.policy_definition_versions.get( - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_get_built_in(self, resource_group): - response = self.client.policy_definition_versions.get_built_in( - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_create_or_update_at_management_group(self, resource_group): - response = self.client.policy_definition_versions.create_or_update_at_management_group( - management_group_name="str", - policy_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_delete_at_management_group(self, resource_group): - response = self.client.policy_definition_versions.delete_at_management_group( - management_group_name="str", - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_get_at_management_group(self, resource_group): - response = self.client.policy_definition_versions.get_at_management_group( - management_group_name="str", - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_list(self, resource_group): - response = self.client.policy_definition_versions.list( - policy_definition_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_list_built_in(self, resource_group): - response = self.client.policy_definition_versions.list_built_in( - policy_definition_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definition_versions_list_by_management_group(self, resource_group): - response = self.client.policy_definition_versions.list_by_management_group( - management_group_name="str", - policy_definition_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations_async.py deleted file mode 100644 index 24f06e299437..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definition_versions_operations_async.py +++ /dev/null @@ -1,240 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_list_all_builtins(self, resource_group): - response = await self.client.policy_definition_versions.list_all_builtins( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_list_all_at_management_group(self, resource_group): - response = await self.client.policy_definition_versions.list_all_at_management_group( - management_group_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_list_all(self, resource_group): - response = await self.client.policy_definition_versions.list_all( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_create_or_update(self, resource_group): - response = await self.client.policy_definition_versions.create_or_update( - policy_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_delete(self, resource_group): - response = await self.client.policy_definition_versions.delete( - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_get(self, resource_group): - response = await self.client.policy_definition_versions.get( - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_get_built_in(self, resource_group): - response = await self.client.policy_definition_versions.get_built_in( - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_create_or_update_at_management_group(self, resource_group): - response = await self.client.policy_definition_versions.create_or_update_at_management_group( - management_group_name="str", - policy_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_delete_at_management_group(self, resource_group): - response = await self.client.policy_definition_versions.delete_at_management_group( - management_group_name="str", - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_get_at_management_group(self, resource_group): - response = await self.client.policy_definition_versions.get_at_management_group( - management_group_name="str", - policy_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_list(self, resource_group): - response = self.client.policy_definition_versions.list( - policy_definition_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_list_built_in(self, resource_group): - response = self.client.policy_definition_versions.list_built_in( - policy_definition_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definition_versions_list_by_management_group(self, resource_group): - response = self.client.policy_definition_versions.list_by_management_group( - management_group_name="str", - policy_definition_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations.py deleted file mode 100644 index 2b1965134aa6..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations.py +++ /dev/null @@ -1,200 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyDefinitionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_create_or_update(self, resource_group): - response = self.client.policy_definitions.create_or_update( - policy_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_delete(self, resource_group): - response = self.client.policy_definitions.delete( - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_get(self, resource_group): - response = self.client.policy_definitions.get( - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_get_built_in(self, resource_group): - response = self.client.policy_definitions.get_built_in( - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_create_or_update_at_management_group(self, resource_group): - response = self.client.policy_definitions.create_or_update_at_management_group( - management_group_id="str", - policy_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_delete_at_management_group(self, resource_group): - response = self.client.policy_definitions.delete_at_management_group( - management_group_id="str", - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_get_at_management_group(self, resource_group): - response = self.client.policy_definitions.get_at_management_group( - management_group_id="str", - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_list(self, resource_group): - response = self.client.policy_definitions.list( - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_list_built_in(self, resource_group): - response = self.client.policy_definitions.list_built_in( - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_list_by_management_group(self, resource_group): - response = self.client.policy_definitions.list_by_management_group( - management_group_id="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations_async.py deleted file mode 100644 index bbec542c33e9..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_definitions_operations_async.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_create_or_update(self, resource_group): - response = await self.client.policy_definitions.create_or_update( - policy_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_delete(self, resource_group): - response = await self.client.policy_definitions.delete( - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_get(self, resource_group): - response = await self.client.policy_definitions.get( - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_get_built_in(self, resource_group): - response = await self.client.policy_definitions.get_built_in( - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_create_or_update_at_management_group(self, resource_group): - response = await self.client.policy_definitions.create_or_update_at_management_group( - management_group_id="str", - policy_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "mode": "Indexed", - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyRule": {}, - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_delete_at_management_group(self, resource_group): - response = await self.client.policy_definitions.delete_at_management_group( - management_group_id="str", - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_get_at_management_group(self, resource_group): - response = await self.client.policy_definitions.get_at_management_group( - management_group_id="str", - policy_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_list(self, resource_group): - response = self.client.policy_definitions.list( - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_list_built_in(self, resource_group): - response = self.client.policy_definitions.list_built_in( - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_list_by_management_group(self, resource_group): - response = self.client.policy_definitions.list_by_management_group( - management_group_id="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations.py deleted file mode 100644 index cfaf494b118a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyExemptionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_delete(self, resource_group): - response = self.client.policy_exemptions.delete( - scope="str", - policy_exemption_name="str", - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_create_or_update(self, resource_group): - response = self.client.policy_exemptions.create_or_update( - scope="str", - policy_exemption_name="str", - parameters={ - "exemptionCategory": "str", - "policyAssignmentId": "str", - "assignmentScopeValidation": "str", - "description": "str", - "displayName": "str", - "expiresOn": "2020-02-20 00:00:00", - "id": "str", - "metadata": {}, - "name": "str", - "policyDefinitionReferenceIds": ["str"], - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_get(self, resource_group): - response = self.client.policy_exemptions.get( - scope="str", - policy_exemption_name="str", - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_update(self, resource_group): - response = self.client.policy_exemptions.update( - scope="str", - policy_exemption_name="str", - parameters={ - "assignmentScopeValidation": "str", - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - }, - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_list(self, resource_group): - response = self.client.policy_exemptions.list( - api_version="2022-07-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_list_for_resource_group(self, resource_group): - response = self.client.policy_exemptions.list_for_resource_group( - resource_group_name=resource_group.name, - api_version="2022-07-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_list_for_resource(self, resource_group): - response = self.client.policy_exemptions.list_for_resource( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - api_version="2022-07-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_exemptions_list_for_management_group(self, resource_group): - response = self.client.policy_exemptions.list_for_management_group( - management_group_id="str", - api_version="2022-07-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations_async.py deleted file mode 100644 index 7960bd6eb74c..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_exemptions_operations_async.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicyExemptionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_delete(self, resource_group): - response = await self.client.policy_exemptions.delete( - scope="str", - policy_exemption_name="str", - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_create_or_update(self, resource_group): - response = await self.client.policy_exemptions.create_or_update( - scope="str", - policy_exemption_name="str", - parameters={ - "exemptionCategory": "str", - "policyAssignmentId": "str", - "assignmentScopeValidation": "str", - "description": "str", - "displayName": "str", - "expiresOn": "2020-02-20 00:00:00", - "id": "str", - "metadata": {}, - "name": "str", - "policyDefinitionReferenceIds": ["str"], - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_get(self, resource_group): - response = await self.client.policy_exemptions.get( - scope="str", - policy_exemption_name="str", - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_update(self, resource_group): - response = await self.client.policy_exemptions.update( - scope="str", - policy_exemption_name="str", - parameters={ - "assignmentScopeValidation": "str", - "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], - }, - api_version="2022-07-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_list(self, resource_group): - response = self.client.policy_exemptions.list( - api_version="2022-07-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_list_for_resource_group(self, resource_group): - response = self.client.policy_exemptions.list_for_resource_group( - resource_group_name=resource_group.name, - api_version="2022-07-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_list_for_resource(self, resource_group): - response = self.client.policy_exemptions.list_for_resource( - resource_group_name=resource_group.name, - resource_provider_namespace="str", - parent_resource_path="str", - resource_type="str", - resource_name="str", - api_version="2022-07-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_exemptions_list_for_management_group(self, resource_group): - response = self.client.policy_exemptions.list_for_management_group( - management_group_id="str", - api_version="2022-07-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations.py deleted file mode 100644 index 62b7d7194bf4..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations.py +++ /dev/null @@ -1,275 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicySetDefinitionVersionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_list_all_builtins(self, resource_group): - response = self.client.policy_set_definition_versions.list_all_builtins( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_list_all_at_management_group(self, resource_group): - response = self.client.policy_set_definition_versions.list_all_at_management_group( - management_group_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_list_all(self, resource_group): - response = self.client.policy_set_definition_versions.list_all( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_create_or_update(self, resource_group): - response = self.client.policy_set_definition_versions.create_or_update( - policy_set_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_delete(self, resource_group): - response = self.client.policy_set_definition_versions.delete( - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_get(self, resource_group): - response = self.client.policy_set_definition_versions.get( - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_get_built_in(self, resource_group): - response = self.client.policy_set_definition_versions.get_built_in( - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_list(self, resource_group): - response = self.client.policy_set_definition_versions.list( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_list_built_in(self, resource_group): - response = self.client.policy_set_definition_versions.list_built_in( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_create_or_update_at_management_group(self, resource_group): - response = self.client.policy_set_definition_versions.create_or_update_at_management_group( - management_group_name="str", - policy_set_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_delete_at_management_group(self, resource_group): - response = self.client.policy_set_definition_versions.delete_at_management_group( - management_group_name="str", - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_get_at_management_group(self, resource_group): - response = self.client.policy_set_definition_versions.get_at_management_group( - management_group_name="str", - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definition_versions_list_by_management_group(self, resource_group): - response = self.client.policy_set_definition_versions.list_by_management_group( - management_group_name="str", - policy_set_definition_name="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations_async.py deleted file mode 100644 index 8bcf4cb39fb2..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definition_versions_operations_async.py +++ /dev/null @@ -1,276 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicySetDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_list_all_builtins(self, resource_group): - response = await self.client.policy_set_definition_versions.list_all_builtins( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_list_all_at_management_group(self, resource_group): - response = await self.client.policy_set_definition_versions.list_all_at_management_group( - management_group_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_list_all(self, resource_group): - response = await self.client.policy_set_definition_versions.list_all( - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_create_or_update(self, resource_group): - response = await self.client.policy_set_definition_versions.create_or_update( - policy_set_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_delete(self, resource_group): - response = await self.client.policy_set_definition_versions.delete( - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_get(self, resource_group): - response = await self.client.policy_set_definition_versions.get( - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_get_built_in(self, resource_group): - response = await self.client.policy_set_definition_versions.get_built_in( - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_list(self, resource_group): - response = self.client.policy_set_definition_versions.list( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_list_built_in(self, resource_group): - response = self.client.policy_set_definition_versions.list_built_in( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_create_or_update_at_management_group(self, resource_group): - response = await self.client.policy_set_definition_versions.create_or_update_at_management_group( - management_group_name="str", - policy_set_definition_name="str", - policy_definition_version="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_delete_at_management_group(self, resource_group): - response = await self.client.policy_set_definition_versions.delete_at_management_group( - management_group_name="str", - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_get_at_management_group(self, resource_group): - response = await self.client.policy_set_definition_versions.get_at_management_group( - management_group_name="str", - policy_set_definition_name="str", - policy_definition_version="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definition_versions_list_by_management_group(self, resource_group): - response = self.client.policy_set_definition_versions.list_by_management_group( - management_group_name="str", - policy_set_definition_name="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations.py deleted file mode 100644 index 640d2c73344f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations.py +++ /dev/null @@ -1,236 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicySetDefinitionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_create_or_update(self, resource_group): - response = self.client.policy_set_definitions.create_or_update( - policy_set_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_delete(self, resource_group): - response = self.client.policy_set_definitions.delete( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_get(self, resource_group): - response = self.client.policy_set_definitions.get( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_get_built_in(self, resource_group): - response = self.client.policy_set_definitions.get_built_in( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_list(self, resource_group): - response = self.client.policy_set_definitions.list( - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_list_built_in(self, resource_group): - response = self.client.policy_set_definitions.list_built_in( - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_create_or_update_at_management_group(self, resource_group): - response = self.client.policy_set_definitions.create_or_update_at_management_group( - management_group_id="str", - policy_set_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_delete_at_management_group(self, resource_group): - response = self.client.policy_set_definitions.delete_at_management_group( - management_group_id="str", - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_get_at_management_group(self, resource_group): - response = self.client.policy_set_definitions.get_at_management_group( - management_group_id="str", - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_set_definitions_list_by_management_group(self, resource_group): - response = self.client.policy_set_definitions.list_by_management_group( - management_group_id="str", - api_version="2023-04-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations_async.py deleted file mode 100644 index f1fdf201e272..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_policy_set_definitions_operations_async.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyPolicySetDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_create_or_update(self, resource_group): - response = await self.client.policy_set_definitions.create_or_update( - policy_set_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_delete(self, resource_group): - response = await self.client.policy_set_definitions.delete( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_get(self, resource_group): - response = await self.client.policy_set_definitions.get( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_get_built_in(self, resource_group): - response = await self.client.policy_set_definitions.get_built_in( - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_list(self, resource_group): - response = self.client.policy_set_definitions.list( - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_list_built_in(self, resource_group): - response = self.client.policy_set_definitions.list_built_in( - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_create_or_update_at_management_group(self, resource_group): - response = await self.client.policy_set_definitions.create_or_update_at_management_group( - management_group_id="str", - policy_set_definition_name="str", - parameters={ - "description": "str", - "displayName": "str", - "id": "str", - "metadata": {}, - "name": "str", - "parameters": { - "str": { - "allowedValues": [{}], - "defaultValue": {}, - "metadata": { - "assignPermissions": bool, - "description": "str", - "displayName": "str", - "strongType": "str", - }, - "schema": {}, - "type": "str", - } - }, - "policyDefinitionGroups": [ - { - "name": "str", - "additionalMetadataId": "str", - "category": "str", - "description": "str", - "displayName": "str", - } - ], - "policyDefinitions": [ - { - "policyDefinitionId": "str", - "definitionVersion": "str", - "effectiveDefinitionVersion": "str", - "groupNames": ["str"], - "latestDefinitionVersion": "str", - "parameters": {"str": {"value": {}}}, - "policyDefinitionReferenceId": "str", - } - ], - "policyType": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - "version": "str", - "versions": ["str"], - }, - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_delete_at_management_group(self, resource_group): - response = await self.client.policy_set_definitions.delete_at_management_group( - management_group_id="str", - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_get_at_management_group(self, resource_group): - response = await self.client.policy_set_definitions.get_at_management_group( - management_group_id="str", - policy_set_definition_name="str", - api_version="2023-04-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_set_definitions_list_by_management_group(self, resource_group): - response = self.client.policy_set_definitions.list_by_management_group( - management_group_id="str", - api_version="2023-04-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations.py deleted file mode 100644 index e09d26b19c57..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyVariableValuesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_delete(self, resource_group): - response = self.client.variable_values.delete( - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_create_or_update(self, resource_group): - response = self.client.variable_values.create_or_update( - variable_name="str", - variable_value_name="str", - parameters={ - "values": [{"columnName": "str", "columnValue": {}}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_get(self, resource_group): - response = self.client.variable_values.get( - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_list(self, resource_group): - response = self.client.variable_values.list( - variable_name="str", - api_version="2022-08-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_list_for_management_group(self, resource_group): - response = self.client.variable_values.list_for_management_group( - management_group_id="str", - variable_name="str", - api_version="2022-08-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_delete_at_management_group(self, resource_group): - response = self.client.variable_values.delete_at_management_group( - management_group_id="str", - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_create_or_update_at_management_group(self, resource_group): - response = self.client.variable_values.create_or_update_at_management_group( - management_group_id="str", - variable_name="str", - variable_value_name="str", - parameters={ - "values": [{"columnName": "str", "columnValue": {}}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variable_values_get_at_management_group(self, resource_group): - response = self.client.variable_values.get_at_management_group( - management_group_id="str", - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations_async.py deleted file mode 100644 index a7bbd7e294fc..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variable_values_operations_async.py +++ /dev/null @@ -1,146 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyVariableValuesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_delete(self, resource_group): - response = await self.client.variable_values.delete( - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_create_or_update(self, resource_group): - response = await self.client.variable_values.create_or_update( - variable_name="str", - variable_value_name="str", - parameters={ - "values": [{"columnName": "str", "columnValue": {}}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_get(self, resource_group): - response = await self.client.variable_values.get( - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_list(self, resource_group): - response = self.client.variable_values.list( - variable_name="str", - api_version="2022-08-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_list_for_management_group(self, resource_group): - response = self.client.variable_values.list_for_management_group( - management_group_id="str", - variable_name="str", - api_version="2022-08-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_delete_at_management_group(self, resource_group): - response = await self.client.variable_values.delete_at_management_group( - management_group_id="str", - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_create_or_update_at_management_group(self, resource_group): - response = await self.client.variable_values.create_or_update_at_management_group( - management_group_id="str", - variable_name="str", - variable_value_name="str", - parameters={ - "values": [{"columnName": "str", "columnValue": {}}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variable_values_get_at_management_group(self, resource_group): - response = await self.client.variable_values.get_at_management_group( - management_group_id="str", - variable_name="str", - variable_value_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations.py deleted file mode 100644 index 19f865cb0853..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations.py +++ /dev/null @@ -1,137 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyVariablesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_delete(self, resource_group): - response = self.client.variables.delete( - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_create_or_update(self, resource_group): - response = self.client.variables.create_or_update( - variable_name="str", - parameters={ - "columns": [{"columnName": "str"}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_get(self, resource_group): - response = self.client.variables.get( - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_delete_at_management_group(self, resource_group): - response = self.client.variables.delete_at_management_group( - management_group_id="str", - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_create_or_update_at_management_group(self, resource_group): - response = self.client.variables.create_or_update_at_management_group( - management_group_id="str", - variable_name="str", - parameters={ - "columns": [{"columnName": "str"}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_get_at_management_group(self, resource_group): - response = self.client.variables.get_at_management_group( - management_group_id="str", - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_list(self, resource_group): - response = self.client.variables.list( - api_version="2022-08-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_variables_list_for_management_group(self, resource_group): - response = self.client.variables.list_for_management_group( - management_group_id="str", - api_version="2022-08-01-preview", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations_async.py deleted file mode 100644 index df7d9ca1d591..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_policy_variables_operations_async.py +++ /dev/null @@ -1,138 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPolicyVariablesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_delete(self, resource_group): - response = await self.client.variables.delete( - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_create_or_update(self, resource_group): - response = await self.client.variables.create_or_update( - variable_name="str", - parameters={ - "columns": [{"columnName": "str"}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_get(self, resource_group): - response = await self.client.variables.get( - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_delete_at_management_group(self, resource_group): - response = await self.client.variables.delete_at_management_group( - management_group_id="str", - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_create_or_update_at_management_group(self, resource_group): - response = await self.client.variables.create_or_update_at_management_group( - management_group_id="str", - variable_name="str", - parameters={ - "columns": [{"columnName": "str"}], - "id": "str", - "name": "str", - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, - "type": "str", - }, - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_get_at_management_group(self, resource_group): - response = await self.client.variables.get_at_management_group( - management_group_id="str", - variable_name="str", - api_version="2022-08-01-preview", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_list(self, resource_group): - response = self.client.variables.list( - api_version="2022-08-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_variables_list_for_management_group(self, resource_group): - response = self.client.variables.list_for_management_group( - management_group_id="str", - api_version="2022-08-01-preview", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations.py deleted file mode 100644 index c0ffcb253d5b..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.resources.v2022_09_01 import ResourceManagementClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourceManagementDeploymentOperationsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourceManagementClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_get_at_scope(self, resource_group): - response = self.client.deployment_operations.get_at_scope( - scope="str", - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_list_at_scope(self, resource_group): - response = self.client.deployment_operations.list_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_get_at_tenant_scope(self, resource_group): - response = self.client.deployment_operations.get_at_tenant_scope( - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_list_at_tenant_scope(self, resource_group): - response = self.client.deployment_operations.list_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_get_at_management_group_scope(self, resource_group): - response = self.client.deployment_operations.get_at_management_group_scope( - group_id="str", - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_list_at_management_group_scope(self, resource_group): - response = self.client.deployment_operations.list_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_get_at_subscription_scope(self, resource_group): - response = self.client.deployment_operations.get_at_subscription_scope( - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_list_at_subscription_scope(self, resource_group): - response = self.client.deployment_operations.list_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_get(self, resource_group): - response = self.client.deployment_operations.get( - resource_group_name=resource_group.name, - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployment_operations_list(self, resource_group): - response = self.client.deployment_operations.list( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations_async.py deleted file mode 100644 index 29902f86d0a0..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployment_operations_operations_async.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.resources.v2022_09_01.aio import ResourceManagementClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourceManagementDeploymentOperationsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourceManagementClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_get_at_scope(self, resource_group): - response = await self.client.deployment_operations.get_at_scope( - scope="str", - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_list_at_scope(self, resource_group): - response = self.client.deployment_operations.list_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_get_at_tenant_scope(self, resource_group): - response = await self.client.deployment_operations.get_at_tenant_scope( - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_list_at_tenant_scope(self, resource_group): - response = self.client.deployment_operations.list_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_get_at_management_group_scope(self, resource_group): - response = await self.client.deployment_operations.get_at_management_group_scope( - group_id="str", - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_list_at_management_group_scope(self, resource_group): - response = self.client.deployment_operations.list_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_get_at_subscription_scope(self, resource_group): - response = await self.client.deployment_operations.get_at_subscription_scope( - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_list_at_subscription_scope(self, resource_group): - response = self.client.deployment_operations.list_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_get(self, resource_group): - response = await self.client.deployment_operations.get( - resource_group_name=resource_group.name, - deployment_name="str", - operation_id="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployment_operations_list(self, resource_group): - response = self.client.deployment_operations.list( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations.py deleted file mode 100644 index e7842471096f..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations.py +++ /dev/null @@ -1,885 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.resources.v2022_09_01 import ResourceManagementClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourceManagementDeploymentsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourceManagementClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_delete_at_scope(self, resource_group): - response = self.client.deployments.begin_delete_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_check_existence_at_scope(self, resource_group): - response = self.client.deployments.check_existence_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_create_or_update_at_scope(self, resource_group): - response = self.client.deployments.begin_create_or_update_at_scope( - scope="str", - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_get_at_scope(self, resource_group): - response = self.client.deployments.get_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_cancel_at_scope(self, resource_group): - response = self.client.deployments.cancel_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_validate_at_scope(self, resource_group): - response = self.client.deployments.begin_validate_at_scope( - scope="str", - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_export_template_at_scope(self, resource_group): - response = self.client.deployments.export_template_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_list_at_scope(self, resource_group): - response = self.client.deployments.list_at_scope( - scope="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_delete_at_tenant_scope(self, resource_group): - response = self.client.deployments.begin_delete_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_check_existence_at_tenant_scope(self, resource_group): - response = self.client.deployments.check_existence_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_create_or_update_at_tenant_scope(self, resource_group): - response = self.client.deployments.begin_create_or_update_at_tenant_scope( - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_get_at_tenant_scope(self, resource_group): - response = self.client.deployments.get_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_cancel_at_tenant_scope(self, resource_group): - response = self.client.deployments.cancel_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_validate_at_tenant_scope(self, resource_group): - response = self.client.deployments.begin_validate_at_tenant_scope( - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_what_if_at_tenant_scope(self, resource_group): - response = self.client.deployments.begin_what_if_at_tenant_scope( - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_export_template_at_tenant_scope(self, resource_group): - response = self.client.deployments.export_template_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_list_at_tenant_scope(self, resource_group): - response = self.client.deployments.list_at_tenant_scope( - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_delete_at_management_group_scope(self, resource_group): - response = self.client.deployments.begin_delete_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_check_existence_at_management_group_scope(self, resource_group): - response = self.client.deployments.check_existence_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_create_or_update_at_management_group_scope(self, resource_group): - response = self.client.deployments.begin_create_or_update_at_management_group_scope( - group_id="str", - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_get_at_management_group_scope(self, resource_group): - response = self.client.deployments.get_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_cancel_at_management_group_scope(self, resource_group): - response = self.client.deployments.cancel_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_validate_at_management_group_scope(self, resource_group): - response = self.client.deployments.begin_validate_at_management_group_scope( - group_id="str", - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_what_if_at_management_group_scope(self, resource_group): - response = self.client.deployments.begin_what_if_at_management_group_scope( - group_id="str", - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_export_template_at_management_group_scope(self, resource_group): - response = self.client.deployments.export_template_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_list_at_management_group_scope(self, resource_group): - response = self.client.deployments.list_at_management_group_scope( - group_id="str", - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_delete_at_subscription_scope(self, resource_group): - response = self.client.deployments.begin_delete_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_check_existence_at_subscription_scope(self, resource_group): - response = self.client.deployments.check_existence_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_create_or_update_at_subscription_scope(self, resource_group): - response = self.client.deployments.begin_create_or_update_at_subscription_scope( - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_get_at_subscription_scope(self, resource_group): - response = self.client.deployments.get_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_cancel_at_subscription_scope(self, resource_group): - response = self.client.deployments.cancel_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_validate_at_subscription_scope(self, resource_group): - response = self.client.deployments.begin_validate_at_subscription_scope( - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_what_if_at_subscription_scope(self, resource_group): - response = self.client.deployments.begin_what_if_at_subscription_scope( - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - "location": "str", - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_export_template_at_subscription_scope(self, resource_group): - response = self.client.deployments.export_template_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_list_at_subscription_scope(self, resource_group): - response = self.client.deployments.list_at_subscription_scope( - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_delete(self, resource_group): - response = self.client.deployments.begin_delete( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_check_existence(self, resource_group): - response = self.client.deployments.check_existence( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_create_or_update(self, resource_group): - response = self.client.deployments.begin_create_or_update( - resource_group_name=resource_group.name, - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_get(self, resource_group): - response = self.client.deployments.get( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_cancel(self, resource_group): - response = self.client.deployments.cancel( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_validate(self, resource_group): - response = self.client.deployments.begin_validate( - resource_group_name=resource_group.name, - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_begin_what_if(self, resource_group): - response = self.client.deployments.begin_what_if( - resource_group_name=resource_group.name, - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - "location": "str", - }, - api_version="2022-09-01", - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_export_template(self, resource_group): - response = self.client.deployments.export_template( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_list_by_resource_group(self, resource_group): - response = self.client.deployments.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2022-09-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_deployments_calculate_template_hash(self, resource_group): - response = self.client.deployments.calculate_template_hash( - template={}, - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations_async.py deleted file mode 100644 index db0ccbd4d05a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_management_deployments_operations_async.py +++ /dev/null @@ -1,924 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.resources.v2022_09_01.aio import ResourceManagementClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourceManagementDeploymentsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourceManagementClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_delete_at_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_delete_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_check_existence_at_scope(self, resource_group): - response = await self.client.deployments.check_existence_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_create_or_update_at_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_create_or_update_at_scope( - scope="str", - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_get_at_scope(self, resource_group): - response = await self.client.deployments.get_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_cancel_at_scope(self, resource_group): - response = await self.client.deployments.cancel_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_validate_at_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_validate_at_scope( - scope="str", - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_export_template_at_scope(self, resource_group): - response = await self.client.deployments.export_template_at_scope( - scope="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_list_at_scope(self, resource_group): - response = self.client.deployments.list_at_scope( - scope="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_delete_at_tenant_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_delete_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_check_existence_at_tenant_scope(self, resource_group): - response = await self.client.deployments.check_existence_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_create_or_update_at_tenant_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_create_or_update_at_tenant_scope( - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_get_at_tenant_scope(self, resource_group): - response = await self.client.deployments.get_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_cancel_at_tenant_scope(self, resource_group): - response = await self.client.deployments.cancel_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_validate_at_tenant_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_validate_at_tenant_scope( - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_what_if_at_tenant_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_what_if_at_tenant_scope( - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_export_template_at_tenant_scope(self, resource_group): - response = await self.client.deployments.export_template_at_tenant_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_list_at_tenant_scope(self, resource_group): - response = self.client.deployments.list_at_tenant_scope( - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_delete_at_management_group_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_delete_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_check_existence_at_management_group_scope(self, resource_group): - response = await self.client.deployments.check_existence_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_create_or_update_at_management_group_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_create_or_update_at_management_group_scope( - group_id="str", - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_get_at_management_group_scope(self, resource_group): - response = await self.client.deployments.get_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_cancel_at_management_group_scope(self, resource_group): - response = await self.client.deployments.cancel_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_validate_at_management_group_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_validate_at_management_group_scope( - group_id="str", - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_what_if_at_management_group_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_what_if_at_management_group_scope( - group_id="str", - deployment_name="str", - parameters={ - "location": "str", - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_export_template_at_management_group_scope(self, resource_group): - response = await self.client.deployments.export_template_at_management_group_scope( - group_id="str", - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_list_at_management_group_scope(self, resource_group): - response = self.client.deployments.list_at_management_group_scope( - group_id="str", - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_delete_at_subscription_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_delete_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_check_existence_at_subscription_scope(self, resource_group): - response = await self.client.deployments.check_existence_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_create_or_update_at_subscription_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_create_or_update_at_subscription_scope( - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_get_at_subscription_scope(self, resource_group): - response = await self.client.deployments.get_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_cancel_at_subscription_scope(self, resource_group): - response = await self.client.deployments.cancel_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_validate_at_subscription_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_validate_at_subscription_scope( - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_what_if_at_subscription_scope(self, resource_group): - response = await ( - await self.client.deployments.begin_what_if_at_subscription_scope( - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - "location": "str", - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_export_template_at_subscription_scope(self, resource_group): - response = await self.client.deployments.export_template_at_subscription_scope( - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_list_at_subscription_scope(self, resource_group): - response = self.client.deployments.list_at_subscription_scope( - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_delete(self, resource_group): - response = await ( - await self.client.deployments.begin_delete( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_check_existence(self, resource_group): - response = await self.client.deployments.check_existence( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_create_or_update(self, resource_group): - response = await ( - await self.client.deployments.begin_create_or_update( - resource_group_name=resource_group.name, - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_get(self, resource_group): - response = await self.client.deployments.get( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_cancel(self, resource_group): - response = await self.client.deployments.cancel( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_validate(self, resource_group): - response = await ( - await self.client.deployments.begin_validate( - resource_group_name=resource_group.name, - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - }, - "location": "str", - "tags": {"str": "str"}, - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_begin_what_if(self, resource_group): - response = await ( - await self.client.deployments.begin_what_if( - resource_group_name=resource_group.name, - deployment_name="str", - parameters={ - "properties": { - "mode": "str", - "debugSetting": {"detailLevel": "str"}, - "expressionEvaluationOptions": {"scope": "str"}, - "onErrorDeployment": {"deploymentName": "str", "type": "str"}, - "parameters": { - "str": { - "reference": {"keyVault": {"id": "str"}, "secretName": "str", "secretVersion": "str"}, - "value": {}, - } - }, - "parametersLink": {"uri": "str", "contentVersion": "str"}, - "template": {}, - "templateLink": { - "contentVersion": "str", - "id": "str", - "queryString": "str", - "relativePath": "str", - "uri": "str", - }, - "whatIfSettings": {"resultFormat": "str"}, - }, - "location": "str", - }, - api_version="2022-09-01", - ) - ).result() # call '.result()' to poll until service return final result - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_export_template(self, resource_group): - response = await self.client.deployments.export_template( - resource_group_name=resource_group.name, - deployment_name="str", - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_list_by_resource_group(self, resource_group): - response = self.client.deployments.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2022-09-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_deployments_calculate_template_hash(self, resource_group): - response = await self.client.deployments.calculate_template_hash( - template={}, - api_version="2022-09-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations.py deleted file mode 100644 index 376f6e410d0d..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourcePrivateLinkPrivateLinkAssociationOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_private_link_association_put(self, resource_group): - response = self.client.private_link_association.put( - group_id="str", - pla_id="str", - parameters={"properties": {"privateLink": "str", "publicNetworkAccess": "str"}}, - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_private_link_association_get(self, resource_group): - response = self.client.private_link_association.get( - group_id="str", - pla_id="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_private_link_association_delete(self, resource_group): - response = self.client.private_link_association.delete( - group_id="str", - pla_id="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_private_link_association_list(self, resource_group): - response = self.client.private_link_association.list( - group_id="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations_async.py deleted file mode 100644 index 6b65996b500a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_private_link_association_operations_async.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.privatelinks.aio import ResourcePrivateLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourcePrivateLinkPrivateLinkAssociationOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_private_link_association_put(self, resource_group): - response = await self.client.private_link_association.put( - group_id="str", - pla_id="str", - parameters={"properties": {"privateLink": "str", "publicNetworkAccess": "str"}}, - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_private_link_association_get(self, resource_group): - response = await self.client.private_link_association.get( - group_id="str", - pla_id="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_private_link_association_delete(self, resource_group): - response = await self.client.private_link_association.delete( - group_id="str", - pla_id="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_private_link_association_list(self, resource_group): - response = await self.client.private_link_association.list( - group_id="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations.py deleted file mode 100644 index f6fd1f5fdd00..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourcePrivateLinkResourceManagementPrivateLinkOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_put(self, resource_group): - response = self.client.resource_management_private_link.put( - resource_group_name=resource_group.name, - rmpl_name="str", - parameters={"location": "str"}, - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_get(self, resource_group): - response = self.client.resource_management_private_link.get( - resource_group_name=resource_group.name, - rmpl_name="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_delete(self, resource_group): - response = self.client.resource_management_private_link.delete( - resource_group_name=resource_group.name, - rmpl_name="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_list(self, resource_group): - response = self.client.resource_management_private_link.list( - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_list_by_resource_group(self, resource_group): - response = self.client.resource_management_private_link.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py deleted file mode 100644 index b21f7a1c97a5..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_resource_private_link_resource_management_private_link_operations_async.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.privatelinks.aio import ResourcePrivateLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestResourcePrivateLinkResourceManagementPrivateLinkOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_put(self, resource_group): - response = await self.client.resource_management_private_link.put( - resource_group_name=resource_group.name, - rmpl_name="str", - parameters={"location": "str"}, - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_get(self, resource_group): - response = await self.client.resource_management_private_link.get( - resource_group_name=resource_group.name, - rmpl_name="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_delete(self, resource_group): - response = await self.client.resource_management_private_link.delete( - resource_group_name=resource_group.name, - rmpl_name="str", - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_list(self, resource_group): - response = await self.client.resource_management_private_link.list( - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_list_by_resource_group(self, resource_group): - response = await self.client.resource_management_private_link.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2020-05-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription.py deleted file mode 100644 index 44687506daed..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscription(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_check_resource_name(self, resource_group): - response = self.client.check_resource_name( - api_version="2022-12-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_async.py deleted file mode 100644 index df24a5a1b8e6..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions.aio import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_check_resource_name(self, resource_group): - response = await self.client.check_resource_name( - api_version="2022-12-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations.py deleted file mode 100644 index 854df62b3cea..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_operations_list(self, resource_group): - response = self.client.operations.list( - api_version="2022-12-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations_async.py deleted file mode 100644 index a4df00309613..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_operations_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions.aio import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_operations_list(self, resource_group): - response = self.client.operations.list( - api_version="2022-12-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations.py deleted file mode 100644 index b02b4addda74..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations.py +++ /dev/null @@ -1,63 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionSubscriptionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscriptions_list_locations(self, resource_group): - response = self.client.subscriptions.list_locations( - subscription_id="str", - api_version="2022-12-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscriptions_get(self, resource_group): - response = self.client.subscriptions.get( - subscription_id="str", - api_version="2022-12-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscriptions_list(self, resource_group): - response = self.client.subscriptions.list( - api_version="2022-12-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscriptions_check_zone_peers(self, resource_group): - response = self.client.subscriptions.check_zone_peers( - subscription_id="str", - parameters={"location": "str", "subscriptionIds": ["str"]}, - api_version="2022-12-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations_async.py deleted file mode 100644 index a615ee0a8f1a..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_subscriptions_operations_async.py +++ /dev/null @@ -1,64 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions.aio import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionSubscriptionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscriptions_list_locations(self, resource_group): - response = self.client.subscriptions.list_locations( - subscription_id="str", - api_version="2022-12-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscriptions_get(self, resource_group): - response = await self.client.subscriptions.get( - subscription_id="str", - api_version="2022-12-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscriptions_list(self, resource_group): - response = self.client.subscriptions.list( - api_version="2022-12-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscriptions_check_zone_peers(self, resource_group): - response = await self.client.subscriptions.check_zone_peers( - subscription_id="str", - parameters={"location": "str", "subscriptionIds": ["str"]}, - api_version="2022-12-01", - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations.py deleted file mode 100644 index 6a9cf04ca45e..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionTenantsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_tenants_list(self, resource_group): - response = self.client.tenants.list( - api_version="2022-12-01", - ) - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations_async.py b/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations_async.py deleted file mode 100644 index cd39b2d42d63..000000000000 --- a/sdk/resources/azure-mgmt-resource/generated_tests/test_subscription_tenants_operations_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions.aio import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestSubscriptionTenantsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_tenants_list(self, resource_group): - response = self.client.tenants.list( - api_version="2022-12-01", - ) - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/resources/azure-mgmt-resource/pyproject.toml b/sdk/resources/azure-mgmt-resource/pyproject.toml index d7e1e07a7653..c30a680d2e02 100644 --- a/sdk/resources/azure-mgmt-resource/pyproject.toml +++ b/sdk/resources/azure-mgmt-resource/pyproject.toml @@ -13,7 +13,7 @@ authors = [ description = "Microsoft Azure Resource Management Client Library for Python" license = "MIT" classifiers = [ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", @@ -78,7 +78,7 @@ verifytypes = false package_name = "azure-mgmt-resource" package_pprint_name = "Resource Management" package_doc_id = "resources?view=azure-python-preview" -is_stable = false +is_stable = true need_msrestazure = false need_azuremgmtcore = true sample_link = "" diff --git a/sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py b/sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py deleted file mode 100644 index 5a5549039a05..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_async_test.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.databoundaries.aio import DataBoundaryMgmtClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestDataBoundaryMgmtDataBoundariesOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(DataBoundaryMgmtClient, is_async=True) - - @pytest.mark.skip(reason="can not pass") - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_put(self, resource_group): - response = await self.client.data_boundaries.put( - default="default", - data_boundary_definition={"properties": {"dataBoundary": "EU"}}, - ) - - assert response - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_get_tenant(self, resource_group): - response = await self.client.data_boundaries.get_tenant( - default="default", - ) - - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py b/sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py deleted file mode 100644 index cb70cbac1454..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_data_boundary_mgmt_data_boundaries_operations_test.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.databoundaries import DataBoundaryMgmtClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestDataBoundaryMgmtDataBoundariesOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(DataBoundaryMgmtClient) - - @pytest.mark.skip(reason="can not pass") - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_put(self, resource_group): - response = self.client.data_boundaries.put( - default="default", - data_boundary_definition={"properties": {"dataBoundary": "EU"}}, - ) - - assert response - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_get_tenant(self, resource_group): - response = self.client.data_boundaries.get_tenant( - default="default", - ) - - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_changes_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_changes_test.py deleted file mode 100644 index 54f0f74f07ed..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_changes_test.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mgmt.resource.resources import ResourceManagementClient -from azure.mgmt.resource.changes import ChangesClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLinks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.client = self.create_mgmt_client(ChangesClient) - self.resource_client = self.create_mgmt_client(ResourceManagementClient) - - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_changes_list(self, resource_group): - resource_name = self.get_resource_name("test_resource") - - create_result = self.resource_client.resources.begin_create_or_update( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - parameters={"location": "eastus"}, - api_version="2019-07-01", - ) - - result = list( - self.client.changes.list( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - resource_type="availabilitySets", - resource_name=resource_name, - ) - ) - - assert len(result) > 0 - - delete_result = self.resource_client.resources.begin_delete( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - api_version="2019-07-01", - ) - delete_result.wait() diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_deployment_scripts_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_deployment_scripts_test.py deleted file mode 100644 index 5f36d2c312b1..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_deployment_scripts_test.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -# covered ops: -# deployment_scripts: 8/8 - -import unittest - -import azure.core.exceptions -import azure.mgmt.resource -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceDeploymentScript(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.script_client = self.create_mgmt_client( - azure.mgmt.resource.deploymentscripts.DeploymentScriptsClient, api_version="2019-10-01-preview" - ) - - # if self.is_live: - # from azure.mgmt.msi import ManagedServiceIdentityClient - # self.msi_client = self.create_mgmt_client( - # ManagedServiceIdentityClient, - # ) - - @pytest.mark.skip(reason="authorization failed, need to add white_list") - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_deployment_scripts(self, resource_group, location): - SUBSCRIPTION = self.get_settings_value("SUBSCRIPTION_ID") - script_name = "scripttest" - identity_name = "uai" - - # Create identity - if self.is_live: - self.msi_client.user_assigned_identities.create_or_update( - resource_group.name, identity_name, {"location": "westus", "tags": {"key1": "value1"}} - ) - - # Create script - result = self.script_client.deployment_scripts.begin_create( - resource_group.name, - script_name, - { - "kind": "AzurePowerShell", - "location": "westus", - "identity": { - "type": "UserAssigned", - "user_assigned_identities": { - "/subscriptions/" - + SUBSCRIPTION - + "/resourceGroups/" - + resource_group.name - + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/uai": {} - }, - }, - "azPowerShellVersion": "3.0", - "scriptContent": "Param([string]$Location,[string]$Name) $deploymentScriptOutputs['test'] = 'value' Get-AzResourceGroup -Location $Location -Name $Name", - "arguments": "-Location 'westus' -Name \"*rg2\"", - # "supportingScriptUris": [ - # "https://uri1.to.supporting.script", - # "https://uri2.to.supporting.script" - # ], - "retentionInterval": "PT26H", - "timeout": "PT30M", - "cleanupPreference": "Always", - }, - ) - - # azure.core.exceptions.HttpResponseError: Operation returned an invalid status 'OK' - try: - result.result() - except azure.core.exceptions.HttpResponseError: - pass - - # Update script tags - BODY = {"tags": {"key1": "value1"}} - self.script_client.deployment_scripts.update(resource_group.name, script_name, BODY) - - # Get script - self.script_client.deployment_scripts.get(resource_group.name, script_name) - - # List scripts by subscription - self.script_client.deployment_scripts.list_by_subscription() - - # List scripts by resource group - self.script_client.deployment_scripts.list_by_resource_group(resource_group.name) - - # Get script logs default - self.script_client.deployment_scripts.get_logs_default(resource_group.name, script_name) - - # Get script logs - self.script_client.deployment_scripts.get_logs(resource_group.name, script_name) - - # Delete script - self.script_client.deployment_scripts.delete(resource_group.name, script_name) - - -# ------------------------------------------------------------------------------ -if __name__ == "__main__": - unittest.main() diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_feature_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_feature_test.py deleted file mode 100644 index f90ec00ac69e..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_feature_test.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding: utf-8 -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mgmt.resource.features import FeatureClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLinks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.client = self.create_mgmt_client(FeatureClient) - - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_features_list(self): - result = list(self.client.features.list_all()) - assert len(result) > 0 diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_links_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_links_test.py deleted file mode 100644 index 86adef03a0f9..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_links_test.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mgmt.resource.links import ManagementLinkClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLinks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.client = self.create_mgmt_client(ManagementLinkClient) - - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_links(self): - list(self.client.resource_links.list_at_subscription()) diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_locks_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_locks_test.py deleted file mode 100644 index 1cf929ecb84c..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_locks_test.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import unittest -import pytest - -from azure.mgmt.resource.resources import ResourceManagementClient -from azure.mgmt.resource.locks import ManagementLockClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLocks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.locks_client = self.create_mgmt_client(ManagementLockClient) - - self.resource_client = self.create_mgmt_client(ResourceManagementClient) - - @pytest.mark.skip(reason="authorization failed, need to add white_list") - @recorded_by_proxy - def test_locks_at_subscription_level(self): - lock_name = "pylockrg" - - lock = self.locks_client.management_locks.create_or_update_at_subscription_level( - lock_name, {"level": "CanNotDelete"} - ) - assert lock is not None - - self.locks_client.management_locks.get_at_subscription_level(lock_name) - - locks = list(self.locks_client.management_locks.list_at_subscription_level()) - - lock = self.locks_client.management_locks.delete_at_subscription_level(lock_name) - - @pytest.mark.skip(reason="authorization failed, need to add white_list") - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_locks_by_scope(self, resource_group, location): - lock_name = "pylockrg" - SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") - resource_name = self.get_resource_name("pytestavset") - - resource_id = "/subscriptions/{guid}/resourceGroups/{resourcegroupname}/providers/{resourceprovidernamespace}/{resourcetype}/{resourcename}".format( - guid=SUBSCRIPTION_ID, - resourcegroupname=resource_group.name, - resourceprovidernamespace="Microsoft.Compute", - resourcetype="availabilitySets", - resourcename=resource_name, - ) - - create_result = self.resource_client.resources.begin_create_or_update_by_id( - resource_id, parameters={"location": location}, api_version="2019-07-01" - ) - - lock = self.locks_client.management_locks.create_or_update_by_scope( - resource_id, lock_name, {"level": "CanNotDelete"} - ) - - self.locks_client.management_locks.get_by_scope(resource_id, lock_name) - - self.locks_client.management_locks.list_by_scope(resource_id) - - self.locks_client.management_locks.delete_by_scope(resource_id, lock_name) - - result = self.resource_client.resources.begin_delete_by_id(resource_id, api_version="2019-07-01") - result = result.result() - - @pytest.mark.skip(reason="authorization failed, need to add white_list") - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_locks_at_resource_level(self, resource_group, location): - lock_name = "pylockrg" - resource_name = self.get_resource_name("pytestavset") - - # create resource - create_result = self.resource_client.resources.begin_create_or_update( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - parameters={"location": location}, - api_version="2019-07-01", - ) - - lock = self.locks_client.management_locks.create_or_update_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - lock_name=lock_name, - parameters={"level": "CanNotDelete"}, - ) - assert lock is not None - - self.locks_client.management_locks.get_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - lock_name=lock_name, - ) - - locks = list( - self.locks_client.management_locks.list_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - ) - ) - assert len(locks) == 1 - - lock = self.locks_client.management_locks.delete_at_resource_level( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - lock_name=lock_name, - ) - - # delete resource - delete_result = self.resource_client.resources.begin_delete( - resource_group_name=resource_group.name, - resource_provider_namespace="Microsoft.Compute", - parent_resource_path="", - resource_type="availabilitySets", - resource_name=resource_name, - api_version="2019-07-01", - ) - delete_result.wait() - - @pytest.mark.skip(reason="authorization failed, need to add white_list") - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_locks_at_resource_group_level(self, resource_group, location): - lock_name = "pylockrg" - - lock = self.locks_client.management_locks.create_or_update_at_resource_group_level( - resource_group.name, lock_name, {"level": "CanNotDelete"} - ) - assert lock is not None - - self.locks_client.management_locks.get_at_resource_group_level(resource_group.name, lock_name) - - locks = list(self.locks_client.management_locks.list_at_resource_group_level(resource_group.name)) - assert len(locks) == 1 - - lock = self.locks_client.management_locks.delete_at_resource_group_level(resource_group.name, lock_name) - - @recorded_by_proxy - def test_operations(self): - self.locks_client.authorization_operations.list() - - -# ------------------------------------------------------------------------------ -if __name__ == "__main__": - unittest.main() diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_managed_application_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_managed_application_test.py deleted file mode 100644 index c9897538d1f9..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_managed_application_test.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding: utf-8 -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mgmt.resource.managedapplications import ApplicationClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLinks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.client = self.create_mgmt_client(ApplicationClient) - - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_application_list(self): - result = list(self.client.applications.list_by_subscription()) diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_policy_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_policy_test.py deleted file mode 100644 index fb2ae2de3b70..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_policy_test.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding: utf-8 -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mgmt.resource.policy import PolicyClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLinks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_policy_list(self): - result = list(self.client.policy_assignments.list()) - assert len(result) > 0 diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_private_link_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_private_link_test.py deleted file mode 100644 index 535d596db07a..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_private_link_test.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding: utf-8 -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceLinks(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient) - - @RandomNameResourceGroupPreparer() - @recorded_by_proxy - def test_private_link_list(self): - result = self.client.resource_management_private_link.list() diff --git a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_subscriptions_test.py b/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_subscriptions_test.py deleted file mode 100644 index 91d54e3d910f..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_mgmt_resource_subscriptions_test.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -# covered ops: -# operations: 1/1 -# subscriptions: 3/3 -# tenants: 1/1 - -import unittest - -import azure.mgmt.resource.subscriptions -from devtools_testutils import AzureMgmtRecordedTestCase, recorded_by_proxy -import pytest - - -@pytest.mark.live_test_only -class TestMgmtResourceSubscriptions(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - self.subscriptions_client = self.create_mgmt_client(azure.mgmt.resource.subscriptions.SubscriptionClient) - - @recorded_by_proxy - def test_subscriptions(self): - subs = list(self.subscriptions_client.subscriptions.list()) - assert len(subs) >= 0 - - # [ZIM] temporarily disabled - # assert all(isinstance(v, azure.mgmt.resource.subscriptions.models.Subscription) for v in subs) - - subscription_id = self.get_settings_value("SUBSCRIPTION_ID") - locations = list(self.subscriptions_client.subscriptions.list_locations(subscription_id)) - assert len(locations) >= 0 - - # [ZIM] temporarily disabled - # assert all(isinstance(v, azure.mgmt.resource.subscriptions.models.Location) for v in locations) - - sub = self.subscriptions_client.subscriptions.get(subscription_id) - assert sub.subscription_id == subscription_id - - @recorded_by_proxy - def test_tenants(self): - tenants = list(self.subscriptions_client.tenants.list()) - assert len(tenants) >= 0 - - # [ZIM] temporarily disabled - # assert all(isinstance(v, azure.mgmt.resource.subscriptions.models.TenantIdDescription) for v in tenants) - - @recorded_by_proxy - def test_operations(self): - self.subscriptions_client.operations.list() - - -# ------------------------------------------------------------------------------ -if __name__ == "__main__": - unittest.main() diff --git a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_async_test.py b/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_async_test.py deleted file mode 100644 index 3ad516c08d62..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_async_test.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestPolicyPolicyAssignmentsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_list_for_resource_group(self, resource_group): - response = self.client.policy_assignments.list_for_resource_group( - resource_group_name=resource_group.name, - ) - result = [r async for r in response] - assert result - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_assignments_list(self, resource_group): - response = self.client.policy_assignments.list() - result = [r async for r in response] - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_test.py b/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_test.py deleted file mode 100644 index 5a6d62700be3..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_assignments_operations_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestPolicyPolicyAssignmentsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_list_for_resource_group(self, resource_group): - response = self.client.policy_assignments.list_for_resource_group( - resource_group_name=resource_group.name, - ) - result = [r for r in response] - assert result - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_assignments_list(self, resource_group): - response = self.client.policy_assignments.list() - result = [r for r in response] - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_async_test.py b/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_async_test.py deleted file mode 100644 index 32d331e6880d..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_async_test.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy.aio import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestPolicyPolicyDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_list(self, resource_group): - response = self.client.policy_definitions.list() - result = [r async for r in response] - assert response - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_policy_definitions_list_built_in(self, resource_group): - response = self.client.policy_definitions.list_built_in() - result = [r async for r in response] - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_test.py b/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_test.py deleted file mode 100644 index 93ec578d34c9..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_policy_policy_definitions_operations_test.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.policy import PolicyClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestPolicyPolicyDefinitionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(PolicyClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_list(self, resource_group): - response = self.client.policy_definitions.list() - result = [r for r in response] - assert response - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_policy_definitions_list_built_in(self, resource_group): - response = self.client.policy_definitions.list_built_in() - result = [r for r in response] - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py b/sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py deleted file mode 100644 index a46e14429642..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_async_test.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.privatelinks.aio import ResourcePrivateLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestResourcePrivateLinkResourceManagementPrivateLinkOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_list(self, resource_group): - response = await self.client.resource_management_private_link.list() - - assert response - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_resource_management_private_link_list_by_resource_group(self, resource_group): - response = await self.client.resource_management_private_link.list_by_resource_group( - resource_group_name=resource_group.name, - ) - result = [r for r in response.value] - assert result == [] diff --git a/sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_test.py b/sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_test.py deleted file mode 100644 index 4d27643b1b0d..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_resource_private_link_resource_management_private_link_operations_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.privatelinks import ResourcePrivateLinkClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestResourcePrivateLinkResourceManagementPrivateLinkOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(ResourcePrivateLinkClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_list(self, resource_group): - response = self.client.resource_management_private_link.list() - - assert response - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_resource_management_private_link_list_by_resource_group(self, resource_group): - response = self.client.resource_management_private_link.list_by_resource_group( - resource_group_name=resource_group.name, - ) - result = [r for r in response.value] - assert result == [] diff --git a/sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_async_test.py b/sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_async_test.py deleted file mode 100644 index 0fe3ebed625c..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_async_test.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions.aio import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer -from devtools_testutils.aio import recorded_by_proxy_async - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestSubscriptionSubscriptionsOperationsAsync(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient, is_async=True) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_subscriptions_list(self, resource_group): - response = self.client.subscriptions.list() - result = [r async for r in response] - assert response diff --git a/sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_test.py b/sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_test.py deleted file mode 100644 index 5c6293959c4c..000000000000 --- a/sdk/resources/azure-mgmt-resource/tests/test_subscription_subscriptions_operations_test.py +++ /dev/null @@ -1,26 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.resource.subscriptions import SubscriptionClient - -from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy - -AZURE_LOCATION = "eastus" - - -@pytest.mark.live_test_only -class TestSubscriptionSubscriptionsOperations(AzureMgmtRecordedTestCase): - def setup_method(self, method): - self.client = self.create_mgmt_client(SubscriptionClient) - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_subscriptions_list(self, resource_group): - response = self.client.subscriptions.list() - result = [r for r in response] - assert response From 333ade28e02b68b4dc1e0536c2077042089308b2 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 5 Feb 2026 18:41:42 -0800 Subject: [PATCH 76/84] [AutoRelease] t2-redhatopenshift-2026-01-22-31664(can only be merged by SDK owner) (#44791) * code and test * update changelog * Update CHANGELOG.md --------- Co-authored-by: azure-sdk Co-authored-by: ChenxiJiang333 Co-authored-by: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> --- .../azure-mgmt-redhatopenshift/CHANGELOG.md | 47 + .../azure-mgmt-redhatopenshift/MANIFEST.in | 9 +- .../azure-mgmt-redhatopenshift/README.md | 6 +- .../azure-mgmt-redhatopenshift/_meta.json | 11 - .../azure-mgmt-redhatopenshift/_metadata.json | 11 + .../apiview-properties.json | 72 ++ .../azure/__init__.py | 2 +- .../azure/mgmt/__init__.py | 2 +- .../azure/mgmt/redhatopenshift/__init__.py | 12 +- .../_azure_red_hat_open_shift_client.py | 69 +- .../mgmt/redhatopenshift/_configuration.py | 24 +- .../mgmt/redhatopenshift/_utils/__init__.py | 6 + .../serialization.py} | 601 +++++++------ .../azure/mgmt/redhatopenshift/_version.py | 2 +- .../mgmt/redhatopenshift/aio/__init__.py | 12 +- .../aio/_azure_red_hat_open_shift_client.py | 71 +- .../redhatopenshift/aio/_configuration.py | 24 +- .../aio/operations/__init__.py | 28 +- .../operations/_machine_pools_operations.py | 562 ------------ .../_open_shift_clusters_operations.py | 54 +- .../_open_shift_versions_operations.py | 93 +- .../aio/operations/_operations.py | 29 +- ...m_workload_identity_role_set_operations.py | 115 +++ ..._workload_identity_role_sets_operations.py | 139 +++ .../aio/operations/_secrets_operations.py | 558 ------------ .../_sync_identity_providers_operations.py | 570 ------------- .../aio/operations/_sync_sets_operations.py | 559 ------------ .../mgmt/redhatopenshift/models/__init__.py | 121 +-- .../_azure_red_hat_open_shift_client_enums.py | 11 + .../redhatopenshift/models/_models_py3.py | 784 ++++++++--------- .../redhatopenshift/operations/__init__.py | 28 +- .../operations/_machine_pools_operations.py | 796 ----------------- .../_open_shift_clusters_operations.py | 106 +-- .../_open_shift_versions_operations.py | 138 ++- .../redhatopenshift/operations/_operations.py | 34 +- ...m_workload_identity_role_set_operations.py | 154 ++++ ..._workload_identity_role_sets_operations.py | 170 ++++ .../operations/_secrets_operations.py | 792 ----------------- .../_sync_identity_providers_operations.py | 803 ------------------ .../operations/_sync_sets_operations.py | 793 ----------------- .../machine_pools_create_or_update.py | 48 -- .../generated_samples/machine_pools_delete.py | 42 - .../generated_samples/machine_pools_get.py | 43 - .../generated_samples/machine_pools_list.py | 43 - .../generated_samples/machine_pools_update.py | 48 -- .../open_shift_clusters_create_or_update.py | 13 +- .../open_shift_clusters_delete.py | 5 +- .../open_shift_clusters_get.py | 5 +- .../open_shift_clusters_list.py | 5 +- ...n_shift_clusters_list_admin_credentials.py | 5 +- ...n_shift_clusters_list_by_resource_group.py | 5 +- .../open_shift_clusters_list_credentials.py | 5 +- .../open_shift_clusters_update.py | 13 +- ...rets_get.py => open_shift_versions_get.py} | 14 +- .../open_shift_versions_list.py | 5 +- .../generated_samples/operations_list.py | 3 +- ...latform_workload_identity_role_set_get.py} | 15 +- ...tform_workload_identity_role_sets_list.py} | 12 +- .../generated_samples/secrets_delete.py | 42 - .../generated_samples/secrets_update.py | 44 - ...ync_identity_providers_create_or_update.py | 48 -- .../sync_identity_providers_delete.py | 42 - .../sync_identity_providers_get.py | 43 - .../sync_identity_providers_list.py | 43 - .../sync_identity_providers_update.py | 48 -- .../sync_sets_create_or_update.py | 48 -- .../generated_samples/sync_sets_delete.py | 42 - .../generated_samples/sync_sets_get.py | 43 - .../generated_samples/sync_sets_list.py | 43 - .../generated_samples/sync_sets_update.py | 48 -- .../generated_tests/conftest.py | 2 +- ...en_shift_open_shift_clusters_operations.py | 62 +- ...ft_open_shift_clusters_operations_async.py | 66 +- ...en_shift_open_shift_versions_operations.py | 16 +- ...ft_open_shift_versions_operations_async.py | 16 +- ...est_azure_red_hat_open_shift_operations.py | 4 +- ...ure_red_hat_open_shift_operations_async.py | 4 +- ...m_workload_identity_role_set_operations.py | 31 + ...load_identity_role_set_operations_async.py | 32 + ..._workload_identity_role_sets_operations.py | 30 + ...oad_identity_role_sets_operations_async.py | 31 + .../azure-mgmt-redhatopenshift/pyproject.toml | 82 ++ .../sdk_packaging.toml | 8 - .../azure-mgmt-redhatopenshift/setup.py | 85 -- 84 files changed, 2331 insertions(+), 7419 deletions(-) delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/_meta.json create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/_metadata.json create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/apiview-properties.json create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/__init__.py rename sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/{_serialization.py => _utils/serialization.py} (81%) delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_machine_pools_operations.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_set_operations.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_sets_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_secrets_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_identity_providers_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_sets_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_machine_pools_operations.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_set_operations.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_sets_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_secrets_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_identity_providers_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_sets_operations.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_create_or_update.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_delete.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_get.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_list.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_update.py rename sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/{secrets_get.py => open_shift_versions_get.py} (77%) rename sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/{secrets_create_or_update.py => platform_workload_identity_role_set_get.py} (75%) rename sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/{secrets_list.py => platform_workload_identity_role_sets_list.py} (77%) delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_delete.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_update.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_create_or_update.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_delete.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_get.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_list.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_update.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_create_or_update.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_delete.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_get.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_list.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_update.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations_async.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations.py create mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations_async.py delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/sdk_packaging.toml delete mode 100644 sdk/redhatopenshift/azure-mgmt-redhatopenshift/setup.py diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/CHANGELOG.md b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/CHANGELOG.md index 9df1dd3da0eb..e7e8575fb2d7 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/CHANGELOG.md +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/CHANGELOG.md @@ -1,5 +1,52 @@ # Release History +## 3.0.0 (2026-02-06) + +### Features Added + + - Model `AzureRedHatOpenShiftClient` added parameter `cloud_setting` in method `__init__` + - Client `AzureRedHatOpenShiftClient` added operation group `platform_workload_identity_role_sets` + - Client `AzureRedHatOpenShiftClient` added operation group `platform_workload_identity_role_set` + - Model `ClusterProfile` added property `oidc_issuer` + - Model `OpenShiftCluster` added property `identity` + - Model `OpenShiftCluster` added property `platform_workload_identity_profile` + - Model `OpenShiftClusterUpdate` added property `identity` + - Model `OpenShiftClusterUpdate` added property `platform_workload_identity_profile` + - Added model `ManagedServiceIdentity` + - Added enum `ManagedServiceIdentityType` + - Added model `PlatformWorkloadIdentity` + - Added model `PlatformWorkloadIdentityProfile` + - Added model `PlatformWorkloadIdentityRole` + - Added model `PlatformWorkloadIdentityRoleSet` + - Added model `PlatformWorkloadIdentityRoleSetList` + - Added model `UserAssignedIdentity` + - Added operation group `PlatformWorkloadIdentityRoleSetOperations` + - Added operation group `PlatformWorkloadIdentityRoleSetsOperations` + +### Breaking Changes + + - Deleted or renamed client operation group `AzureRedHatOpenShiftClient.machine_pools` + - Deleted or renamed client operation group `AzureRedHatOpenShiftClient.secrets` + - Deleted or renamed client operation group `AzureRedHatOpenShiftClient.sync_identity_providers` + - Deleted or renamed client operation group `AzureRedHatOpenShiftClient.sync_sets` + - Model `OpenShiftClusterUpdate` deleted or renamed its instance variable `system_data` + - Deleted or renamed model `MachinePool` + - Deleted or renamed model `MachinePoolList` + - Deleted or renamed model `MachinePoolUpdate` + - Deleted or renamed model `Secret` + - Deleted or renamed model `SecretList` + - Deleted or renamed model `SecretUpdate` + - Deleted or renamed model `SyncIdentityProvider` + - Deleted or renamed model `SyncIdentityProviderList` + - Deleted or renamed model `SyncIdentityProviderUpdate` + - Deleted or renamed model `SyncSet` + - Deleted or renamed model `SyncSetList` + - Deleted or renamed model `SyncSetUpdate` + - Deleted or renamed operation group `MachinePoolsOperations` + - Deleted or renamed operation group `SecretsOperations` + - Deleted or renamed operation group `SyncIdentityProvidersOperations` + - Deleted or renamed operation group `SyncSetsOperations` + ## 2.0.0 (2024-10-30) ### Breaking Changes diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/MANIFEST.in b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/MANIFEST.in index f613d9ba0210..9407420cf38c 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/MANIFEST.in +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/MANIFEST.in @@ -1,8 +1,7 @@ -include _meta.json -recursive-include tests *.py *.json -recursive-include samples *.py *.md include *.md -include azure/__init__.py -include azure/mgmt/__init__.py include LICENSE include azure/mgmt/redhatopenshift/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/README.md b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/README.md index 2e9c20567988..feff304ae814 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/README.md +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Red Hat Openshift Management Client Library. -This package has been tested with Python 3.8+. +This package has been tested with Python 3.9+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.8+ is required to use this package. +- Python 3.9+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -24,7 +24,7 @@ pip install azure-identity ### Authentication -By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of following environment variables. +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. - `AZURE_CLIENT_ID` for Azure client ID. - `AZURE_TENANT_ID` for Azure tenant ID. diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/_meta.json b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/_meta.json deleted file mode 100644 index f95af25c6039..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "2776cb32cd6ca9ea953a13ae26c954b989e83367", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.10.2", - "use": [ - "@autorest/python@6.19.0", - "@autorest/modelerfour@4.27.0" - ], - "autorest_command": "autorest specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-2023-11 --use=@autorest/python@6.19.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", - "readme": "specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/readme.md" -} diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/_metadata.json b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/_metadata.json new file mode 100644 index 000000000000..d58e3600b003 --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "f52764d11d53276b79bbbba37f977ef0b03bbd2c", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.45.1", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.45.1 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/readme.md" +} \ No newline at end of file diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/apiview-properties.json b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/apiview-properties.json new file mode 100644 index 000000000000..a60407f6fd0f --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/apiview-properties.json @@ -0,0 +1,72 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.redhatopenshift.models.APIServerProfile": null, + "azure.mgmt.redhatopenshift.models.CloudErrorBody": null, + "azure.mgmt.redhatopenshift.models.ClusterProfile": null, + "azure.mgmt.redhatopenshift.models.ConsoleProfile": null, + "azure.mgmt.redhatopenshift.models.Display": null, + "azure.mgmt.redhatopenshift.models.EffectiveOutboundIP": null, + "azure.mgmt.redhatopenshift.models.IngressProfile": null, + "azure.mgmt.redhatopenshift.models.LoadBalancerProfile": null, + "azure.mgmt.redhatopenshift.models.ManagedOutboundIPs": null, + "azure.mgmt.redhatopenshift.models.ManagedServiceIdentity": null, + "azure.mgmt.redhatopenshift.models.MasterProfile": null, + "azure.mgmt.redhatopenshift.models.NetworkProfile": null, + "azure.mgmt.redhatopenshift.models.Resource": null, + "azure.mgmt.redhatopenshift.models.TrackedResource": null, + "azure.mgmt.redhatopenshift.models.OpenShiftCluster": null, + "azure.mgmt.redhatopenshift.models.OpenShiftClusterAdminKubeconfig": null, + "azure.mgmt.redhatopenshift.models.OpenShiftClusterCredentials": null, + "azure.mgmt.redhatopenshift.models.OpenShiftClusterList": null, + "azure.mgmt.redhatopenshift.models.OpenShiftClusterUpdate": null, + "azure.mgmt.redhatopenshift.models.ProxyResource": null, + "azure.mgmt.redhatopenshift.models.OpenShiftVersion": null, + "azure.mgmt.redhatopenshift.models.OpenShiftVersionList": null, + "azure.mgmt.redhatopenshift.models.Operation": null, + "azure.mgmt.redhatopenshift.models.OperationList": null, + "azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentity": null, + "azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityProfile": null, + "azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRole": null, + "azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet": null, + "azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSetList": null, + "azure.mgmt.redhatopenshift.models.ServicePrincipalProfile": null, + "azure.mgmt.redhatopenshift.models.SystemData": null, + "azure.mgmt.redhatopenshift.models.UserAssignedIdentity": null, + "azure.mgmt.redhatopenshift.models.WorkerProfile": null, + "azure.mgmt.redhatopenshift.models.CreatedByType": null, + "azure.mgmt.redhatopenshift.models.EncryptionAtHost": null, + "azure.mgmt.redhatopenshift.models.Visibility": null, + "azure.mgmt.redhatopenshift.models.ManagedServiceIdentityType": null, + "azure.mgmt.redhatopenshift.models.ProvisioningState": null, + "azure.mgmt.redhatopenshift.models.FipsValidatedModules": null, + "azure.mgmt.redhatopenshift.models.OutboundType": null, + "azure.mgmt.redhatopenshift.models.PreconfiguredNSG": null, + "azure.mgmt.redhatopenshift.operations.Operations.list": null, + "azure.mgmt.redhatopenshift.aio.operations.Operations.list": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftVersionsOperations.list": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftVersionsOperations.list": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftVersionsOperations.get": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftVersionsOperations.get": null, + "azure.mgmt.redhatopenshift.operations.PlatformWorkloadIdentityRoleSetsOperations.list": null, + "azure.mgmt.redhatopenshift.aio.operations.PlatformWorkloadIdentityRoleSetsOperations.list": null, + "azure.mgmt.redhatopenshift.operations.PlatformWorkloadIdentityRoleSetOperations.get": null, + "azure.mgmt.redhatopenshift.aio.operations.PlatformWorkloadIdentityRoleSetOperations.get": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.list": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.list": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.list_by_resource_group": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.list_by_resource_group": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.get": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.get": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.begin_create_or_update": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.begin_create_or_update": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.begin_delete": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.begin_delete": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.begin_update": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.begin_update": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.list_admin_credentials": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.list_admin_credentials": null, + "azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations.list_credentials": null, + "azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations.list_credentials": null + } +} \ No newline at end of file diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/__init__.py index c64163c98d3d..bddf8279c601 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_red_hat_open_shift_client import AzureRedHatOpenShiftClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._azure_red_hat_open_shift_client import AzureRedHatOpenShiftClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -21,6 +27,6 @@ __all__ = [ "AzureRedHatOpenShiftClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_azure_red_hat_open_shift_client.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_azure_red_hat_open_shift_client.py index 150eafc9e5da..95ef4224f197 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_azure_red_hat_open_shift_client.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_azure_red_hat_open_shift_client.py @@ -7,57 +7,58 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING, cast from typing_extensions import Self from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings from azure.mgmt.core import ARMPipelineClient from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from . import models as _models from ._configuration import AzureRedHatOpenShiftClientConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( - MachinePoolsOperations, OpenShiftClustersOperations, OpenShiftVersionsOperations, Operations, - SecretsOperations, - SyncIdentityProvidersOperations, - SyncSetsOperations, + PlatformWorkloadIdentityRoleSetOperations, + PlatformWorkloadIdentityRoleSetsOperations, ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials import TokenCredential -class AzureRedHatOpenShiftClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class AzureRedHatOpenShiftClient: """Rest API for Azure Red Hat OpenShift 4. :ivar operations: Operations operations :vartype operations: azure.mgmt.redhatopenshift.operations.Operations :ivar open_shift_versions: OpenShiftVersionsOperations operations :vartype open_shift_versions: azure.mgmt.redhatopenshift.operations.OpenShiftVersionsOperations + :ivar platform_workload_identity_role_sets: PlatformWorkloadIdentityRoleSetsOperations + operations + :vartype platform_workload_identity_role_sets: + azure.mgmt.redhatopenshift.operations.PlatformWorkloadIdentityRoleSetsOperations + :ivar platform_workload_identity_role_set: PlatformWorkloadIdentityRoleSetOperations operations + :vartype platform_workload_identity_role_set: + azure.mgmt.redhatopenshift.operations.PlatformWorkloadIdentityRoleSetOperations :ivar open_shift_clusters: OpenShiftClustersOperations operations :vartype open_shift_clusters: azure.mgmt.redhatopenshift.operations.OpenShiftClustersOperations - :ivar machine_pools: MachinePoolsOperations operations - :vartype machine_pools: azure.mgmt.redhatopenshift.operations.MachinePoolsOperations - :ivar secrets: SecretsOperations operations - :vartype secrets: azure.mgmt.redhatopenshift.operations.SecretsOperations - :ivar sync_identity_providers: SyncIdentityProvidersOperations operations - :vartype sync_identity_providers: - azure.mgmt.redhatopenshift.operations.SyncIdentityProvidersOperations - :ivar sync_sets: SyncSetsOperations operations - :vartype sync_sets: azure.mgmt.redhatopenshift.operations.SyncSetsOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2023-11-22". Note that overriding this + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2025-07-25". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no @@ -68,12 +69,24 @@ def __init__( self, credential: "TokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = AzureRedHatOpenShiftClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs ) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -92,7 +105,7 @@ def __init__( policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) @@ -102,15 +115,15 @@ def __init__( self.open_shift_versions = OpenShiftVersionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.open_shift_clusters = OpenShiftClustersOperations( + self.platform_workload_identity_role_sets = PlatformWorkloadIdentityRoleSetsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.machine_pools = MachinePoolsOperations(self._client, self._config, self._serialize, self._deserialize) - self.secrets = SecretsOperations(self._client, self._config, self._serialize, self._deserialize) - self.sync_identity_providers = SyncIdentityProvidersOperations( + self.platform_workload_identity_role_set = PlatformWorkloadIdentityRoleSetOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.open_shift_clusters = OpenShiftClustersOperations( self._client, self._config, self._serialize, self._deserialize ) - self.sync_sets = SyncSetsOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_configuration.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_configuration.py index db318d6f55d8..de49d35baeb1 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_configuration.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_configuration.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy @@ -14,11 +14,11 @@ from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials import TokenCredential -class AzureRedHatOpenShiftClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class AzureRedHatOpenShiftClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for AzureRedHatOpenShiftClient. Note that all parameters used to create this instance are saved as instance @@ -26,15 +26,24 @@ class AzureRedHatOpenShiftClientConfiguration: # pylint: disable=too-many-insta :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2023-11-22". Note that overriding this + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2025-07-25". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2023-11-22") + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-07-25") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -43,6 +52,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.credential = credential self.subscription_id = subscription_id + self.cloud_setting = cloud_setting self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-redhatopenshift/{}".format(VERSION)) diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_serialization.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/serialization.py similarity index 81% rename from sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_serialization.py rename to sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/serialization.py index 8139854b97bb..6da830e0cf4a 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_serialization.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -39,7 +21,6 @@ import sys import codecs from typing import ( - Dict, Any, cast, Optional, @@ -48,11 +29,7 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, - List, - Mapping, ) try: @@ -62,13 +39,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,6 +68,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +91,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -155,6 +134,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -179,80 +163,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -300,13 +242,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -326,7 +278,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -346,12 +302,14 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -380,12 +338,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -395,30 +356,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -426,9 +388,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -448,21 +412,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -501,11 +469,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -540,7 +510,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -556,17 +526,20 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} + self.dependencies: dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -592,17 +565,19 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) + serialized |= target_obj.additional_properties continue try: @@ -633,7 +608,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -664,17 +640,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise SerializationError(msg) from err - else: - return serialized + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -703,7 +679,7 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: raise SerializationError("Unable to build a model: " + str(err)) from err @@ -712,11 +688,13 @@ def body(self, data, data_type, **kwargs): def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -728,21 +706,20 @@ def url(self, name, data, data_type, **kwargs): output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. :rtype: str, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator @@ -759,19 +736,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -780,21 +758,20 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") @@ -805,12 +782,12 @@ def serialize_data(self, data, data_type, **kwargs): if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,11 +798,10 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -841,23 +817,33 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -871,8 +857,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -882,15 +867,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -945,9 +928,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -971,7 +953,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -979,6 +961,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -1003,7 +986,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1034,56 +1017,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1091,11 +1079,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1105,30 +1094,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1141,12 +1132,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1172,13 +1164,14 @@ def serialize_iso(attr, **kwargs): raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1186,17 +1179,17 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data while "." in key: # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) + dict_keys = cast(list[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1211,7 +1204,9 @@ def rest_key_extractor(attr, attr_desc, data): return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1232,17 +1227,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1279,7 +1286,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1331,22 +1338,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1354,7 +1360,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1363,9 +1369,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1385,7 +1391,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} + self.dependencies: dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1401,27 +1407,29 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1440,13 +1448,13 @@ def _deserialize(self, target_obj, data): if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1476,9 +1484,8 @@ def _deserialize(self, target_obj, data): except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1505,6 +1512,8 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None @@ -1516,7 +1525,7 @@ def _classify_target(self, target, data): return target, target try: - target = target._classify(data, self.dependencies) # type: ignore + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1531,10 +1540,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1552,10 +1563,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1579,24 +1592,35 @@ def _unpack_content(raw_data, content_type=None): def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1605,15 +1629,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1627,7 +1652,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1647,14 +1676,14 @@ def deserialize_data(self, data, data_type): msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1671,6 +1700,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1681,13 +1711,14 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None @@ -1720,11 +1751,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1732,8 +1762,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1743,24 +1774,27 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, str): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): @@ -1768,6 +1802,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1781,8 +1816,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1794,6 +1828,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1804,9 +1839,9 @@ def deserialize_enum(data, enum_obj): # Workaround. We might consider remove it in the future. try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1822,8 +1857,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1834,8 +1870,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1849,8 +1886,9 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text @@ -1865,8 +1903,9 @@ def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1877,8 +1916,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1887,16 +1927,16 @@ def deserialize_duration(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise DeserializationError(msg) from err - else: - return duration + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1910,8 +1950,9 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1924,31 +1965,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1976,8 +2018,7 @@ def deserialize_iso(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_unix(attr): @@ -1985,8 +2026,9 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore @@ -1996,5 +2038,4 @@ def deserialize_unix(attr): except ValueError as err: msg = "Cannot deserialize to unix datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_version.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_version.py index 48944bf3938a..cac9f5d10f8b 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_version.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/__init__.py index b06f0016da77..85bf1858da3e 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/__init__.py @@ -5,12 +5,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_red_hat_open_shift_client import AzureRedHatOpenShiftClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._azure_red_hat_open_shift_client import AzureRedHatOpenShiftClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -18,6 +24,6 @@ __all__ = [ "AzureRedHatOpenShiftClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_azure_red_hat_open_shift_client.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_azure_red_hat_open_shift_client.py index 4862d11c40cd..a5d9343bae58 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_azure_red_hat_open_shift_client.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_azure_red_hat_open_shift_client.py @@ -7,33 +7,33 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast from typing_extensions import Self from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from .. import models as _models -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import AzureRedHatOpenShiftClientConfiguration from .operations import ( - MachinePoolsOperations, OpenShiftClustersOperations, OpenShiftVersionsOperations, Operations, - SecretsOperations, - SyncIdentityProvidersOperations, - SyncSetsOperations, + PlatformWorkloadIdentityRoleSetOperations, + PlatformWorkloadIdentityRoleSetsOperations, ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class AzureRedHatOpenShiftClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class AzureRedHatOpenShiftClient: """Rest API for Azure Red Hat OpenShift 4. :ivar operations: Operations operations @@ -41,25 +41,26 @@ class AzureRedHatOpenShiftClient: # pylint: disable=client-accepts-api-version- :ivar open_shift_versions: OpenShiftVersionsOperations operations :vartype open_shift_versions: azure.mgmt.redhatopenshift.aio.operations.OpenShiftVersionsOperations + :ivar platform_workload_identity_role_sets: PlatformWorkloadIdentityRoleSetsOperations + operations + :vartype platform_workload_identity_role_sets: + azure.mgmt.redhatopenshift.aio.operations.PlatformWorkloadIdentityRoleSetsOperations + :ivar platform_workload_identity_role_set: PlatformWorkloadIdentityRoleSetOperations operations + :vartype platform_workload_identity_role_set: + azure.mgmt.redhatopenshift.aio.operations.PlatformWorkloadIdentityRoleSetOperations :ivar open_shift_clusters: OpenShiftClustersOperations operations :vartype open_shift_clusters: azure.mgmt.redhatopenshift.aio.operations.OpenShiftClustersOperations - :ivar machine_pools: MachinePoolsOperations operations - :vartype machine_pools: azure.mgmt.redhatopenshift.aio.operations.MachinePoolsOperations - :ivar secrets: SecretsOperations operations - :vartype secrets: azure.mgmt.redhatopenshift.aio.operations.SecretsOperations - :ivar sync_identity_providers: SyncIdentityProvidersOperations operations - :vartype sync_identity_providers: - azure.mgmt.redhatopenshift.aio.operations.SyncIdentityProvidersOperations - :ivar sync_sets: SyncSetsOperations operations - :vartype sync_sets: azure.mgmt.redhatopenshift.aio.operations.SyncSetsOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2023-11-22". Note that overriding this + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2025-07-25". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no @@ -70,12 +71,24 @@ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = AzureRedHatOpenShiftClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs ) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -94,7 +107,9 @@ def __init__( policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) @@ -104,15 +119,15 @@ def __init__( self.open_shift_versions = OpenShiftVersionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.open_shift_clusters = OpenShiftClustersOperations( + self.platform_workload_identity_role_sets = PlatformWorkloadIdentityRoleSetsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.machine_pools = MachinePoolsOperations(self._client, self._config, self._serialize, self._deserialize) - self.secrets = SecretsOperations(self._client, self._config, self._serialize, self._deserialize) - self.sync_identity_providers = SyncIdentityProvidersOperations( + self.platform_workload_identity_role_set = PlatformWorkloadIdentityRoleSetOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.open_shift_clusters = OpenShiftClustersOperations( self._client, self._config, self._serialize, self._deserialize ) - self.sync_sets = SyncSetsOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_configuration.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_configuration.py index f3376438bb0e..90b8b8df5001 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_configuration.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/_configuration.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy @@ -14,11 +14,11 @@ from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class AzureRedHatOpenShiftClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class AzureRedHatOpenShiftClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for AzureRedHatOpenShiftClient. Note that all parameters used to create this instance are saved as instance @@ -26,15 +26,24 @@ class AzureRedHatOpenShiftClientConfiguration: # pylint: disable=too-many-insta :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2023-11-22". Note that overriding this + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2025-07-25". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2023-11-22") + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-07-25") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -43,6 +52,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.credential = credential self.subscription_id = subscription_id + self.cloud_setting = cloud_setting self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-redhatopenshift/{}".format(VERSION)) diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/__init__.py index f03257fe6903..0940c895da8b 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/__init__.py @@ -5,27 +5,29 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._open_shift_versions_operations import OpenShiftVersionsOperations -from ._open_shift_clusters_operations import OpenShiftClustersOperations -from ._machine_pools_operations import MachinePoolsOperations -from ._secrets_operations import SecretsOperations -from ._sync_identity_providers_operations import SyncIdentityProvidersOperations -from ._sync_sets_operations import SyncSetsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._open_shift_versions_operations import OpenShiftVersionsOperations # type: ignore +from ._platform_workload_identity_role_sets_operations import PlatformWorkloadIdentityRoleSetsOperations # type: ignore +from ._platform_workload_identity_role_set_operations import PlatformWorkloadIdentityRoleSetOperations # type: ignore +from ._open_shift_clusters_operations import OpenShiftClustersOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Operations", "OpenShiftVersionsOperations", + "PlatformWorkloadIdentityRoleSetsOperations", + "PlatformWorkloadIdentityRoleSetOperations", "OpenShiftClustersOperations", - "MachinePoolsOperations", - "SecretsOperations", - "SyncIdentityProvidersOperations", - "SyncSetsOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_machine_pools_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_machine_pools_operations.py deleted file mode 100644 index 6f7a5a2d00f2..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_machine_pools_operations.py +++ /dev/null @@ -1,562 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._machine_pools_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class MachinePoolsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.aio.AzureRedHatOpenShiftClient`'s - :attr:`machine_pools` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> AsyncIterable["_models.MachinePool"]: - """Lists MachinePools that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either MachinePool or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redhatopenshift.models.MachinePool] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MachinePoolList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MachinePoolList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.MachinePool: - """Gets a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MachinePool] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MachinePool", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.MachinePool, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Creates or updates a MachinePool with the specified subscription, resource group and resource - name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Creates or updates a MachinePool with the specified subscription, resource group and resource - name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.MachinePool, IO[bytes]], - **kwargs: Any - ) -> _models.MachinePool: - """Creates or updates a MachinePool with the specified subscription, resource group and resource - name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Is either a MachinePool type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePool or IO[bytes] - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MachinePool] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "MachinePool") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MachinePool", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a MachinePool with the specified subscription, resource group and resource name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.MachinePoolUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Updates a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePoolUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Updates a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.MachinePoolUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.MachinePool: - """Updates a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Is either a MachinePoolUpdate type or a IO[bytes] - type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePoolUpdate or IO[bytes] - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MachinePool] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "MachinePoolUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MachinePool", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_clusters_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_clusters_operations.py index 79143236e115..76b4d1979c8e 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_clusters_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_clusters_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,11 +5,12 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -32,6 +32,7 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer from ...operations._open_shift_clusters_operations import ( build_create_or_update_request, build_delete_request, @@ -42,13 +43,11 @@ build_list_request, build_update_request, ) +from .._configuration import AzureRedHatOpenShiftClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class OpenShiftClustersOperations: @@ -65,13 +64,15 @@ class OpenShiftClustersOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.OpenShiftCluster"]: + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.OpenShiftCluster"]: """Lists OpenShift clusters in the specified subscription. The operation returns properties of each OpenShift cluster. @@ -87,7 +88,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.OpenShiftCluster"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OpenShiftClusterList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -150,7 +151,7 @@ async def get_next(next_link=None): @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any - ) -> AsyncIterable["_models.OpenShiftCluster"]: + ) -> AsyncItemPaged["_models.OpenShiftCluster"]: """Lists OpenShift clusters in the specified subscription and resource group. The operation returns properties of each OpenShift cluster. @@ -169,7 +170,7 @@ def list_by_resource_group( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OpenShiftClusterList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -245,7 +246,7 @@ async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftCluster :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -294,7 +295,7 @@ async def _create_or_update_initial( parameters: Union[_models.OpenShiftCluster, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -491,7 +492,7 @@ def get_long_running_output(pipeline_response): async def _delete_initial( self, resource_group_name: str, resource_name: str, **kwargs: Any ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -600,7 +601,7 @@ async def _update_initial( parameters: Union[_models.OpenShiftClusterUpdate, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -669,7 +670,8 @@ async def begin_update( content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.OpenShiftCluster]: - """Updates a OpenShift cluster with the specified subscription, resource group and resource name. + """Creates or updates a OpenShift cluster with the specified subscription, resource group and + resource name. The operation returns properties of a OpenShift cluster. @@ -699,7 +701,8 @@ async def begin_update( content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.OpenShiftCluster]: - """Updates a OpenShift cluster with the specified subscription, resource group and resource name. + """Creates or updates a OpenShift cluster with the specified subscription, resource group and + resource name. The operation returns properties of a OpenShift cluster. @@ -727,7 +730,8 @@ async def begin_update( parameters: Union[_models.OpenShiftClusterUpdate, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.OpenShiftCluster]: - """Updates a OpenShift cluster with the specified subscription, resource group and resource name. + """Creates or updates a OpenShift cluster with the specified subscription, resource group and + resource name. The operation returns properties of a OpenShift cluster. @@ -809,7 +813,7 @@ async def list_admin_credentials( :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftClusterAdminKubeconfig :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -869,7 +873,7 @@ async def list_credentials( :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftClusterCredentials :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_versions_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_versions_operations.py index 14ef60644f08..cd89c27619d9 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_versions_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_open_shift_versions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -22,18 +22,18 @@ from azure.core.pipeline import PipelineResponse from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ...operations._open_shift_versions_operations import build_list_request +from ..._utils.serialization import Deserializer, Serializer +from ...operations._open_shift_versions_operations import build_get_request, build_list_request +from .._configuration import AzureRedHatOpenShiftClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class OpenShiftVersionsOperations: @@ -50,18 +50,20 @@ class OpenShiftVersionsOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.OpenShiftVersion"]: + def list(self, location: str, **kwargs: Any) -> AsyncItemPaged["_models.OpenShiftVersion"]: """Lists all OpenShift versions available to install in the specified location. - The operation returns the installable OpenShift versions as strings. + The operation returns the installable OpenShift versions as a string. - :param location: The name of Azure region. Required. + :param location: The name of the Azure region. Required. :type location: str :return: An iterator like instance of either OpenShiftVersion or the result of cls(response) :rtype: @@ -74,7 +76,7 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.OpenShift api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OpenShiftVersionList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -134,3 +136,60 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, location: str, open_shift_version: str, **kwargs: Any) -> _models.OpenShiftVersion: + """Gets an available OpenShift version to install in the specified location. + + This operation returns installable OpenShift version as a string. + + :param location: The name of the Azure region. Required. + :type location: str + :param open_shift_version: The desired version value of the OpenShiftVersion resource. + Required. + :type open_shift_version: str + :return: OpenShiftVersion or the result of cls(response) + :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OpenShiftVersion] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + open_shift_version=open_shift_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("OpenShiftVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_operations.py index 37358486a661..dd6d8eacd573 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -26,14 +26,13 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_list_request +from .._configuration import AzureRedHatOpenShiftClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class Operations: @@ -50,13 +49,15 @@ class Operations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: """Lists all of the available RP operations. The operation returns the RP operations. @@ -71,7 +72,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_set_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_set_operations.py new file mode 100644 index 000000000000..37a4ad4039cb --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_set_operations.py @@ -0,0 +1,115 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._platform_workload_identity_role_set_operations import build_get_request +from .._configuration import AzureRedHatOpenShiftClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class PlatformWorkloadIdentityRoleSetOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redhatopenshift.aio.AzureRedHatOpenShiftClient`'s + :attr:`platform_workload_identity_role_set` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, location: str, open_shift_minor_version: str, **kwargs: Any + ) -> _models.PlatformWorkloadIdentityRoleSet: + """Gets a mapping of an OpenShift version to identity requirements, which includes operatorName, + roleDefinitionName, roleDefinitionId, and serviceAccounts. + + This operation returns Platform Workload Identity Role Set as a string. + + :param location: The name of the Azure region. Required. + :type location: str + :param open_shift_minor_version: The desired version value of the + PlatformWorkloadIdentityRoleSet resource. Required. + :type open_shift_minor_version: str + :return: PlatformWorkloadIdentityRoleSet or the result of cls(response) + :rtype: ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PlatformWorkloadIdentityRoleSet] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + open_shift_minor_version=open_shift_minor_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PlatformWorkloadIdentityRoleSet", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_sets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_sets_operations.py new file mode 100644 index 000000000000..fe962d4d0921 --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_platform_workload_identity_role_sets_operations.py @@ -0,0 +1,139 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._platform_workload_identity_role_sets_operations import build_list_request +from .._configuration import AzureRedHatOpenShiftClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class PlatformWorkloadIdentityRoleSetsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redhatopenshift.aio.AzureRedHatOpenShiftClient`'s + :attr:`platform_workload_identity_role_sets` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, location: str, **kwargs: Any) -> AsyncItemPaged["_models.PlatformWorkloadIdentityRoleSet"]: + """Lists a mapping of OpenShift versions to identity requirements, which include operatorName, + roleDefinitionName, roleDefinitionId, and serviceAccounts. + + This operation returns a list of Platform Workload Identity Role Sets as a string. + + :param location: The name of the Azure region. Required. + :type location: str + :return: An iterator like instance of either PlatformWorkloadIdentityRoleSet or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PlatformWorkloadIdentityRoleSetList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PlatformWorkloadIdentityRoleSetList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_secrets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_secrets_operations.py deleted file mode 100644 index a89e55a7aa24..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_secrets_operations.py +++ /dev/null @@ -1,558 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._secrets_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class SecretsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.aio.AzureRedHatOpenShiftClient`'s - :attr:`secrets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> AsyncIterable["_models.Secret"]: - """Lists Secrets that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either Secret or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redhatopenshift.models.Secret] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SecretList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SecretList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.Secret: - """Gets a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Secret] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Secret", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.Secret, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Creates or updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.Secret - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Creates or updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.Secret, IO[bytes]], - **kwargs: Any - ) -> _models.Secret: - """Creates or updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Is either a Secret type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.Secret or IO[bytes] - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Secret] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Secret") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Secret", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a Secret with the specified subscription, resource group and resource name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SecretUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SecretUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SecretUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.Secret: - """Updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Is either a SecretUpdate type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SecretUpdate or IO[bytes] - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Secret] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SecretUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Secret", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_identity_providers_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_identity_providers_operations.py deleted file mode 100644 index c0073ae25f44..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_identity_providers_operations.py +++ /dev/null @@ -1,570 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._sync_identity_providers_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class SyncIdentityProvidersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.aio.AzureRedHatOpenShiftClient`'s - :attr:`sync_identity_providers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, resource_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SyncIdentityProvider"]: - """Lists SyncIdentityProviders that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either SyncIdentityProvider or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redhatopenshift.models.SyncIdentityProvider] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncIdentityProviderList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SyncIdentityProviderList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Gets a SyncIdentityProvider with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncIdentityProvider] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncIdentityProvider", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncIdentityProvider, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Creates or updates a SyncIdentityProvider with the specified subscription, resource group and - resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Creates or updates a SyncIdentityProvider with the specified subscription, resource group and - resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncIdentityProvider, IO[bytes]], - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Creates or updates a SyncIdentityProvider with the specified subscription, resource group and - resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Is either a SyncIdentityProvider type or - a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider or IO[bytes] - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncIdentityProvider] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncIdentityProvider") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncIdentityProvider", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncIdentityProviderUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Updates a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProviderUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Updates a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncIdentityProviderUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Updates a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Is either a SyncIdentityProviderUpdate - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProviderUpdate or IO[bytes] - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncIdentityProvider] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncIdentityProviderUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncIdentityProvider", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_sets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_sets_operations.py deleted file mode 100644 index 4341fbe9b590..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/aio/operations/_sync_sets_operations.py +++ /dev/null @@ -1,559 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._sync_sets_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class SyncSetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.aio.AzureRedHatOpenShiftClient`'s - :attr:`sync_sets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> AsyncIterable["_models.SyncSet"]: - """Lists SyncSets that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either SyncSet or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redhatopenshift.models.SyncSet] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncSetList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SyncSetList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.SyncSet: - """Gets a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncSet] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncSet", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncSet, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Creates or updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSet - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Creates or updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncSet, IO[bytes]], - **kwargs: Any - ) -> _models.SyncSet: - """Creates or updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Is either a SyncSet type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSet or IO[bytes] - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncSet] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncSet") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncSet", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a SyncSet with the specified subscription, resource group and resource name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncSetUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSetUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncSetUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.SyncSet: - """Updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Is either a SyncSetUpdate type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSetUpdate or IO[bytes] - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncSet] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncSetUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncSet", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/__init__.py index ac29f6814737..6cbbe32480fc 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/__init__.py @@ -5,55 +5,62 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models_py3 import APIServerProfile -from ._models_py3 import CloudErrorBody -from ._models_py3 import ClusterProfile -from ._models_py3 import ConsoleProfile -from ._models_py3 import Display -from ._models_py3 import EffectiveOutboundIP -from ._models_py3 import IngressProfile -from ._models_py3 import LoadBalancerProfile -from ._models_py3 import MachinePool -from ._models_py3 import MachinePoolList -from ._models_py3 import MachinePoolUpdate -from ._models_py3 import ManagedOutboundIPs -from ._models_py3 import MasterProfile -from ._models_py3 import NetworkProfile -from ._models_py3 import OpenShiftCluster -from ._models_py3 import OpenShiftClusterAdminKubeconfig -from ._models_py3 import OpenShiftClusterCredentials -from ._models_py3 import OpenShiftClusterList -from ._models_py3 import OpenShiftClusterUpdate -from ._models_py3 import OpenShiftVersion -from ._models_py3 import OpenShiftVersionList -from ._models_py3 import Operation -from ._models_py3 import OperationList -from ._models_py3 import ProxyResource -from ._models_py3 import Resource -from ._models_py3 import Secret -from ._models_py3 import SecretList -from ._models_py3 import SecretUpdate -from ._models_py3 import ServicePrincipalProfile -from ._models_py3 import SyncIdentityProvider -from ._models_py3 import SyncIdentityProviderList -from ._models_py3 import SyncIdentityProviderUpdate -from ._models_py3 import SyncSet -from ._models_py3 import SyncSetList -from ._models_py3 import SyncSetUpdate -from ._models_py3 import SystemData -from ._models_py3 import TrackedResource -from ._models_py3 import WorkerProfile +from typing import TYPE_CHECKING -from ._azure_red_hat_open_shift_client_enums import CreatedByType -from ._azure_red_hat_open_shift_client_enums import EncryptionAtHost -from ._azure_red_hat_open_shift_client_enums import FipsValidatedModules -from ._azure_red_hat_open_shift_client_enums import OutboundType -from ._azure_red_hat_open_shift_client_enums import PreconfiguredNSG -from ._azure_red_hat_open_shift_client_enums import ProvisioningState -from ._azure_red_hat_open_shift_client_enums import Visibility +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + APIServerProfile, + CloudErrorBody, + ClusterProfile, + ConsoleProfile, + Display, + EffectiveOutboundIP, + IngressProfile, + LoadBalancerProfile, + ManagedOutboundIPs, + ManagedServiceIdentity, + MasterProfile, + NetworkProfile, + OpenShiftCluster, + OpenShiftClusterAdminKubeconfig, + OpenShiftClusterCredentials, + OpenShiftClusterList, + OpenShiftClusterUpdate, + OpenShiftVersion, + OpenShiftVersionList, + Operation, + OperationList, + PlatformWorkloadIdentity, + PlatformWorkloadIdentityProfile, + PlatformWorkloadIdentityRole, + PlatformWorkloadIdentityRoleSet, + PlatformWorkloadIdentityRoleSetList, + ProxyResource, + Resource, + ServicePrincipalProfile, + SystemData, + TrackedResource, + UserAssignedIdentity, + WorkerProfile, +) + +from ._azure_red_hat_open_shift_client_enums import ( # type: ignore + CreatedByType, + EncryptionAtHost, + FipsValidatedModules, + ManagedServiceIdentityType, + OutboundType, + PreconfiguredNSG, + ProvisioningState, + Visibility, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -65,10 +72,8 @@ "EffectiveOutboundIP", "IngressProfile", "LoadBalancerProfile", - "MachinePool", - "MachinePoolList", - "MachinePoolUpdate", "ManagedOutboundIPs", + "ManagedServiceIdentity", "MasterProfile", "NetworkProfile", "OpenShiftCluster", @@ -80,28 +85,26 @@ "OpenShiftVersionList", "Operation", "OperationList", + "PlatformWorkloadIdentity", + "PlatformWorkloadIdentityProfile", + "PlatformWorkloadIdentityRole", + "PlatformWorkloadIdentityRoleSet", + "PlatformWorkloadIdentityRoleSetList", "ProxyResource", "Resource", - "Secret", - "SecretList", - "SecretUpdate", "ServicePrincipalProfile", - "SyncIdentityProvider", - "SyncIdentityProviderList", - "SyncIdentityProviderUpdate", - "SyncSet", - "SyncSetList", - "SyncSetUpdate", "SystemData", "TrackedResource", + "UserAssignedIdentity", "WorkerProfile", "CreatedByType", "EncryptionAtHost", "FipsValidatedModules", + "ManagedServiceIdentityType", "OutboundType", "PreconfiguredNSG", "ProvisioningState", "Visibility", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_azure_red_hat_open_shift_client_enums.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_azure_red_hat_open_shift_client_enums.py index 8be2edf2fdb5..30d9f182f79c 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_azure_red_hat_open_shift_client_enums.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_azure_red_hat_open_shift_client_enums.py @@ -33,6 +33,17 @@ class FipsValidatedModules(str, Enum, metaclass=CaseInsensitiveEnumMeta): ENABLED = "Enabled" +class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of managed service identity (where both SystemAssigned and UserAssigned types are + allowed). + """ + + NONE = "None" + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" + + class OutboundType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The outbound routing strategy used to provide your cluster egress to the internet.""" diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_models_py3.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_models_py3.py index 5e301305ffac..ccd330b6b6e6 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_models_py3.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/models/_models_py3.py @@ -1,5 +1,5 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 -# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -8,12 +8,11 @@ # -------------------------------------------------------------------------- import datetime -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union +from typing import Any, Optional, TYPE_CHECKING, Union -from .. import _serialization +from .._utils import serialization as _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -48,8 +47,8 @@ def __init__(self, *, visibility: Optional[Union[str, "_models.Visibility"]] = N """ super().__init__(**kwargs) self.visibility = visibility - self.url = None - self.ip = None + self.url: Optional[str] = None + self.ip: Optional[str] = None class CloudErrorBody(_serialization.Model): @@ -81,7 +80,7 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["_models.CloudErrorBody"]] = None, + details: Optional[list["_models.CloudErrorBody"]] = None, **kwargs: Any ) -> None: """ @@ -107,6 +106,8 @@ def __init__( class ClusterProfile(_serialization.Model): """ClusterProfile represents a cluster profile. + Variables are only populated by the server, and will be ignored when sending a request. + :ivar pull_secret: The pull secret for the cluster. :vartype pull_secret: str :ivar domain: The domain for the cluster. @@ -118,14 +119,21 @@ class ClusterProfile(_serialization.Model): :ivar fips_validated_modules: If FIPS validated crypto modules are used. Known values are: "Disabled" and "Enabled". :vartype fips_validated_modules: str or ~azure.mgmt.redhatopenshift.models.FipsValidatedModules + :ivar oidc_issuer: The URL of the managed OIDC issuer in a workload identity cluster. + :vartype oidc_issuer: str """ + _validation = { + "oidc_issuer": {"readonly": True}, + } + _attribute_map = { "pull_secret": {"key": "pullSecret", "type": "str"}, "domain": {"key": "domain", "type": "str"}, "version": {"key": "version", "type": "str"}, "resource_group_id": {"key": "resourceGroupId", "type": "str"}, "fips_validated_modules": {"key": "fipsValidatedModules", "type": "str"}, + "oidc_issuer": {"key": "oidcIssuer", "type": "str"}, } def __init__( @@ -158,6 +166,7 @@ def __init__( self.version = version self.resource_group_id = resource_group_id self.fips_validated_modules = fips_validated_modules + self.oidc_issuer: Optional[str] = None class ConsoleProfile(_serialization.Model): @@ -180,7 +189,7 @@ class ConsoleProfile(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.url = None + self.url: Optional[str] = None class Display(_serialization.Model): @@ -289,7 +298,7 @@ def __init__( super().__init__(**kwargs) self.name = name self.visibility = visibility - self.ip = None + self.ip: Optional[str] = None class LoadBalancerProfile(_serialization.Model): @@ -322,195 +331,96 @@ def __init__(self, *, managed_outbound_ips: Optional["_models.ManagedOutboundIPs """ super().__init__(**kwargs) self.managed_outbound_ips = managed_outbound_ips - self.effective_outbound_ips = None + self.effective_outbound_ips: Optional[list["_models.EffectiveOutboundIP"]] = None -class Resource(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. +class ManagedOutboundIPs(_serialization.Model): + """ManagedOutboundIPs represents the desired managed outbound IPs for the cluster public load + balancer. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData + :ivar count: Count represents the desired number of IPv4 outbound IPs created and managed by + Azure for the cluster public load balancer. Allowed values are in the range of 1 - 20. The + default value is 1. + :vartype count: int """ - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, + "count": {"key": "count", "type": "int"}, } - def __init__(self, **kwargs: Any) -> None: - """ """ + def __init__(self, *, count: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword count: Count represents the desired number of IPv4 outbound IPs created and managed by + Azure for the cluster public load balancer. Allowed values are in the range of 1 - 20. The + default value is 1. + :paramtype count: int + """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None + self.count = count -class ProxyResource(Resource): - """The resource model definition for a Azure Resource Manager proxy resource. It will not have - tags and a location. +class ManagedServiceIdentity(_serialization.Model): + """Managed service identity (system assigned and/or user assigned identities). Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - """ - - -class MachinePool(ProxyResource): - """MachinePool represents a MachinePool. - - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar resources: - :vartype resources: str + :ivar principal_id: The service principal ID of the system assigned identity. This property + will only be provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the system assigned identity. This property will only be + provided for a system assigned identity. + :vartype tenant_id: str + :ivar type: Type of managed service identity (where both SystemAssigned and UserAssigned types + are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and + "SystemAssigned,UserAssigned". + :vartype type: str or ~azure.mgmt.redhatopenshift.models.ManagedServiceIdentityType + :ivar user_assigned_identities: The set of user assigned identities associated with the + resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + The dictionary values can be empty objects ({}) in requests. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.redhatopenshift.models.UserAssignedIdentity] """ _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + "type": {"required": True}, } _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "resources": {"key": "properties.resources", "type": "str"}, - } - - def __init__(self, *, resources: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword resources: - :paramtype resources: str - """ - super().__init__(**kwargs) - self.resources = resources - - -class MachinePoolList(_serialization.Model): - """MachinePoolList represents a list of MachinePools. - - :ivar value: The list of Machine Pools. - :vartype value: list[~azure.mgmt.redhatopenshift.models.MachinePool] - :ivar next_link: The link used to get the next page of operations. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[MachinePool]"}, - "next_link": {"key": "nextLink", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, } def __init__( - self, *, value: Optional[List["_models.MachinePool"]] = None, next_link: Optional[str] = None, **kwargs: Any + self, + *, + type: Union[str, "_models.ManagedServiceIdentityType"], + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentity"]] = None, + **kwargs: Any ) -> None: """ - :keyword value: The list of Machine Pools. - :paramtype value: list[~azure.mgmt.redhatopenshift.models.MachinePool] - :keyword next_link: The link used to get the next page of operations. - :paramtype next_link: str + :keyword type: Type of managed service identity (where both SystemAssigned and UserAssigned + types are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and + "SystemAssigned,UserAssigned". + :paramtype type: str or ~azure.mgmt.redhatopenshift.models.ManagedServiceIdentityType + :keyword user_assigned_identities: The set of user assigned identities associated with the + resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + The dictionary values can be empty objects ({}) in requests. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.redhatopenshift.models.UserAssignedIdentity] """ super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class MachinePoolUpdate(_serialization.Model): - """MachinePool represents a MachinePool. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar resources: - :vartype resources: str - """ - - _validation = { - "system_data": {"readonly": True}, - } - - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "resources": {"key": "properties.resources", "type": "str"}, - } - - def __init__(self, *, resources: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword resources: - :paramtype resources: str - """ - super().__init__(**kwargs) - self.system_data = None - self.resources = resources - - -class ManagedOutboundIPs(_serialization.Model): - """ManagedOutboundIPs represents the desired managed outbound IPs for the cluster public load - balancer. - - :ivar count: Count represents the desired number of IPv4 outbound IPs created and managed by - Azure for the cluster public load balancer. Allowed values are in the range of 1 - 20. The - default value is 1. - :vartype count: int - """ - - _attribute_map = { - "count": {"key": "count", "type": "int"}, - } - - def __init__(self, *, count: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword count: Count represents the desired number of IPv4 outbound IPs created and managed by - Azure for the cluster public load balancer. Allowed values are in the range of 1 - 20. The - default value is 1. - :paramtype count: int - """ - super().__init__(**kwargs) - self.count = count + self.principal_id: Optional[str] = None + self.tenant_id: Optional[str] = None + self.type = type + self.user_assigned_identities = user_assigned_identities class MasterProfile(_serialization.Model): @@ -620,6 +530,47 @@ def __init__( self.preconfigured_nsg = preconfigured_nsg +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + + class TrackedResource(Resource): """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. @@ -628,8 +579,8 @@ class TrackedResource(Resource): All required parameters must be populated in order to send to server. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -662,7 +613,7 @@ class TrackedResource(Resource): "location": {"key": "location", "type": "str"}, } - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + def __init__(self, *, location: str, tags: Optional[dict[str, str]] = None, **kwargs: Any) -> None: """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] @@ -674,15 +625,15 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.location = location -class OpenShiftCluster(TrackedResource): # pylint: disable=too-many-instance-attributes +class OpenShiftCluster(TrackedResource): """OpenShiftCluster represents an Azure Red Hat OpenShift cluster. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to server. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -696,6 +647,9 @@ class OpenShiftCluster(TrackedResource): # pylint: disable=too-many-instance-at :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str + :ivar identity: Identity stores information about the cluster MSI(s) in a workload identity + cluster. + :vartype identity: ~azure.mgmt.redhatopenshift.models.ManagedServiceIdentity :ivar provisioning_state: The cluster provisioning state. Known values are: "AdminUpdating", "Canceled", "Creating", "Deleting", "Failed", "Succeeded", and "Updating". :vartype provisioning_state: str or ~azure.mgmt.redhatopenshift.models.ProvisioningState @@ -705,6 +659,9 @@ class OpenShiftCluster(TrackedResource): # pylint: disable=too-many-instance-at :vartype console_profile: ~azure.mgmt.redhatopenshift.models.ConsoleProfile :ivar service_principal_profile: The cluster service principal profile. :vartype service_principal_profile: ~azure.mgmt.redhatopenshift.models.ServicePrincipalProfile + :ivar platform_workload_identity_profile: The workload identity profile. + :vartype platform_workload_identity_profile: + ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityProfile :ivar network_profile: The cluster network profile. :vartype network_profile: ~azure.mgmt.redhatopenshift.models.NetworkProfile :ivar master_profile: The cluster master profile. @@ -735,10 +692,15 @@ class OpenShiftCluster(TrackedResource): # pylint: disable=too-many-instance-at "system_data": {"key": "systemData", "type": "SystemData"}, "tags": {"key": "tags", "type": "{str}"}, "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "cluster_profile": {"key": "properties.clusterProfile", "type": "ClusterProfile"}, "console_profile": {"key": "properties.consoleProfile", "type": "ConsoleProfile"}, "service_principal_profile": {"key": "properties.servicePrincipalProfile", "type": "ServicePrincipalProfile"}, + "platform_workload_identity_profile": { + "key": "properties.platformWorkloadIdentityProfile", + "type": "PlatformWorkloadIdentityProfile", + }, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "master_profile": {"key": "properties.masterProfile", "type": "MasterProfile"}, "worker_profiles": {"key": "properties.workerProfiles", "type": "[WorkerProfile]"}, @@ -751,16 +713,18 @@ def __init__( self, *, location: str, - tags: Optional[Dict[str, str]] = None, + tags: Optional[dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, cluster_profile: Optional["_models.ClusterProfile"] = None, console_profile: Optional["_models.ConsoleProfile"] = None, service_principal_profile: Optional["_models.ServicePrincipalProfile"] = None, + platform_workload_identity_profile: Optional["_models.PlatformWorkloadIdentityProfile"] = None, network_profile: Optional["_models.NetworkProfile"] = None, master_profile: Optional["_models.MasterProfile"] = None, - worker_profiles: Optional[List["_models.WorkerProfile"]] = None, + worker_profiles: Optional[list["_models.WorkerProfile"]] = None, apiserver_profile: Optional["_models.APIServerProfile"] = None, - ingress_profiles: Optional[List["_models.IngressProfile"]] = None, + ingress_profiles: Optional[list["_models.IngressProfile"]] = None, **kwargs: Any ) -> None: """ @@ -768,6 +732,9 @@ def __init__( :paramtype tags: dict[str, str] :keyword location: The geo-location where the resource lives. Required. :paramtype location: str + :keyword identity: Identity stores information about the cluster MSI(s) in a workload identity + cluster. + :paramtype identity: ~azure.mgmt.redhatopenshift.models.ManagedServiceIdentity :keyword provisioning_state: The cluster provisioning state. Known values are: "AdminUpdating", "Canceled", "Creating", "Deleting", "Failed", "Succeeded", and "Updating". :paramtype provisioning_state: str or ~azure.mgmt.redhatopenshift.models.ProvisioningState @@ -778,6 +745,9 @@ def __init__( :keyword service_principal_profile: The cluster service principal profile. :paramtype service_principal_profile: ~azure.mgmt.redhatopenshift.models.ServicePrincipalProfile + :keyword platform_workload_identity_profile: The workload identity profile. + :paramtype platform_workload_identity_profile: + ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityProfile :keyword network_profile: The cluster network profile. :paramtype network_profile: ~azure.mgmt.redhatopenshift.models.NetworkProfile :keyword master_profile: The cluster master profile. @@ -790,14 +760,16 @@ def __init__( :paramtype ingress_profiles: list[~azure.mgmt.redhatopenshift.models.IngressProfile] """ super().__init__(tags=tags, location=location, **kwargs) + self.identity = identity self.provisioning_state = provisioning_state self.cluster_profile = cluster_profile self.console_profile = console_profile self.service_principal_profile = service_principal_profile + self.platform_workload_identity_profile = platform_workload_identity_profile self.network_profile = network_profile self.master_profile = master_profile self.worker_profiles = worker_profiles - self.worker_profiles_status = None + self.worker_profiles_status: Optional[list["_models.WorkerProfile"]] = None self.apiserver_profile = apiserver_profile self.ingress_profiles = ingress_profiles @@ -867,7 +839,7 @@ class OpenShiftClusterList(_serialization.Model): def __init__( self, *, - value: Optional[List["_models.OpenShiftCluster"]] = None, + value: Optional[list["_models.OpenShiftCluster"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: @@ -882,15 +854,16 @@ def __init__( self.next_link = next_link -class OpenShiftClusterUpdate(_serialization.Model): # pylint: disable=too-many-instance-attributes +class OpenShiftClusterUpdate(_serialization.Model): """OpenShiftCluster represents an Azure Red Hat OpenShift cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar tags: The resource tags. :vartype tags: dict[str, str] - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData + :ivar identity: Identity stores information about the cluster MSI(s) in a workload identity + cluster. + :vartype identity: ~azure.mgmt.redhatopenshift.models.ManagedServiceIdentity :ivar provisioning_state: The cluster provisioning state. Known values are: "AdminUpdating", "Canceled", "Creating", "Deleting", "Failed", "Succeeded", and "Updating". :vartype provisioning_state: str or ~azure.mgmt.redhatopenshift.models.ProvisioningState @@ -900,6 +873,9 @@ class OpenShiftClusterUpdate(_serialization.Model): # pylint: disable=too-many- :vartype console_profile: ~azure.mgmt.redhatopenshift.models.ConsoleProfile :ivar service_principal_profile: The cluster service principal profile. :vartype service_principal_profile: ~azure.mgmt.redhatopenshift.models.ServicePrincipalProfile + :ivar platform_workload_identity_profile: The workload identity profile. + :vartype platform_workload_identity_profile: + ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityProfile :ivar network_profile: The cluster network profile. :vartype network_profile: ~azure.mgmt.redhatopenshift.models.NetworkProfile :ivar master_profile: The cluster master profile. @@ -915,17 +891,20 @@ class OpenShiftClusterUpdate(_serialization.Model): # pylint: disable=too-many- """ _validation = { - "system_data": {"readonly": True}, "worker_profiles_status": {"readonly": True}, } _attribute_map = { "tags": {"key": "tags", "type": "{str}"}, - "system_data": {"key": "systemData", "type": "SystemData"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "cluster_profile": {"key": "properties.clusterProfile", "type": "ClusterProfile"}, "console_profile": {"key": "properties.consoleProfile", "type": "ConsoleProfile"}, "service_principal_profile": {"key": "properties.servicePrincipalProfile", "type": "ServicePrincipalProfile"}, + "platform_workload_identity_profile": { + "key": "properties.platformWorkloadIdentityProfile", + "type": "PlatformWorkloadIdentityProfile", + }, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "master_profile": {"key": "properties.masterProfile", "type": "MasterProfile"}, "worker_profiles": {"key": "properties.workerProfiles", "type": "[WorkerProfile]"}, @@ -937,21 +916,26 @@ class OpenShiftClusterUpdate(_serialization.Model): # pylint: disable=too-many- def __init__( self, *, - tags: Optional[Dict[str, str]] = None, + tags: Optional[dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, cluster_profile: Optional["_models.ClusterProfile"] = None, console_profile: Optional["_models.ConsoleProfile"] = None, service_principal_profile: Optional["_models.ServicePrincipalProfile"] = None, + platform_workload_identity_profile: Optional["_models.PlatformWorkloadIdentityProfile"] = None, network_profile: Optional["_models.NetworkProfile"] = None, master_profile: Optional["_models.MasterProfile"] = None, - worker_profiles: Optional[List["_models.WorkerProfile"]] = None, + worker_profiles: Optional[list["_models.WorkerProfile"]] = None, apiserver_profile: Optional["_models.APIServerProfile"] = None, - ingress_profiles: Optional[List["_models.IngressProfile"]] = None, + ingress_profiles: Optional[list["_models.IngressProfile"]] = None, **kwargs: Any ) -> None: """ :keyword tags: The resource tags. :paramtype tags: dict[str, str] + :keyword identity: Identity stores information about the cluster MSI(s) in a workload identity + cluster. + :paramtype identity: ~azure.mgmt.redhatopenshift.models.ManagedServiceIdentity :keyword provisioning_state: The cluster provisioning state. Known values are: "AdminUpdating", "Canceled", "Creating", "Deleting", "Failed", "Succeeded", and "Updating". :paramtype provisioning_state: str or ~azure.mgmt.redhatopenshift.models.ProvisioningState @@ -962,6 +946,9 @@ def __init__( :keyword service_principal_profile: The cluster service principal profile. :paramtype service_principal_profile: ~azure.mgmt.redhatopenshift.models.ServicePrincipalProfile + :keyword platform_workload_identity_profile: The workload identity profile. + :paramtype platform_workload_identity_profile: + ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityProfile :keyword network_profile: The cluster network profile. :paramtype network_profile: ~azure.mgmt.redhatopenshift.models.NetworkProfile :keyword master_profile: The cluster master profile. @@ -975,26 +962,47 @@ def __init__( """ super().__init__(**kwargs) self.tags = tags - self.system_data = None + self.identity = identity self.provisioning_state = provisioning_state self.cluster_profile = cluster_profile self.console_profile = console_profile self.service_principal_profile = service_principal_profile + self.platform_workload_identity_profile = platform_workload_identity_profile self.network_profile = network_profile self.master_profile = master_profile self.worker_profiles = worker_profiles - self.worker_profiles_status = None + self.worker_profiles_status: Optional[list["_models.WorkerProfile"]] = None self.apiserver_profile = apiserver_profile self.ingress_profiles = ingress_profiles +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have + tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData + """ + + class OpenShiftVersion(ProxyResource): """OpenShiftVersion represents an OpenShift version that can be installed. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1049,7 +1057,7 @@ class OpenShiftVersionList(_serialization.Model): def __init__( self, *, - value: Optional[List["_models.OpenShiftVersion"]] = None, + value: Optional[list["_models.OpenShiftVersion"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: @@ -1120,7 +1128,7 @@ class OperationList(_serialization.Model): } def __init__( - self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + self, *, value: Optional[list["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: List of operations supported by the resource provider. @@ -1133,247 +1141,128 @@ def __init__( self.next_link = next_link -class Secret(ProxyResource): - """Secret represents a secret. +class PlatformWorkloadIdentity(_serialization.Model): + """PlatformWorkloadIdentity stores information representing a single workload identity. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar secret_resources: The Secrets Resources. - :vartype secret_resources: str + :ivar resource_id: The resource ID of the PlatformWorkloadIdentity resource. + :vartype resource_id: str + :ivar client_id: The ClientID of the PlatformWorkloadIdentity resource. + :vartype client_id: str + :ivar object_id: The ObjectID of the PlatformWorkloadIdentity resource. + :vartype object_id: str """ _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, + "client_id": {"readonly": True}, + "object_id": {"readonly": True}, } _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "secret_resources": {"key": "properties.secretResources", "type": "str"}, + "resource_id": {"key": "resourceId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + "object_id": {"key": "objectId", "type": "str"}, } - def __init__(self, *, secret_resources: Optional[str] = None, **kwargs: Any) -> None: + def __init__(self, *, resource_id: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword secret_resources: The Secrets Resources. - :paramtype secret_resources: str + :keyword resource_id: The resource ID of the PlatformWorkloadIdentity resource. + :paramtype resource_id: str """ super().__init__(**kwargs) - self.secret_resources = secret_resources + self.resource_id = resource_id + self.client_id: Optional[str] = None + self.object_id: Optional[str] = None -class SecretList(_serialization.Model): - """SecretList represents a list of Secrets. +class PlatformWorkloadIdentityProfile(_serialization.Model): + """PlatformWorkloadIdentityProfile encapsulates all information that is specific to workload + identity clusters. - :ivar value: The list of secrets. - :vartype value: list[~azure.mgmt.redhatopenshift.models.Secret] - :ivar next_link: The link used to get the next page of operations. - :vartype next_link: str + :ivar upgradeable_to: UpgradeableTo stores a single OpenShift version a workload identity + cluster can be upgraded to. + :vartype upgradeable_to: str + :ivar platform_workload_identities: Dictionary of :code:``. + :vartype platform_workload_identities: dict[str, + ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentity] """ _attribute_map = { - "value": {"key": "value", "type": "[Secret]"}, - "next_link": {"key": "nextLink", "type": "str"}, + "upgradeable_to": {"key": "upgradeableTo", "type": "str"}, + "platform_workload_identities": {"key": "platformWorkloadIdentities", "type": "{PlatformWorkloadIdentity}"}, } def __init__( - self, *, value: Optional[List["_models.Secret"]] = None, next_link: Optional[str] = None, **kwargs: Any + self, + *, + upgradeable_to: Optional[str] = None, + platform_workload_identities: Optional[dict[str, "_models.PlatformWorkloadIdentity"]] = None, + **kwargs: Any ) -> None: """ - :keyword value: The list of secrets. - :paramtype value: list[~azure.mgmt.redhatopenshift.models.Secret] - :keyword next_link: The link used to get the next page of operations. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class SecretUpdate(_serialization.Model): - """Secret represents a secret. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar secret_resources: The Secrets Resources. - :vartype secret_resources: str - """ - - _validation = { - "system_data": {"readonly": True}, - } - - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "secret_resources": {"key": "properties.secretResources", "type": "str"}, - } - - def __init__(self, *, secret_resources: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword secret_resources: The Secrets Resources. - :paramtype secret_resources: str + :keyword upgradeable_to: UpgradeableTo stores a single OpenShift version a workload identity + cluster can be upgraded to. + :paramtype upgradeable_to: str + :keyword platform_workload_identities: Dictionary of :code:``. + :paramtype platform_workload_identities: dict[str, + ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentity] """ super().__init__(**kwargs) - self.system_data = None - self.secret_resources = secret_resources + self.upgradeable_to = upgradeable_to + self.platform_workload_identities = platform_workload_identities -class ServicePrincipalProfile(_serialization.Model): - """ServicePrincipalProfile represents a service principal profile. +class PlatformWorkloadIdentityRole(_serialization.Model): + """PlatformWorkloadIdentityRole represents a mapping from a particular OCP operator to the + built-in role that should be assigned to that operator's corresponding managed identity. - :ivar client_id: The client ID used for the cluster. - :vartype client_id: str - :ivar client_secret: The client secret used for the cluster. - :vartype client_secret: str + :ivar operator_name: OperatorName represents the name of the operator that this role is for. + :vartype operator_name: str + :ivar role_definition_name: RoleDefinitionName represents the name of the role. + :vartype role_definition_name: str + :ivar role_definition_id: RoleDefinitionID represents the resource ID of the role definition. + :vartype role_definition_id: str """ _attribute_map = { - "client_id": {"key": "clientId", "type": "str"}, - "client_secret": {"key": "clientSecret", "type": "str"}, - } - - def __init__(self, *, client_id: Optional[str] = None, client_secret: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword client_id: The client ID used for the cluster. - :paramtype client_id: str - :keyword client_secret: The client secret used for the cluster. - :paramtype client_secret: str - """ - super().__init__(**kwargs) - self.client_id = client_id - self.client_secret = client_secret - - -class SyncIdentityProvider(ProxyResource): - """SyncIdentityProvider represents a SyncIdentityProvider. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar resources: - :vartype resources: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "resources": {"key": "properties.resources", "type": "str"}, - } - - def __init__(self, *, resources: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword resources: - :paramtype resources: str - """ - super().__init__(**kwargs) - self.resources = resources - - -class SyncIdentityProviderList(_serialization.Model): - """SyncSetList represents a list of SyncSets. - - :ivar value: The list of sync identity providers. - :vartype value: list[~azure.mgmt.redhatopenshift.models.SyncIdentityProvider] - :ivar next_link: The link used to get the next page of operations. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[SyncIdentityProvider]"}, - "next_link": {"key": "nextLink", "type": "str"}, + "operator_name": {"key": "operatorName", "type": "str"}, + "role_definition_name": {"key": "roleDefinitionName", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, } def __init__( self, *, - value: Optional[List["_models.SyncIdentityProvider"]] = None, - next_link: Optional[str] = None, + operator_name: Optional[str] = None, + role_definition_name: Optional[str] = None, + role_definition_id: Optional[str] = None, **kwargs: Any ) -> None: """ - :keyword value: The list of sync identity providers. - :paramtype value: list[~azure.mgmt.redhatopenshift.models.SyncIdentityProvider] - :keyword next_link: The link used to get the next page of operations. - :paramtype next_link: str + :keyword operator_name: OperatorName represents the name of the operator that this role is for. + :paramtype operator_name: str + :keyword role_definition_name: RoleDefinitionName represents the name of the role. + :paramtype role_definition_name: str + :keyword role_definition_id: RoleDefinitionID represents the resource ID of the role + definition. + :paramtype role_definition_id: str """ super().__init__(**kwargs) - self.value = value - self.next_link = next_link + self.operator_name = operator_name + self.role_definition_name = role_definition_name + self.role_definition_id = role_definition_id -class SyncIdentityProviderUpdate(_serialization.Model): - """SyncIdentityProvider represents a SyncIdentityProvider. +class PlatformWorkloadIdentityRoleSet(ProxyResource): + """PlatformWorkloadIdentityRoleSet represents a mapping from the names of OCP operators to the + built-in roles that should be assigned to those operator's corresponding managed identities for + a particular OCP version. Variables are only populated by the server, and will be ignored when sending a request. - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar resources: - :vartype resources: str - """ - - _validation = { - "system_data": {"readonly": True}, - } - - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "resources": {"key": "properties.resources", "type": "str"}, - } - - def __init__(self, *, resources: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword resources: - :paramtype resources: str - """ - super().__init__(**kwargs) - self.system_data = None - self.resources = resources - - -class SyncSet(ProxyResource): - """SyncSet represents a SyncSet for an Azure Red Hat OpenShift Cluster. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1383,8 +1272,13 @@ class SyncSet(ProxyResource): :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar resources: Resources represents the SyncSets configuration. - :vartype resources: str + :ivar open_shift_version: OpenShiftVersion represents the version associated with this set of + roles. + :vartype open_shift_version: str + :ivar platform_workload_identity_roles: PlatformWorkloadIdentityRoles represents the set of + roles associated with this version. + :vartype platform_workload_identity_roles: + list[~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRole] """ _validation = { @@ -1399,39 +1293,59 @@ class SyncSet(ProxyResource): "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "system_data": {"key": "systemData", "type": "SystemData"}, - "resources": {"key": "properties.resources", "type": "str"}, + "open_shift_version": {"key": "properties.openShiftVersion", "type": "str"}, + "platform_workload_identity_roles": { + "key": "properties.platformWorkloadIdentityRoles", + "type": "[PlatformWorkloadIdentityRole]", + }, } - def __init__(self, *, resources: Optional[str] = None, **kwargs: Any) -> None: + def __init__( + self, + *, + open_shift_version: Optional[str] = None, + platform_workload_identity_roles: Optional[list["_models.PlatformWorkloadIdentityRole"]] = None, + **kwargs: Any + ) -> None: """ - :keyword resources: Resources represents the SyncSets configuration. - :paramtype resources: str + :keyword open_shift_version: OpenShiftVersion represents the version associated with this set + of roles. + :paramtype open_shift_version: str + :keyword platform_workload_identity_roles: PlatformWorkloadIdentityRoles represents the set of + roles associated with this version. + :paramtype platform_workload_identity_roles: + list[~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRole] """ super().__init__(**kwargs) - self.resources = resources + self.open_shift_version = open_shift_version + self.platform_workload_identity_roles = platform_workload_identity_roles -class SyncSetList(_serialization.Model): - """SyncSetList represents a list of SyncSets. +class PlatformWorkloadIdentityRoleSetList(_serialization.Model): + """PlatformWorkloadIdentityRoleSetList represents a List of role sets. - :ivar value: The list of syncsets. - :vartype value: list[~azure.mgmt.redhatopenshift.models.SyncSet] - :ivar next_link: The link used to get the next page of operations. + :ivar value: The list of role sets. + :vartype value: list[~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet] + :ivar next_link: Next Link to next operation. :vartype next_link: str """ _attribute_map = { - "value": {"key": "value", "type": "[SyncSet]"}, + "value": {"key": "value", "type": "[PlatformWorkloadIdentityRoleSet]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, *, value: Optional[List["_models.SyncSet"]] = None, next_link: Optional[str] = None, **kwargs: Any + self, + *, + value: Optional[list["_models.PlatformWorkloadIdentityRoleSet"]] = None, + next_link: Optional[str] = None, + **kwargs: Any ) -> None: """ - :keyword value: The list of syncsets. - :paramtype value: list[~azure.mgmt.redhatopenshift.models.SyncSet] - :keyword next_link: The link used to get the next page of operations. + :keyword value: The list of role sets. + :paramtype value: list[~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet] + :keyword next_link: Next Link to next operation. :paramtype next_link: str """ super().__init__(**kwargs) @@ -1439,34 +1353,30 @@ def __init__( self.next_link = next_link -class SyncSetUpdate(_serialization.Model): - """SyncSet represents a SyncSet for an Azure Red Hat OpenShift Cluster. - - Variables are only populated by the server, and will be ignored when sending a request. +class ServicePrincipalProfile(_serialization.Model): + """ServicePrincipalProfile represents a service principal profile. - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.redhatopenshift.models.SystemData - :ivar resources: Resources represents the SyncSets configuration. - :vartype resources: str + :ivar client_id: The client ID used for the cluster. + :vartype client_id: str + :ivar client_secret: The client secret used for the cluster. + :vartype client_secret: str """ - _validation = { - "system_data": {"readonly": True}, - } - _attribute_map = { - "system_data": {"key": "systemData", "type": "SystemData"}, - "resources": {"key": "properties.resources", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + "client_secret": {"key": "clientSecret", "type": "str"}, } - def __init__(self, *, resources: Optional[str] = None, **kwargs: Any) -> None: + def __init__(self, *, client_id: Optional[str] = None, client_secret: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword resources: Resources represents the SyncSets configuration. - :paramtype resources: str + :keyword client_id: The client ID used for the cluster. + :paramtype client_id: str + :keyword client_secret: The client secret used for the cluster. + :paramtype client_secret: str """ super().__init__(**kwargs) - self.system_data = None - self.resources = resources + self.client_id = client_id + self.client_secret = client_secret class SystemData(_serialization.Model): @@ -1533,6 +1443,34 @@ def __init__( self.last_modified_at = last_modified_at +class UserAssignedIdentity(_serialization.Model): + """User assigned identity properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of the assigned identity. + :vartype principal_id: str + :ivar client_id: The client ID of the assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.client_id: Optional[str] = None + + class WorkerProfile(_serialization.Model): """WorkerProfile represents a worker profile. diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/__init__.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/__init__.py index f03257fe6903..0940c895da8b 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/__init__.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/__init__.py @@ -5,27 +5,29 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._open_shift_versions_operations import OpenShiftVersionsOperations -from ._open_shift_clusters_operations import OpenShiftClustersOperations -from ._machine_pools_operations import MachinePoolsOperations -from ._secrets_operations import SecretsOperations -from ._sync_identity_providers_operations import SyncIdentityProvidersOperations -from ._sync_sets_operations import SyncSetsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._open_shift_versions_operations import OpenShiftVersionsOperations # type: ignore +from ._platform_workload_identity_role_sets_operations import PlatformWorkloadIdentityRoleSetsOperations # type: ignore +from ._platform_workload_identity_role_set_operations import PlatformWorkloadIdentityRoleSetOperations # type: ignore +from ._open_shift_clusters_operations import OpenShiftClustersOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Operations", "OpenShiftVersionsOperations", + "PlatformWorkloadIdentityRoleSetsOperations", + "PlatformWorkloadIdentityRoleSetOperations", "OpenShiftClustersOperations", - "MachinePoolsOperations", - "SecretsOperations", - "SyncIdentityProvidersOperations", - "SyncSetsOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_machine_pools_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_machine_pools_operations.py deleted file mode 100644 index 2f081db2d010..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_machine_pools_operations.py +++ /dev/null @@ -1,796 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftCluster/{resourceName}/machinePools", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/machinePool/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/machinePool/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/machinePool/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/machinePool/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -class MachinePoolsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.AzureRedHatOpenShiftClient`'s - :attr:`machine_pools` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> Iterable["_models.MachinePool"]: - """Lists MachinePools that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either MachinePool or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redhatopenshift.models.MachinePool] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MachinePoolList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MachinePoolList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.MachinePool: - """Gets a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MachinePool] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MachinePool", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.MachinePool, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Creates or updates a MachinePool with the specified subscription, resource group and resource - name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Creates or updates a MachinePool with the specified subscription, resource group and resource - name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.MachinePool, IO[bytes]], - **kwargs: Any - ) -> _models.MachinePool: - """Creates or updates a MachinePool with the specified subscription, resource group and resource - name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Is either a MachinePool type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePool or IO[bytes] - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MachinePool] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "MachinePool") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MachinePool", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a MachinePool with the specified subscription, resource group and resource name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.MachinePoolUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Updates a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePoolUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.MachinePool: - """Updates a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.MachinePoolUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.MachinePool: - """Updates a MachinePool with the specified subscription, resource group and resource name. - - The operation returns properties of a MachinePool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the MachinePool resource. Required. - :type child_resource_name: str - :param parameters: The MachinePool resource. Is either a MachinePoolUpdate type or a IO[bytes] - type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.MachinePoolUpdate or IO[bytes] - :return: MachinePool or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.MachinePool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MachinePool] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "MachinePoolUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MachinePool", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_clusters_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_clusters_operations.py index 3827260193c8..aaf092831956 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_clusters_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_clusters_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,11 +6,12 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -31,14 +32,12 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer +from .._configuration import AzureRedHatOpenShiftClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -48,15 +47,15 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.RedHatOpenShift/openShiftClusters" - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -74,16 +73,16 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -104,16 +103,16 @@ def build_get_request(resource_group_name: str, resource_name: str, subscription _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters/{resourceName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -137,7 +136,7 @@ def build_create_or_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -145,9 +144,9 @@ def build_create_or_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters/{resourceName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -173,16 +172,16 @@ def build_delete_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters/{resourceName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -206,7 +205,7 @@ def build_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -214,9 +213,9 @@ def build_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters/{resourceName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -242,16 +241,16 @@ def build_list_admin_credentials_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters/{resourceName}/listAdminCredentials", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -275,16 +274,16 @@ def build_list_credentials_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftClusters/{resourceName}/listCredentials", - ) # pylint: disable=line-too-long + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), @@ -314,15 +313,17 @@ class OpenShiftClustersOperations: models = _models - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.OpenShiftCluster"]: + def list(self, **kwargs: Any) -> ItemPaged["_models.OpenShiftCluster"]: """Lists OpenShift clusters in the specified subscription. The operation returns properties of each OpenShift cluster. @@ -337,7 +338,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.OpenShiftCluster"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OpenShiftClusterList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -398,7 +399,7 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.OpenShiftCluster"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> ItemPaged["_models.OpenShiftCluster"]: """Lists OpenShift clusters in the specified subscription and resource group. The operation returns properties of each OpenShift cluster. @@ -416,7 +417,7 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OpenShiftClusterList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -492,7 +493,7 @@ def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _m :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftCluster :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -541,7 +542,7 @@ def _create_or_update_initial( parameters: Union[_models.OpenShiftCluster, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -736,7 +737,7 @@ def get_long_running_output(pipeline_response): ) def _delete_initial(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -845,7 +846,7 @@ def _update_initial( parameters: Union[_models.OpenShiftClusterUpdate, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -914,7 +915,8 @@ def begin_update( content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.OpenShiftCluster]: - """Updates a OpenShift cluster with the specified subscription, resource group and resource name. + """Creates or updates a OpenShift cluster with the specified subscription, resource group and + resource name. The operation returns properties of a OpenShift cluster. @@ -944,7 +946,8 @@ def begin_update( content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.OpenShiftCluster]: - """Updates a OpenShift cluster with the specified subscription, resource group and resource name. + """Creates or updates a OpenShift cluster with the specified subscription, resource group and + resource name. The operation returns properties of a OpenShift cluster. @@ -972,7 +975,8 @@ def begin_update( parameters: Union[_models.OpenShiftClusterUpdate, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.OpenShiftCluster]: - """Updates a OpenShift cluster with the specified subscription, resource group and resource name. + """Creates or updates a OpenShift cluster with the specified subscription, resource group and + resource name. The operation returns properties of a OpenShift cluster. @@ -1054,7 +1058,7 @@ def list_admin_credentials( :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftClusterAdminKubeconfig :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1114,7 +1118,7 @@ def list_credentials( :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftClusterCredentials :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_versions_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_versions_operations.py index 12d2e067cef5..21dce7374ad1 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_versions_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_open_shift_versions_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -26,14 +27,12 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer +from .._configuration import AzureRedHatOpenShiftClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -43,16 +42,16 @@ def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> Ht _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.RedHatOpenShift/locations/{location}/openshiftversions", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/providers/Microsoft.RedHatOpenShift/locations/{location}/openShiftVersions", + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "location": _SERIALIZER.url("location", location, "str", min_length=1), } @@ -67,6 +66,42 @@ def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> Ht return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) +def build_get_request(location: str, open_shift_version: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.RedHatOpenShift/locations/{location}/openShiftVersions/{openShiftVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=1), + "openShiftVersion": _SERIALIZER.url( + "open_shift_version", + open_shift_version, + "str", + max_length=63, + min_length=1, + pattern=r"^(\d+)\.(\d+)\.(\d+)(.*)", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + class OpenShiftVersionsOperations: """ .. warning:: @@ -79,20 +114,22 @@ class OpenShiftVersionsOperations: models = _models - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, location: str, **kwargs: Any) -> Iterable["_models.OpenShiftVersion"]: + def list(self, location: str, **kwargs: Any) -> ItemPaged["_models.OpenShiftVersion"]: """Lists all OpenShift versions available to install in the specified location. - The operation returns the installable OpenShift versions as strings. + The operation returns the installable OpenShift versions as a string. - :param location: The name of Azure region. Required. + :param location: The name of the Azure region. Required. :type location: str :return: An iterator like instance of either OpenShiftVersion or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redhatopenshift.models.OpenShiftVersion] @@ -104,7 +141,7 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.OpenShiftVersi api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OpenShiftVersionList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -164,3 +201,60 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, location: str, open_shift_version: str, **kwargs: Any) -> _models.OpenShiftVersion: + """Gets an available OpenShift version to install in the specified location. + + This operation returns installable OpenShift version as a string. + + :param location: The name of the Azure region. Required. + :type location: str + :param open_shift_version: The desired version value of the OpenShiftVersion resource. + Required. + :type open_shift_version: str + :return: OpenShiftVersion or the result of cls(response) + :rtype: ~azure.mgmt.redhatopenshift.models.OpenShiftVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OpenShiftVersion] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + open_shift_version=open_shift_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("OpenShiftVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_operations.py index 82b84ed4a039..207615d221d0 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -26,14 +26,12 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer +from .._configuration import AzureRedHatOpenShiftClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -43,7 +41,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -70,15 +68,17 @@ class Operations: models = _models - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: """Lists all of the available RP operations. The operation returns the RP operations. @@ -93,7 +93,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationList] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_set_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_set_operations.py new file mode 100644 index 000000000000..ccc87a7e632e --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_set_operations.py @@ -0,0 +1,154 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import AzureRedHatOpenShiftClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(location: str, open_shift_minor_version: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.RedHatOpenShift/locations/{location}/platformWorkloadIdentityRoleSets/{openShiftMinorVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=1), + "openShiftMinorVersion": _SERIALIZER.url( + "open_shift_minor_version", + open_shift_minor_version, + "str", + max_length=63, + min_length=1, + pattern=r"^(\d+)\.(\d+)", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PlatformWorkloadIdentityRoleSetOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redhatopenshift.AzureRedHatOpenShiftClient`'s + :attr:`platform_workload_identity_role_set` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, location: str, open_shift_minor_version: str, **kwargs: Any + ) -> _models.PlatformWorkloadIdentityRoleSet: + """Gets a mapping of an OpenShift version to identity requirements, which includes operatorName, + roleDefinitionName, roleDefinitionId, and serviceAccounts. + + This operation returns Platform Workload Identity Role Set as a string. + + :param location: The name of the Azure region. Required. + :type location: str + :param open_shift_minor_version: The desired version value of the + PlatformWorkloadIdentityRoleSet resource. Required. + :type open_shift_minor_version: str + :return: PlatformWorkloadIdentityRoleSet or the result of cls(response) + :rtype: ~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PlatformWorkloadIdentityRoleSet] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + open_shift_minor_version=open_shift_minor_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PlatformWorkloadIdentityRoleSet", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_sets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_sets_operations.py new file mode 100644 index 000000000000..4352ae6a58df --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_platform_workload_identity_role_sets_operations.py @@ -0,0 +1,170 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import AzureRedHatOpenShiftClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.RedHatOpenShift/locations/{location}/platformWorkloadIdentityRoleSets", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PlatformWorkloadIdentityRoleSetsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redhatopenshift.AzureRedHatOpenShiftClient`'s + :attr:`platform_workload_identity_role_sets` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureRedHatOpenShiftClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, location: str, **kwargs: Any) -> ItemPaged["_models.PlatformWorkloadIdentityRoleSet"]: + """Lists a mapping of OpenShift versions to identity requirements, which include operatorName, + roleDefinitionName, roleDefinitionId, and serviceAccounts. + + This operation returns a list of Platform Workload Identity Role Sets as a string. + + :param location: The name of the Azure region. Required. + :type location: str + :return: An iterator like instance of either PlatformWorkloadIdentityRoleSet or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.redhatopenshift.models.PlatformWorkloadIdentityRoleSet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PlatformWorkloadIdentityRoleSetList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PlatformWorkloadIdentityRoleSetList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_secrets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_secrets_operations.py deleted file mode 100644 index 50d3ed02c9fc..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_secrets_operations.py +++ /dev/null @@ -1,792 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftCluster/{resourceName}/secrets", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/secret/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/secret/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/secret/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/secret/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -class SecretsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.AzureRedHatOpenShiftClient`'s - :attr:`secrets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> Iterable["_models.Secret"]: - """Lists Secrets that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either Secret or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redhatopenshift.models.Secret] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SecretList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SecretList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.Secret: - """Gets a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.Secret] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Secret", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.Secret, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Creates or updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.Secret - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Creates or updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.Secret, IO[bytes]], - **kwargs: Any - ) -> _models.Secret: - """Creates or updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Is either a Secret type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.Secret or IO[bytes] - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Secret] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "Secret") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Secret", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a Secret with the specified subscription, resource group and resource name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SecretUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SecretUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.Secret: - """Updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SecretUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.Secret: - """Updates a Secret with the specified subscription, resource group and resource name. - - The operation returns properties of a Secret. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the Secret resource. Required. - :type child_resource_name: str - :param parameters: The Secret resource. Is either a SecretUpdate type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SecretUpdate or IO[bytes] - :return: Secret or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.Secret - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Secret] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SecretUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Secret", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_identity_providers_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_identity_providers_operations.py deleted file mode 100644 index a51a465de2cb..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_identity_providers_operations.py +++ /dev/null @@ -1,803 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftCluster/{resourceName}/syncIdentityProviders", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncIdentityProvider/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncIdentityProvider/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncIdentityProvider/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncIdentityProvider/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -class SyncIdentityProvidersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.AzureRedHatOpenShiftClient`'s - :attr:`sync_identity_providers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, resource_name: str, **kwargs: Any - ) -> Iterable["_models.SyncIdentityProvider"]: - """Lists SyncIdentityProviders that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either SyncIdentityProvider or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redhatopenshift.models.SyncIdentityProvider] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncIdentityProviderList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SyncIdentityProviderList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Gets a SyncIdentityProvider with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncIdentityProvider] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncIdentityProvider", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncIdentityProvider, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Creates or updates a SyncIdentityProvider with the specified subscription, resource group and - resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Creates or updates a SyncIdentityProvider with the specified subscription, resource group and - resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncIdentityProvider, IO[bytes]], - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Creates or updates a SyncIdentityProvider with the specified subscription, resource group and - resource name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Is either a SyncIdentityProvider type or - a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider or IO[bytes] - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncIdentityProvider] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncIdentityProvider") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncIdentityProvider", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncIdentityProviderUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Updates a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProviderUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Updates a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncIdentityProviderUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.SyncIdentityProvider: - """Updates a SyncIdentityProvider with the specified subscription, resource group and resource - name. - - The operation returns properties of a SyncIdentityProvider. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncIdentityProvider resource. Required. - :type child_resource_name: str - :param parameters: The SyncIdentityProvider resource. Is either a SyncIdentityProviderUpdate - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncIdentityProviderUpdate or IO[bytes] - :return: SyncIdentityProvider or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncIdentityProvider - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncIdentityProvider] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncIdentityProviderUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncIdentityProvider", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_sets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_sets_operations.py deleted file mode 100644 index 940fc9c62cc3..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/azure/mgmt/redhatopenshift/operations/_sync_sets_operations.py +++ /dev/null @@ -1,793 +0,0 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openShiftCluster/{resourceName}/syncSets", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncSet/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncSet/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncSet/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, resource_name: str, child_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-22")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RedHatOpenShift/openshiftclusters/{resourceName}/syncSet/{childResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "resourceName": _SERIALIZER.url( - "resource_name", - resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - "childResourceName": _SERIALIZER.url( - "child_resource_name", - child_resource_name, - "str", - max_length=63, - min_length=1, - pattern=r"^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]*[a-zA-Z0-9]$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -class SyncSetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redhatopenshift.AzureRedHatOpenShiftClient`'s - :attr:`sync_sets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> Iterable["_models.SyncSet"]: - """Lists SyncSets that belong to that Azure Red Hat OpenShift Cluster. - - The operation returns properties of each SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :return: An iterator like instance of either SyncSet or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redhatopenshift.models.SyncSet] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncSetList] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SyncSetList", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> _models.SyncSet: - """Gets a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SyncSet] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncSet", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncSet, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Creates or updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSet - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Creates or updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncSet, IO[bytes]], - **kwargs: Any - ) -> _models.SyncSet: - """Creates or updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Is either a SyncSet type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSet or IO[bytes] - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncSet] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncSet") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncSet", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, resource_name: str, child_resource_name: str, **kwargs: Any - ) -> None: - """Deletes a SyncSet with the specified subscription, resource group and resource name. - - The operation returns nothing. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: _models.SyncSetUpdate, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSetUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SyncSet: - """Updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update( - self, - resource_group_name: str, - resource_name: str, - child_resource_name: str, - parameters: Union[_models.SyncSetUpdate, IO[bytes]], - **kwargs: Any - ) -> _models.SyncSet: - """Updates a SyncSet with the specified subscription, resource group and resource name. - - The operation returns properties of a SyncSet. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param resource_name: The name of the OpenShift cluster resource. Required. - :type resource_name: str - :param child_resource_name: The name of the SyncSet resource. Required. - :type child_resource_name: str - :param parameters: The SyncSet resource. Is either a SyncSetUpdate type or a IO[bytes] type. - Required. - :type parameters: ~azure.mgmt.redhatopenshift.models.SyncSetUpdate or IO[bytes] - :return: SyncSet or the result of cls(response) - :rtype: ~azure.mgmt.redhatopenshift.models.SyncSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SyncSet] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "SyncSetUpdate") - - _request = build_update_request( - resource_group_name=resource_group_name, - resource_name=resource_name, - child_resource_name=child_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SyncSet", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_create_or_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_create_or_update.py deleted file mode 100644 index b1c40785811f..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_create_or_update.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python machine_pools_create_or_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.machine_pools.create_or_update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={ - "properties": { - "resources": "ewogICAgImFwaVZlcnNpb24iOiAiaGl2ZS5vcGVuc2hpZnQuaW8vdjEiLAogICAgImtpbmQiOiAiTWFjaGluZVBvb2wiLAogICAgIm1ldGFkYXRhIjogewogICAgICAgICJuYW1lIjogInRlc3QtY2x1c3Rlci13b3JrZXIiLAogICAgICAgICJuYW1lc3BhY2UiOiAiYXJvLWY2MGFlOGEyLWJjYTEtNDk4Ny05MDU2LVhYWFhYWFhYWFhYWCIKICAgIH0sCiAgICAic3BlYyI6IHsKICAgICAgICAiY2x1c3RlckRlcGxveW1lbnRSZWYiOiB7CiAgICAgICAgICAgICJuYW1lIjogInRlc3QtY2x1c3RlciIKICAgICAgICB9LAogICAgICAgICJuYW1lIjogIndvcmtlciIsCiAgICAgICAgInBsYXRmb3JtIjogewogICAgICAgICAgICAiYXdzIjogewogICAgICAgICAgICAgICAgInJvb3RWb2x1bWUiOiB7CiAgICAgICAgICAgICAgICAgICAgImlvcHMiOiAwLAogICAgICAgICAgICAgICAgICAgICJzaXplIjogMzAwLAogICAgICAgICAgICAgICAgICAgICJ0eXBlIjogImdwMyIKICAgICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICAgICAidHlwZSI6ICJtNS54bGFyZ2UiLAogICAgICAgICAgICAgICAgInpvbmVzIjogWwogICAgICAgICAgICAgICAgICAgICJ1cy1lYXN0LTFhIgogICAgICAgICAgICAgICAgXQogICAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgICAicmVwbGljYXMiOiAyCiAgICB9LAogICAgInN0YXR1cyI6IHsKICAgICAgICAiY29uZGl0aW9ucyI6IFsKICAgICAgICBdCiAgICB9Cn0K" - } - }, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/MachinePools_CreateOrUpdate.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_delete.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_delete.py deleted file mode 100644 index 807205d8a756..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_delete.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python machine_pools_delete.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.machine_pools.delete( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/MachinePools_Delete.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_get.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_get.py deleted file mode 100644 index 5f25448afad3..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_get.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python machine_pools_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.machine_pools.get( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/MachinePools_Get.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_list.py deleted file mode 100644 index e14ecd37cca0..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_list.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python machine_pools_list.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.machine_pools.list( - resource_group_name="resourceGroup", - resource_name="resourceName", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/MachinePools_List.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_update.py deleted file mode 100644 index b69db1b1a64b..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/machine_pools_update.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python machine_pools_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.machine_pools.update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={ - "properties": { - "resources": "ewogICAgImFwaVZlcnNpb24iOiAiaGl2ZS5vcGVuc2hpZnQuaW8vdjEiLAogICAgImtpbmQiOiAiTWFjaGluZVBvb2wiLAogICAgIm1ldGFkYXRhIjogewogICAgICAgICJuYW1lIjogInRlc3QtY2x1c3Rlci13b3JrZXIiLAogICAgICAgICJuYW1lc3BhY2UiOiAiYXJvLWY2MGFlOGEyLWJjYTEtNDk4Ny05MDU2LVhYWFhYWFhYWFhYWCIKICAgIH0sCiAgICAic3BlYyI6IHsKICAgICAgICAiY2x1c3RlckRlcGxveW1lbnRSZWYiOiB7CiAgICAgICAgICAgICJuYW1lIjogInRlc3QtY2x1c3RlciIKICAgICAgICB9LAogICAgICAgICJuYW1lIjogIndvcmtlciIsCiAgICAgICAgInBsYXRmb3JtIjogewogICAgICAgICAgICAiYXdzIjogewogICAgICAgICAgICAgICAgInJvb3RWb2x1bWUiOiB7CiAgICAgICAgICAgICAgICAgICAgImlvcHMiOiAwLAogICAgICAgICAgICAgICAgICAgICJzaXplIjogMzAwLAogICAgICAgICAgICAgICAgICAgICJ0eXBlIjogImdwMyIKICAgICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICAgICAidHlwZSI6ICJtNS54bGFyZ2UiLAogICAgICAgICAgICAgICAgInpvbmVzIjogWwogICAgICAgICAgICAgICAgICAgICJ1cy1lYXN0LTFhIgogICAgICAgICAgICAgICAgXQogICAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgICAicmVwbGljYXMiOiAyCiAgICB9LAogICAgInN0YXR1cyI6IHsKICAgICAgICAiY29uZGl0aW9ucyI6IFsKICAgICAgICBdCiAgICB9Cn0K" - } - }, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/MachinePools_Update.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_create_or_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_create_or_update.py index 97d2619267ca..cf1528fb4a55 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_create_or_update.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_create_or_update.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,13 +28,14 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.begin_create_or_update( resource_group_name="resourceGroup", resource_name="resourceName", parameters={ + "identity": {"type": "UserAssigned", "userAssignedIdentities": {"": {}}}, "location": "location", "properties": { "apiserverProfile": {"visibility": "Public"}, @@ -41,13 +43,13 @@ def main(): "domain": "cluster.location.aroapp.io", "fipsValidatedModules": "Enabled", "pullSecret": '{"auths":{"registry.connect.redhat.com":{"auth":""},"registry.redhat.io":{"auth":""}}}', - "resourceGroupId": "/subscriptions/subscriptionId/resourceGroups/clusterResourceGroup", + "resourceGroupId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clusterResourceGroup", }, "consoleProfile": {}, "ingressProfiles": [{"name": "default", "visibility": "Public"}], "masterProfile": { "encryptionAtHost": "Enabled", - "subnetId": "/subscriptions/subscriptionId/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/master", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/master", "vmSize": "Standard_D8s_v3", }, "networkProfile": { @@ -56,13 +58,14 @@ def main(): "preconfiguredNSG": "Disabled", "serviceCidr": "172.30.0.0/16", }, + "platformWorkloadIdentityProfile": {"platformWorkloadIdentities": {"": {}}}, "servicePrincipalProfile": {"clientId": "clientId", "clientSecret": "clientSecret"}, "workerProfiles": [ { "count": 3, "diskSizeGB": 128, "name": "worker", - "subnetId": "/subscriptions/subscriptionId/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/worker", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/worker", "vmSize": "Standard_D2s_v3", } ], @@ -73,6 +76,6 @@ def main(): print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_CreateOrUpdate.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_CreateOrUpdate.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_delete.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_delete.py index 1a1bf9eb0974..fc6dbd390b24 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_delete.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) client.open_shift_clusters.begin_delete( @@ -36,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_Delete.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_Delete.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_get.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_get.py index 261689a870fd..078cf6e1c776 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_get.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.get( @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_Get.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_Get.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list.py index b308e3461dca..bd1b5b7f532c 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.list() @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_List.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_List.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_admin_credentials.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_admin_credentials.py index bd9c72bd8d1f..2a399c8454e7 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_admin_credentials.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_admin_credentials.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.list_admin_credentials( @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_ListAdminCredentials.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_ListAdminCredentials.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_by_resource_group.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_by_resource_group.py index 8819390c96b6..6a53e0eed0a3 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_by_resource_group.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_by_resource_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.list_by_resource_group( @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_ListByResourceGroup.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_ListByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_credentials.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_credentials.py index 5baca2399d1e..4e97c6434292 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_credentials.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_list_credentials.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.list_credentials( @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_ListCredentials.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_ListCredentials.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_update.py index b32be42cb3b1..984160e9eb43 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_update.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_clusters_update.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,26 +28,27 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_clusters.begin_update( resource_group_name="resourceGroup", resource_name="resourceName", parameters={ + "identity": {"type": "UserAssigned", "userAssignedIdentities": {"": {}}}, "properties": { "apiserverProfile": {"visibility": "Public"}, "clusterProfile": { "domain": "cluster.location.aroapp.io", "fipsValidatedModules": "Enabled", "pullSecret": '{"auths":{"registry.connect.redhat.com":{"auth":""},"registry.redhat.io":{"auth":""}}}', - "resourceGroupId": "/subscriptions/subscriptionId/resourceGroups/clusterResourceGroup", + "resourceGroupId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clusterResourceGroup", }, "consoleProfile": {}, "ingressProfiles": [{"name": "default", "visibility": "Public"}], "masterProfile": { "encryptionAtHost": "Enabled", - "subnetId": "/subscriptions/subscriptionId/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/master", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/master", "vmSize": "Standard_D8s_v3", }, "networkProfile": { @@ -55,13 +57,14 @@ def main(): "preconfiguredNSG": "Disabled", "serviceCidr": "172.30.0.0/16", }, + "platformWorkloadIdentityProfile": {"platformWorkloadIdentities": {"": {}}}, "servicePrincipalProfile": {"clientId": "clientId", "clientSecret": "clientSecret"}, "workerProfiles": [ { "count": 3, "diskSizeGB": 128, "name": "worker", - "subnetId": "/subscriptions/subscriptionId/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/worker", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/vnetResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet/subnets/worker", "vmSize": "Standard_D2s_v3", } ], @@ -72,6 +75,6 @@ def main(): print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftClusters_Update.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftClusters_Update.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_get.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_get.py similarity index 77% rename from sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_get.py rename to sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_get.py index 173b6298d253..22bd9075ac44 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_get.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -15,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-redhatopenshift # USAGE - python secrets_get.py + python open_shift_versions_get.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -27,17 +28,16 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) - response = client.secrets.get( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", + response = client.open_shift_versions.get( + location="location", + open_shift_version="4.14.40", ) print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/Secrets_Get.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftVersions_Get.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_list.py index f9e321c3feef..e2d28c2f1151 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_list.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/open_shift_versions_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,7 +28,7 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.open_shift_versions.list( @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/OpenShiftVersions_List.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/OpenShiftVersions_List.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/operations_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/operations_list.py index a7acf4aa02b7..5003da79296d 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/operations_list.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/operations_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/Operations_List.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/Operations_List.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_create_or_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/platform_workload_identity_role_set_get.py similarity index 75% rename from sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_create_or_update.py rename to sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/platform_workload_identity_role_set_get.py index a1ce2c852fe8..487d5c9d650b 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_create_or_update.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/platform_workload_identity_role_set_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -15,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-redhatopenshift # USAGE - python secrets_create_or_update.py + python platform_workload_identity_role_set_get.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -27,18 +28,16 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) - response = client.secrets.create_or_update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={"properties": {}}, + response = client.platform_workload_identity_role_set.get( + location="location", + open_shift_minor_version="4.14", ) print(response) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/Secrets_CreateOrUpdate.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/PlatformWorkloadIdentityRoleSet_Get.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/platform_workload_identity_role_sets_list.py similarity index 77% rename from sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_list.py rename to sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/platform_workload_identity_role_sets_list.py index 675f3b91894a..abf583ba80a6 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_list.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/platform_workload_identity_role_sets_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -15,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-redhatopenshift # USAGE - python secrets_list.py + python platform_workload_identity_role_sets_list.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -27,17 +28,16 @@ def main(): client = AzureRedHatOpenShiftClient( credential=DefaultAzureCredential(), - subscription_id="subscriptionId", + subscription_id="00000000-0000-0000-0000-000000000000", ) - response = client.secrets.list( - resource_group_name="resourceGroup", - resource_name="resourceName", + response = client.platform_workload_identity_role_sets.list( + location="location", ) for item in response: print(item) -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/Secrets_List.json +# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/OpenShiftClusters/stable/2025-07-25/examples/PlatformWorkloadIdentityRoleSets_List.json if __name__ == "__main__": main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_delete.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_delete.py deleted file mode 100644 index 1441da1a46eb..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_delete.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python secrets_delete.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.secrets.delete( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/Secrets_Delete.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_update.py deleted file mode 100644 index 514139ce7c29..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/secrets_update.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python secrets_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.secrets.update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={"properties": {}}, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/Secrets_Update.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_create_or_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_create_or_update.py deleted file mode 100644 index d5577a75815b..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_create_or_update.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_identity_providers_create_or_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_identity_providers.create_or_update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={ - "properties": { - "resources": "ewogICAgImFwaVZlcnNpb24iOiAiaGl2ZS5vcGVuc2hpZnQuaW8vdjEiLAogICAgImtpbmQiOiAiU3luY0lkZW50aXR5UHJvdmlkZXIiLAogICAgIm1ldGFkYXRhIjogewogICAgICAgICJuYW1lIjogInRlc3QtY2x1c3RlciIsCiAgICAgICAgIm5hbWVzcGFjZSI6ICJhcm8tZjYwYWU4YTItYmNhMS00OTg3LTkwNTYtWFhYWFhYWFhYWFhYIgogICAgfSwKICAgICJzcGVjIjogewogICAgICAgICJjbHVzdGVyRGVwbG95bWVudFJlZnMiOiBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICJuYW1lIjogInRlc3QtY2x1c3RlciIKICAgICAgICAgICAgfQogICAgICAgIF0sCiAgICAgICAgImlkZW50aXR5UHJvdmlkZXJzIjogWwogICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAiaHRwYXNzd2QiOiB7CiAgICAgICAgICAgICAgICAgICAgImZpbGVEYXRhIjogewogICAgICAgICAgICAgICAgICAgICAgICAibmFtZSI6ICJodHBhc3N3ZC1zZWNyZXQiCiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgICAgICJtYXBwaW5nTWV0aG9kIjogImNsYWltIiwKICAgICAgICAgICAgICAgICJuYW1lIjogIkhUUGFzc3dkIiwKICAgICAgICAgICAgICAgICJ0eXBlIjogIkhUUGFzc3dkIgogICAgICAgICAgICB9CiAgICAgICAgXQogICAgfSwKICAgICJzdGF0dXMiOiB7fQp9Cg==" - } - }, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncIdentityProviders_CreateOrUpdate.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_delete.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_delete.py deleted file mode 100644 index d07c664e48ab..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_delete.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_identity_providers_delete.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.sync_identity_providers.delete( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncIdentityProviders_Delete.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_get.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_get.py deleted file mode 100644 index d13b706d6c32..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_get.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_identity_providers_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_identity_providers.get( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncIdentityProviders_Get.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_list.py deleted file mode 100644 index 850d42abcbb8..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_list.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_identity_providers_list.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_identity_providers.list( - resource_group_name="resourceGroup", - resource_name="resourceName", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncIdentityProviders_List.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_update.py deleted file mode 100644 index a8637c4bc430..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_identity_providers_update.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_identity_providers_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_identity_providers.update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={ - "properties": { - "resources": "ewogICAgImFwaVZlcnNpb24iOiAiaGl2ZS5vcGVuc2hpZnQuaW8vdjEiLAogICAgImtpbmQiOiAiU3luY0lkZW50aXR5UHJvdmlkZXIiLAogICAgIm1ldGFkYXRhIjogewogICAgICAgICJuYW1lIjogInRlc3QtY2x1c3RlciIsCiAgICAgICAgIm5hbWVzcGFjZSI6ICJhcm8tZjYwYWU4YTItYmNhMS00OTg3LTkwNTYtWFhYWFhYWFhYWFhYIgogICAgfSwKICAgICJzcGVjIjogewogICAgICAgICJjbHVzdGVyRGVwbG95bWVudFJlZnMiOiBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICJuYW1lIjogInRlc3QtY2x1c3RlciIKICAgICAgICAgICAgfQogICAgICAgIF0sCiAgICAgICAgImlkZW50aXR5UHJvdmlkZXJzIjogWwogICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAiaHRwYXNzd2QiOiB7CiAgICAgICAgICAgICAgICAgICAgImZpbGVEYXRhIjogewogICAgICAgICAgICAgICAgICAgICAgICAibmFtZSI6ICJodHBhc3N3ZC1zZWNyZXQiCiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgICAgICJtYXBwaW5nTWV0aG9kIjogImNsYWltIiwKICAgICAgICAgICAgICAgICJuYW1lIjogIkhUUGFzc3dkIiwKICAgICAgICAgICAgICAgICJ0eXBlIjogIkhUUGFzc3dkIgogICAgICAgICAgICB9CiAgICAgICAgXQogICAgfSwKICAgICJzdGF0dXMiOiB7fQp9Cg==" - } - }, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncIdentityProviders_Update.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_create_or_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_create_or_update.py deleted file mode 100644 index 85d85667547b..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_create_or_update.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_sets_create_or_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_sets.create_or_update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={ - "properties": { - "resources": "eyAKICAiYXBpVmVyc2lvbiI6ICJoaXZlLm9wZW5zaGlmdC5pby92MSIsCiAgImtpbmQiOiAiU3luY1NldCIsCiAgIm1ldGFkYXRhIjogewogICAgIm5hbWUiOiAic2FtcGxlIiwKICAgICJuYW1lc3BhY2UiOiAiYXJvLWY2MGFlOGEyLWJjYTEtNDk4Ny05MDU2LWYyZjZhMTgzN2NhYSIKICB9LAogICJzcGVjIjogewogICAgImNsdXN0ZXJEZXBsb3ltZW50UmVmcyI6IFtdLAogICAgInJlc291cmNlcyI6IFsKICAgICAgewogICAgICAgICJhcGlWZXJzaW9uIjogInYxIiwKICAgICAgICAia2luZCI6ICJDb25maWdNYXAiLAogICAgICAgICJtZXRhZGF0YSI6IHsKICAgICAgICAgICJuYW1lIjogIm15Y29uZmlnbWFwIgogICAgICAgIH0KICAgICAgfQogICAgXQogIH0KfQo=" - } - }, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncSets_CreateOrUpdate.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_delete.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_delete.py deleted file mode 100644 index a36c932c8361..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_delete.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_sets_delete.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - client.sync_sets.delete( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncSets_Delete.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_get.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_get.py deleted file mode 100644 index e2c1bb680ae5..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_get.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_sets_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_sets.get( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncSets_Get.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_list.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_list.py deleted file mode 100644 index fd74ad342b78..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_list.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_sets_list.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_sets.list( - resource_group_name="resourceGroup", - resource_name="resourceName", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncSets_List.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_update.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_update.py deleted file mode 100644 index 0245456fcab3..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_samples/sync_sets_update.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential - -from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-redhatopenshift -# USAGE - python sync_sets_update.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = AzureRedHatOpenShiftClient( - credential=DefaultAzureCredential(), - subscription_id="subscriptionId", - ) - - response = client.sync_sets.update( - resource_group_name="resourceGroup", - resource_name="resourceName", - child_resource_name="childResourceName", - parameters={ - "properties": { - "resources": "eyAKICAiYXBpVmVyc2lvbiI6ICJoaXZlLm9wZW5zaGlmdC5pby92MSIsCiAgImtpbmQiOiAiU3luY1NldCIsCiAgIm1ldGFkYXRhIjogewogICAgIm5hbWUiOiAic2FtcGxlIiwKICAgICJuYW1lc3BhY2UiOiAiYXJvLWY2MGFlOGEyLWJjYTEtNDk4Ny05MDU2LWYyZjZhMTgzN2NhYSIKICB9LAogICJzcGVjIjogewogICAgImNsdXN0ZXJEZXBsb3ltZW50UmVmcyI6IFtdLAogICAgInJlc291cmNlcyI6IFsKICAgICAgewogICAgICAgICJhcGlWZXJzaW9uIjogInYxIiwKICAgICAgICAia2luZCI6ICJDb25maWdNYXAiLAogICAgICAgICJtZXRhZGF0YSI6IHsKICAgICAgICAgICJuYW1lIjogIm15Y29uZmlnbWFwIgogICAgICAgIH0KICAgICAgfQogICAgXQogIH0KfQo=" - } - }, - ) - print(response) - - -# x-ms-original-file: specification/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/openshiftclusters/stable/2023-11-22/examples/SyncSets_Update.json -if __name__ == "__main__": - main() diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/conftest.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/conftest.py index 1d003dbdd652..4f728b9fae96 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/conftest.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/conftest.py @@ -18,7 +18,7 @@ load_dotenv() -# aovid record sensitive identity information in recordings +# For security, please avoid record sensitive identity information in recordings @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): azureredhatopenshift_subscription_id = os.environ.get( diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations.py index 4a277fa65254..4206536470e4 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations.py @@ -20,9 +20,9 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_list(self, resource_group): + def test_open_shift_clusters_list(self, resource_group): response = self.client.open_shift_clusters.list( - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r for r in response] # please add some check logic here by yourself @@ -30,10 +30,10 @@ def test_list(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_list_by_resource_group(self, resource_group): + def test_open_shift_clusters_list_by_resource_group(self, resource_group): response = self.client.open_shift_clusters.list_by_resource_group( resource_group_name=resource_group.name, - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r for r in response] # please add some check logic here by yourself @@ -41,11 +41,11 @@ def test_list_by_resource_group(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_get(self, resource_group): + def test_open_shift_clusters_get(self, resource_group): response = self.client.open_shift_clusters.get( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) # please add some check logic here by yourself @@ -53,7 +53,7 @@ def test_get(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_begin_create_or_update(self, resource_group): + def test_open_shift_clusters_begin_create_or_update(self, resource_group): response = self.client.open_shift_clusters.begin_create_or_update( resource_group_name=resource_group.name, resource_name="str", @@ -63,12 +63,19 @@ def test_begin_create_or_update(self, resource_group): "clusterProfile": { "domain": "str", "fipsValidatedModules": "str", + "oidcIssuer": "str", "pullSecret": "str", "resourceGroupId": "str", "version": "str", }, "consoleProfile": {"url": "str"}, "id": "str", + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, "ingressProfiles": [{"ip": "str", "name": "str", "visibility": "str"}], "masterProfile": { "diskEncryptionSetId": "str", @@ -87,6 +94,10 @@ def test_begin_create_or_update(self, resource_group): "preconfiguredNSG": "str", "serviceCidr": "str", }, + "platformWorkloadIdentityProfile": { + "platformWorkloadIdentities": {"str": {"clientId": "str", "objectId": "str", "resourceId": "str"}}, + "upgradeableTo": "str", + }, "provisioningState": "str", "servicePrincipalProfile": {"clientId": "str", "clientSecret": "str"}, "systemData": { @@ -122,7 +133,7 @@ def test_begin_create_or_update(self, resource_group): } ], }, - api_version="2023-11-22", + api_version="2025-07-25", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -130,11 +141,11 @@ def test_begin_create_or_update(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_begin_delete(self, resource_group): + def test_open_shift_clusters_begin_delete(self, resource_group): response = self.client.open_shift_clusters.begin_delete( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -142,7 +153,7 @@ def test_begin_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_begin_update(self, resource_group): + def test_open_shift_clusters_begin_update(self, resource_group): response = self.client.open_shift_clusters.begin_update( resource_group_name=resource_group.name, resource_name="str", @@ -151,11 +162,18 @@ def test_begin_update(self, resource_group): "clusterProfile": { "domain": "str", "fipsValidatedModules": "str", + "oidcIssuer": "str", "pullSecret": "str", "resourceGroupId": "str", "version": "str", }, "consoleProfile": {"url": "str"}, + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, "ingressProfiles": [{"ip": "str", "name": "str", "visibility": "str"}], "masterProfile": { "diskEncryptionSetId": "str", @@ -173,16 +191,12 @@ def test_begin_update(self, resource_group): "preconfiguredNSG": "str", "serviceCidr": "str", }, + "platformWorkloadIdentityProfile": { + "platformWorkloadIdentities": {"str": {"clientId": "str", "objectId": "str", "resourceId": "str"}}, + "upgradeableTo": "str", + }, "provisioningState": "str", "servicePrincipalProfile": {"clientId": "str", "clientSecret": "str"}, - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, "tags": {"str": "str"}, "workerProfiles": [ { @@ -207,7 +221,7 @@ def test_begin_update(self, resource_group): } ], }, - api_version="2023-11-22", + api_version="2025-07-25", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -215,11 +229,11 @@ def test_begin_update(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_list_admin_credentials(self, resource_group): + def test_open_shift_clusters_list_admin_credentials(self, resource_group): response = self.client.open_shift_clusters.list_admin_credentials( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) # please add some check logic here by yourself @@ -227,11 +241,11 @@ def test_list_admin_credentials(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_list_credentials(self, resource_group): + def test_open_shift_clusters_list_credentials(self, resource_group): response = self.client.open_shift_clusters.list_credentials( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) # please add some check logic here by yourself diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations_async.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations_async.py index 8983ff4be505..cec3c2dd670b 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations_async.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_clusters_operations_async.py @@ -21,9 +21,9 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_list(self, resource_group): + async def test_open_shift_clusters_list(self, resource_group): response = self.client.open_shift_clusters.list( - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r async for r in response] # please add some check logic here by yourself @@ -31,10 +31,10 @@ async def test_list(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_list_by_resource_group(self, resource_group): + async def test_open_shift_clusters_list_by_resource_group(self, resource_group): response = self.client.open_shift_clusters.list_by_resource_group( resource_group_name=resource_group.name, - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r async for r in response] # please add some check logic here by yourself @@ -42,11 +42,11 @@ async def test_list_by_resource_group(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_get(self, resource_group): + async def test_open_shift_clusters_get(self, resource_group): response = await self.client.open_shift_clusters.get( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) # please add some check logic here by yourself @@ -54,7 +54,7 @@ async def test_get(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_begin_create_or_update(self, resource_group): + async def test_open_shift_clusters_begin_create_or_update(self, resource_group): response = await ( await self.client.open_shift_clusters.begin_create_or_update( resource_group_name=resource_group.name, @@ -65,12 +65,19 @@ async def test_begin_create_or_update(self, resource_group): "clusterProfile": { "domain": "str", "fipsValidatedModules": "str", + "oidcIssuer": "str", "pullSecret": "str", "resourceGroupId": "str", "version": "str", }, "consoleProfile": {"url": "str"}, "id": "str", + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, "ingressProfiles": [{"ip": "str", "name": "str", "visibility": "str"}], "masterProfile": { "diskEncryptionSetId": "str", @@ -89,6 +96,12 @@ async def test_begin_create_or_update(self, resource_group): "preconfiguredNSG": "str", "serviceCidr": "str", }, + "platformWorkloadIdentityProfile": { + "platformWorkloadIdentities": { + "str": {"clientId": "str", "objectId": "str", "resourceId": "str"} + }, + "upgradeableTo": "str", + }, "provisioningState": "str", "servicePrincipalProfile": {"clientId": "str", "clientSecret": "str"}, "systemData": { @@ -124,7 +137,7 @@ async def test_begin_create_or_update(self, resource_group): } ], }, - api_version="2023-11-22", + api_version="2025-07-25", ) ).result() # call '.result()' to poll until service return final result @@ -133,12 +146,12 @@ async def test_begin_create_or_update(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_begin_delete(self, resource_group): + async def test_open_shift_clusters_begin_delete(self, resource_group): response = await ( await self.client.open_shift_clusters.begin_delete( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) ).result() # call '.result()' to poll until service return final result @@ -147,7 +160,7 @@ async def test_begin_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_begin_update(self, resource_group): + async def test_open_shift_clusters_begin_update(self, resource_group): response = await ( await self.client.open_shift_clusters.begin_update( resource_group_name=resource_group.name, @@ -157,11 +170,18 @@ async def test_begin_update(self, resource_group): "clusterProfile": { "domain": "str", "fipsValidatedModules": "str", + "oidcIssuer": "str", "pullSecret": "str", "resourceGroupId": "str", "version": "str", }, "consoleProfile": {"url": "str"}, + "identity": { + "type": "str", + "principalId": "str", + "tenantId": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, "ingressProfiles": [{"ip": "str", "name": "str", "visibility": "str"}], "masterProfile": { "diskEncryptionSetId": "str", @@ -179,16 +199,14 @@ async def test_begin_update(self, resource_group): "preconfiguredNSG": "str", "serviceCidr": "str", }, + "platformWorkloadIdentityProfile": { + "platformWorkloadIdentities": { + "str": {"clientId": "str", "objectId": "str", "resourceId": "str"} + }, + "upgradeableTo": "str", + }, "provisioningState": "str", "servicePrincipalProfile": {"clientId": "str", "clientSecret": "str"}, - "systemData": { - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - }, "tags": {"str": "str"}, "workerProfiles": [ { @@ -213,7 +231,7 @@ async def test_begin_update(self, resource_group): } ], }, - api_version="2023-11-22", + api_version="2025-07-25", ) ).result() # call '.result()' to poll until service return final result @@ -222,11 +240,11 @@ async def test_begin_update(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_list_admin_credentials(self, resource_group): + async def test_open_shift_clusters_list_admin_credentials(self, resource_group): response = await self.client.open_shift_clusters.list_admin_credentials( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) # please add some check logic here by yourself @@ -234,11 +252,11 @@ async def test_list_admin_credentials(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_list_credentials(self, resource_group): + async def test_open_shift_clusters_list_credentials(self, resource_group): response = await self.client.open_shift_clusters.list_credentials( resource_group_name=resource_group.name, resource_name="str", - api_version="2023-11-22", + api_version="2025-07-25", ) # please add some check logic here by yourself diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations.py index cf56e7397727..9dca344b1f2b 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations.py @@ -20,11 +20,23 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_list(self, resource_group): + def test_open_shift_versions_list(self, resource_group): response = self.client.open_shift_versions.list( location="str", - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r for r in response] # please add some check logic here by yourself # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_open_shift_versions_get(self, resource_group): + response = self.client.open_shift_versions.get( + location="str", + open_shift_version="str", + api_version="2025-07-25", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations_async.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations_async.py index f0a4299c977c..91fc0f1381ff 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations_async.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_open_shift_versions_operations_async.py @@ -21,11 +21,23 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_list(self, resource_group): + async def test_open_shift_versions_list(self, resource_group): response = self.client.open_shift_versions.list( location="str", - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r async for r in response] # please add some check logic here by yourself # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_open_shift_versions_get(self, resource_group): + response = await self.client.open_shift_versions.get( + location="str", + open_shift_version="str", + api_version="2025-07-25", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations.py index 1b121b0a67d5..82fd8ffdb277 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations.py @@ -20,9 +20,9 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_list(self, resource_group): + def test_operations_list(self, resource_group): response = self.client.operations.list( - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r for r in response] # please add some check logic here by yourself diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations_async.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations_async.py index 3e3e3df01417..2e1d5e1d73e4 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations_async.py +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_operations_async.py @@ -21,9 +21,9 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_list(self, resource_group): + async def test_operations_list(self, resource_group): response = self.client.operations.list( - api_version="2023-11-22", + api_version="2025-07-25", ) result = [r async for r in response] # please add some check logic here by yourself diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations.py new file mode 100644 index 000000000000..e4f26e15bb40 --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureRedHatOpenShiftPlatformWorkloadIdentityRoleSetOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureRedHatOpenShiftClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_platform_workload_identity_role_set_get(self, resource_group): + response = self.client.platform_workload_identity_role_set.get( + location="str", + open_shift_minor_version="str", + api_version="2025-07-25", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations_async.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations_async.py new file mode 100644 index 000000000000..a6237c0a6816 --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_set_operations_async.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.redhatopenshift.aio import AzureRedHatOpenShiftClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureRedHatOpenShiftPlatformWorkloadIdentityRoleSetOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureRedHatOpenShiftClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_platform_workload_identity_role_set_get(self, resource_group): + response = await self.client.platform_workload_identity_role_set.get( + location="str", + open_shift_minor_version="str", + api_version="2025-07-25", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations.py new file mode 100644 index 000000000000..2e7bc7acc6cd --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.redhatopenshift import AzureRedHatOpenShiftClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureRedHatOpenShiftPlatformWorkloadIdentityRoleSetsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureRedHatOpenShiftClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_platform_workload_identity_role_sets_list(self, resource_group): + response = self.client.platform_workload_identity_role_sets.list( + location="str", + api_version="2025-07-25", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations_async.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations_async.py new file mode 100644 index 000000000000..fc76eb71f1ae --- /dev/null +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/generated_tests/test_azure_red_hat_open_shift_platform_workload_identity_role_sets_operations_async.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.redhatopenshift.aio import AzureRedHatOpenShiftClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureRedHatOpenShiftPlatformWorkloadIdentityRoleSetsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureRedHatOpenShiftClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_platform_workload_identity_role_sets_list(self, resource_group): + response = self.client.platform_workload_identity_role_sets.list( + location="str", + api_version="2025-07-25", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/pyproject.toml b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/pyproject.toml index 540da07d41af..1abaaeec3df6 100644 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/pyproject.toml +++ b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/pyproject.toml @@ -1,6 +1,88 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-redhatopenshift" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Redhatopenshift Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.redhatopenshift._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + [tool.azure-sdk-build] breaking = false mypy = false pyright = false type_check_samples = false verifytypes = false + +[packaging] +package_name = "azure-mgmt-redhatopenshift" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "Red Hat Openshift Management" +package_doc_id = "" +is_stable = true +is_arm = true +title = "AzureRedHatOpenShiftClient" +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/sdk_packaging.toml b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/sdk_packaging.toml deleted file mode 100644 index 6a26b763158e..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/sdk_packaging.toml +++ /dev/null @@ -1,8 +0,0 @@ -[packaging] -package_name = "azure-mgmt-redhatopenshift" -package_nspkg = "azure-mgmt-nspkg" -package_pprint_name = "Red Hat Openshift Management" -package_doc_id = "" -is_stable = true -is_arm = true -title = "AzureRedHatOpenShiftClient" diff --git a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/setup.py b/sdk/redhatopenshift/azure-mgmt-redhatopenshift/setup.py deleted file mode 100644 index 49d37ccedc5f..000000000000 --- a/sdk/redhatopenshift/azure-mgmt-redhatopenshift/setup.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/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 -from io import open -from setuptools import find_packages, setup - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-mgmt-redhatopenshift" -PACKAGE_PPRINT_NAME = "Red Hat Openshift Management" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace("-", "/") -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace("-", ".") - -# Version extraction inspired from 'requests' -with open( - ( - os.path.join(package_folder_path, "version.py") - if os.path.exists(os.path.join(package_folder_path, "version.py")) - else os.path.join(package_folder_path, "_version.py") - ), - "r", -) as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError("Cannot find version information") - -with open("README.md", encoding="utf-8") as f: - readme = f.read() -with open("CHANGELOG.md", encoding="utf-8") as f: - changelog = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - description="Microsoft Azure {} Client 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="azpysdkhelp@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python", - keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "License :: OSI Approved :: MIT License", - ], - zip_safe=False, - packages=find_packages( - exclude=[ - "tests", - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - "azure.mgmt", - ] - ), - include_package_data=True, - package_data={ - "pytyped": ["py.typed"], - }, - install_requires=[ - "isodate>=0.6.1", - "typing-extensions>=4.6.0", - "azure-common>=1.1", - "azure-mgmt-core>=1.3.2", - ], - python_requires=">=3.8", -) From ebf32b0e57997d6cadc5953ce26262cd58b7c43f Mon Sep 17 00:00:00 2001 From: Mikhail Simin Date: Fri, 6 Feb 2026 08:03:46 -0800 Subject: [PATCH 77/84] Update httpx dependency version constraint (#45047) Restrict httpx version to less than 1.0 --- sdk/evaluation/azure-ai-evaluation/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/evaluation/azure-ai-evaluation/setup.py b/sdk/evaluation/azure-ai-evaluation/setup.py index 5253c94fa865..5b6d80bccf9a 100644 --- a/sdk/evaluation/azure-ai-evaluation/setup.py +++ b/sdk/evaluation/azure-ai-evaluation/setup.py @@ -72,7 +72,7 @@ "azure-core>=1.31.0", "nltk>=3.9.1", "azure-storage-blob>=12.19.0", - "httpx>=0.27.2", + "httpx>=0.27.2,<1", # Dependencies added since Promptflow will soon be made optional 'pandas>=2.1.2,<3.0.0;python_version<"3.13"', 'pandas>=2.2.3,<3.0.0;python_version=="3.13"', From 6f886dc38fbdaaf37e571090378ae92e633d35e3 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Fri, 6 Feb 2026 09:36:10 -0800 Subject: [PATCH 78/84] Fix base64 encoding for JWT token (#45038) The eng/common/scripts/login-to-github.ps1 script was failing because it was using the standard Base64 encoded signature returned by Azure Key Vault directly in the JWT, instead of converting it to Base64URL format (which replaces + with -, / with _, and removes trailing =). I have fixed the script by adding the necessary character replacements and also added a 10-second clock skew buffer to the iat (issued at) claim to ensure validity. The script now runs successfully and logs in as azure-sdk-automation[bot]. Changes made: - Modified eng/common/scripts/login-to-github.ps1: - Converted the signature from Azure Key Vault to Base64URL format. - Subtracted 10 seconds from the iat claim to account for potential clock skew. Verification: - Ran the script and confirmed it successfully resolved the installation ID for "Azure" and obtained an access token. - gh auth status output confirms successful login. Co-authored-by: Wes Haggard --- eng/common/scripts/login-to-github.ps1 | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/eng/common/scripts/login-to-github.ps1 b/eng/common/scripts/login-to-github.ps1 index 96023d290c4b..e911f31eb12b 100644 --- a/eng/common/scripts/login-to-github.ps1 +++ b/eng/common/scripts/login-to-github.ps1 @@ -57,9 +57,17 @@ function New-GitHubAppJwt { [Parameter(Mandatory)] [string] $AppId ) - function Base64UrlEncode($json) { - $bytes = [System.Text.Encoding]::UTF8.GetBytes($json) - $base64 = [Convert]::ToBase64String($bytes) + function Base64UrlEncode { + param( + [string]$Data, + [switch]$IsBase64String + ) + if ($IsBase64String) { + $base64 = $Data + } else { + $bytes = [System.Text.Encoding]::UTF8.GetBytes($Data) + $base64 = [Convert]::ToBase64String($bytes) + } return $base64.TrimEnd('=') -replace '\+', '-' -replace '/', '_' } @@ -70,7 +78,7 @@ function New-GitHubAppJwt { } $Now = [int][double]::Parse((Get-Date -UFormat %s)) $Payload = @{ - iat = $Now + iat = $Now - 10 # 10 seconds clock skew exp = $Now + 600 # 10 minutes iss = $AppId } @@ -97,7 +105,7 @@ function New-GitHubAppJwt { throw "Azure Key Vault response does not contain a signature. Response: $($SignResultJson | ConvertTo-Json -Compress)" } - $Signature = $SignResultJson.signature + $Signature = Base64UrlEncode -Data $SignResultJson.signature -IsBase64String return "$UnsignedToken.$Signature" } From e20b94144f5a5da807344f117fc1fce8eb90ed05 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 6 Feb 2026 10:47:59 -0800 Subject: [PATCH 79/84] Search tsp migration 2025-11-01-preview (#43629) * Pure auto-gen code * updates * update * update * add tests * updates * update * update * update * update * update * update * update * update * update * update * update * updates * update * update * update * update * update * update * update * update * updates * update * update * update * update * update * updates * update * update * update * update * update * updates * updates * updates * get main * updates * update * update * add tsp-location file * update * updates * update * updates * updates * updates * updates * update * update * updates * updates * fix query_source_authorization * update * updates * update * updates * updates * update * updates * udpate * updates * updates * update * updates * update * updates * updates * remove test_queries * remove test_models * remove test_search_index_client * update * updates * updates * update * updates * update * update * update * update * update tests * updates * udpate * get main * update * updates * update * update * update * updates * updates * update * update * updates * update * updates * updates * udpates * update * updates * updates * update tests * adding the missing V2025_09_01 version * update * update * update * update * update * update * update * run black * fix pylint --------- Co-authored-by: Zixin Yao --- sdk/search/azure-search-documents/MANIFEST.in | 6 +- sdk/search/azure-search-documents/README.md | 14 +- .../azure-search-documents/_metadata.json | 3 + .../apiview-properties.json | 448 + sdk/search/azure-search-documents/assets.json | 2 +- .../azure-search-documents/azure/__init__.py | 7 +- .../azure/search/__init__.py | 7 +- .../azure/search/documents/__init__.py | 56 +- .../azure/search/documents/_api_versions.py | 17 - .../_search_index_client.py => _client.py} | 53 +- .../azure/search/documents/_configuration.py | 79 + .../search/documents/_generated/__init__.py | 27 - .../documents/_generated/_configuration.py | 53 - .../documents/_generated/aio/__init__.py | 27 - .../_generated/aio/_configuration.py | 53 - .../aio/operations/_documents_operations.py | 1180 -- .../documents/_generated/models/__init__.py | 154 - .../_generated/models/_models_py3.py | 3119 ---- .../operations/_documents_operations.py | 1585 -- .../search/documents/_generated/py.typed | 1 - .../azure/search/documents/_headers_mixin.py | 21 - .../operations => _operations}/__init__.py | 10 +- .../documents/_operations/_operations.py | 1973 +++ .../search/documents/_operations/_patch.py | 959 + .../azure/search/documents/_paging.py | 182 - ..._indexing_buffered_sender.py => _patch.py} | 209 +- .../azure/search/documents/_queries.py | 135 - .../azure/search/documents/_search_client.py | 751 - .../documents/_search_documents_error.py | 10 - .../_search_indexing_buffered_sender_base.py | 51 - .../azure/search/documents/_utils.py | 81 - .../{_generated => }/_utils/__init__.py | 4 +- .../search/documents/_utils/model_base.py | 1337 ++ .../{_generated => }/_utils/serialization.py | 21 +- .../azure/search/documents/_utils/utils.py | 57 + .../azure/search/documents/aio/__init__.py | 51 +- .../_client.py} | 57 +- .../search/documents/aio/_configuration.py | 83 + .../aio/_index_documents_batch_async.py | 139 - .../_operations}/__init__.py | 10 +- .../documents/aio/_operations/_operations.py | 1550 ++ .../_patch.py} | 905 +- .../azure/search/documents/aio/_paging.py | 164 - ...ing_buffered_sender_async.py => _patch.py} | 328 +- .../azure/search/documents/aio/_timer.py | 20 - .../search/documents/indexes/__init__.py | 55 +- .../azure/search/documents/indexes/_client.py | 181 + .../documents/indexes/_configuration.py | 127 + .../documents/indexes/_generated/__init__.py | 27 - .../indexes/_generated/_configuration.py | 48 - .../_generated/_search_service_client.py | 133 - .../indexes/_generated/_utils/utils.py | 23 - .../indexes/_generated/aio/__init__.py | 27 - .../indexes/_generated/aio/_configuration.py | 48 - .../_generated/aio/_search_service_client.py | 136 - .../_generated/aio/operations/__init__.py | 39 - .../aio/operations/_aliases_operations.py | 626 - .../operations/_data_sources_operations.py | 607 - .../aio/operations/_indexers_operations.py | 1123 -- .../aio/operations/_indexes_operations.py | 870 - .../operations/_knowledge_bases_operations.py | 598 - .../_knowledge_sources_operations.py | 665 - .../_generated/aio/operations/_patch.py | 21 - .../_search_service_client_operations.py | 202 - .../aio/operations/_skillsets_operations.py | 766 - .../operations/_synonym_maps_operations.py | 594 - .../indexes/_generated/models/__init__.py | 650 - .../indexes/_generated/models/_models_py3.py | 14467 ---------------- .../indexes/_generated/models/_patch.py | 21 - .../indexes/_generated/operations/__init__.py | 39 - .../operations/_aliases_operations.py | 770 - .../operations/_data_sources_operations.py | 764 - .../operations/_indexers_operations.py | 1424 -- .../operations/_indexes_operations.py | 1079 -- .../operations/_knowledge_bases_operations.py | 744 - .../_knowledge_sources_operations.py | 836 - .../indexes/_generated/operations/_patch.py | 21 - .../_search_service_client_operations.py | 244 - .../operations/_skillsets_operations.py | 958 - .../operations/_synonym_maps_operations.py | 746 - .../documents/indexes/_generated/py.typed | 1 - .../documents/indexes/_operations/__init__.py | 24 + .../indexes/_operations/_operations.py | 6106 +++++++ .../documents/indexes/_operations/_patch.py | 850 + .../{_generated => indexes}/_patch.py | 0 .../documents/indexes/_search_index_client.py | 868 - .../indexes/_search_indexer_client.py | 741 - .../azure/search/documents/indexes/_utils.py | 80 - .../{_generated => }/_utils/__init__.py | 4 +- .../documents/indexes/_utils/model_base.py | 1337 ++ .../_utils/serialization.py | 21 +- .../search/documents/indexes/_utils/utils.py | 57 + .../search/documents/indexes/aio/__init__.py | 50 +- .../search/documents/indexes/aio/_client.py | 189 + .../documents/indexes/aio/_configuration.py | 131 + .../indexes/aio/_operations/__init__.py | 24 + .../indexes/aio/_operations/_operations.py | 4746 +++++ .../indexes/aio/_operations/_patch.py | 851 + .../{_generated => indexes}/aio/_patch.py | 0 .../indexes/aio/_search_index_client.py | 862 - .../indexes/aio/_search_indexer_client.py | 691 - .../documents/indexes/models/__init__.py | 518 +- .../search/documents/indexes/models/_edm.py | 19 - .../_enums.py} | 1131 +- .../search/documents/indexes/models/_index.py | 930 - .../documents/indexes/models/_models.py | 13332 ++++++++++++-- .../search/documents/indexes/models/_patch.py | 444 + .../documents/knowledgebases/__init__.py | 51 +- ...ge_base_retrieval_client.py => _client.py} | 60 +- .../knowledgebases/_configuration.py | 72 + .../knowledgebases/_generated/__init__.py | 27 - .../_generated/_configuration.py | 53 - .../knowledgebases/_generated/_patch.py | 21 - .../knowledgebases/_generated/aio/__init__.py | 27 - .../_generated/aio/_configuration.py | 53 - .../knowledgebases/_generated/aio/_patch.py | 21 - .../_knowledge_retrieval_operations.py | 199 - .../_generated/aio/operations/_patch.py | 21 - .../_generated/models/__init__.py | 140 - .../_generated/models/_models_py3.py | 2875 --- .../_generated/models/_patch.py | 21 - .../_generated/operations/_patch.py | 21 - .../knowledgebases/_generated/py.typed | 1 - .../knowledgebases/_knowledgebase_client.py | 101 - .../operations => _operations}/__init__.py | 10 +- .../_operations.py} | 197 +- .../_operations}/_patch.py | 0 .../models => knowledgebases}/_patch.py | 0 .../{_generated => }/_utils/__init__.py | 4 +- .../knowledgebases/_utils/model_base.py | 1337 ++ .../_utils/serialization.py | 21 +- .../documents/knowledgebases/_utils/utils.py | 57 + .../documents/knowledgebases/aio/__init__.py | 48 +- .../_client.py} | 60 +- .../knowledgebases/aio/_configuration.py | 74 + .../aio/_knowledgebase_client_async.py | 102 - .../aio/_operations}/__init__.py | 10 +- .../aio/_operations/_operations.py | 224 + .../aio/_operations}/_patch.py | 0 .../aio}/_patch.py | 0 .../knowledgebases/models/__init__.py | 124 +- .../_enums.py} | 61 +- .../knowledgebases/models/_models.py | 1995 +++ .../aio => knowledgebases/models}/_patch.py | 0 .../azure/search/documents/models/__init__.py | 142 +- .../_enums.py} | 25 +- .../azure/search/documents/models/_models.py | 1680 ++ .../_patch.py} | 143 +- .../azure/search/documents/py.typed | 1 + .../azure-search-documents/pyproject.toml | 62 + .../sample_agentic_retrieval_async.py | 25 +- .../sample_documents_buffered_sender_async.py | 8 +- .../sample_documents_crud_async.py | 16 + .../sample_index_alias_crud_async.py | 16 +- .../sample_index_analyze_text_async.py | 8 +- .../async_samples/sample_index_crud_async.py | 30 +- .../sample_indexer_crud_async.py | 4 +- .../sample_indexer_datasource_crud_async.py | 8 +- .../sample_query_autocomplete_async.py | 4 +- .../sample_query_facets_async.py | 4 +- .../sample_query_semantic_async.py | 16 +- .../sample_query_vector_async.py | 33 +- ...mple_search_client_custom_request_async.py | 4 +- .../samples/sample_agentic_retrieval.py | 13 +- .../sample_documents_buffered_sender.py | 4 +- .../samples/sample_documents_crud.py | 19 +- .../samples/sample_index_alias_crud.py | 16 +- .../samples/sample_index_analyze_text.py | 8 +- .../samples/sample_index_crud.py | 44 +- .../samples/sample_indexer_crud.py | 4 +- .../samples/sample_indexer_workflow.py | 32 +- .../samples/sample_query_facets.py | 4 +- .../samples/sample_query_semantic.py | 18 +- .../samples/sample_query_vector.py | 36 +- .../sample_search_client_custom_request.py | 4 +- sdk/search/azure-search-documents/setup.py | 72 - .../async_tests/test_buffered_sender_async.py | 65 +- ...knowledge_base_configuration_live_async.py | 79 +- .../test_knowledge_base_live_async.py | 71 +- ...dge_source_remote_sharepoint_live_async.py | 16 +- .../test_knowledge_source_web_live_async.py | 4 +- .../async_tests/test_search_client_async.py | 27 +- ...earch_client_buffered_sender_live_async.py | 32 +- ...search_client_index_document_live_async.py | 4 +- .../test_search_client_search_live_async.py | 29 +- ...st_search_index_client_alias_live_async.py | 16 +- .../test_search_index_client_async.py | 87 - ...rch_index_client_data_source_live_async.py | 52 +- .../test_search_index_client_live_async.py | 93 +- ...search_index_client_skillset_live_async.py | 144 +- ...rch_index_client_synonym_map_live_async.py | 8 +- .../test_search_indexer_client_live_async.py | 150 +- .../azure-search-documents/tests/conftest.py | 4 +- .../tests/perfstress_tests/autocomplete.py | 22 +- .../perfstress_tests/search_documents.py | 18 +- .../tests/perfstress_tests/suggest.py | 22 +- .../tests/search_service_preparer.py | 58 +- .../tests/test_buffered_sender.py | 60 +- .../tests/test_index_documents_batch.py | 40 +- .../tests/test_index_field_helpers.py | 35 +- .../test_knowledge_base_configuration_live.py | 82 +- .../tests/test_knowledge_base_live.py | 71 +- .../tests/test_models.py | 194 - .../tests/test_queries.py | 167 - .../tests/test_regex_flags.py | 122 - .../tests/test_search_client.py | 281 +- .../tests/test_search_client_basic_live.py | 12 +- ...test_search_client_buffered_sender_live.py | 32 +- .../test_search_client_index_document_live.py | 6 +- .../tests/test_search_client_search_live.py | 33 +- .../tests/test_search_index_client.py | 136 - .../test_search_index_client_alias_live.py | 8 +- ...st_search_index_client_data_source_live.py | 75 +- .../tests/test_search_index_client_live.py | 65 +- .../test_search_index_client_skillset_live.py | 179 +- ...st_search_index_client_synonym_map_live.py | 4 +- .../tests/test_search_indexer_client_live.py | 100 +- .../tests/test_serialization.py | 46 +- .../azure-search-documents/tsp-location.yaml | 4 + 219 files changed, 42254 insertions(+), 50775 deletions(-) create mode 100644 sdk/search/azure-search-documents/_metadata.json create mode 100644 sdk/search/azure-search-documents/apiview-properties.json delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_api_versions.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/_search_index_client.py => _client.py} (65%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/operations => _operations}/__init__.py (65%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_paging.py rename sdk/search/azure-search-documents/azure/search/documents/{_search_indexing_buffered_sender.py => _patch.py} (66%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_queries.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_utils.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/_utils/__init__.py (52%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/_utils/serialization.py (98%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/aio/_search_index_client.py => aio/_client.py} (66%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py rename sdk/search/azure-search-documents/azure/search/documents/{knowledgebases/_generated/aio/operations => aio/_operations}/__init__.py (65%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/aio/{_search_client_async.py => _operations/_patch.py} (54%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py rename sdk/search/azure-search-documents/azure/search/documents/aio/{_search_indexing_buffered_sender_async.py => _patch.py} (50%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_bases_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_bases_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => indexes}/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated => }/_utils/__init__.py (52%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py rename sdk/search/azure-search-documents/azure/search/documents/{knowledgebases/_generated => indexes}/_utils/serialization.py (98%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => indexes}/aio/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated/models/_search_service_client_enums.py => models/_enums.py} (73%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py rename sdk/search/azure-search-documents/azure/search/documents/knowledgebases/{_generated/_knowledge_base_retrieval_client.py => _client.py} (61%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_knowledge_retrieval_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_models_py3.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_patch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/py.typed delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_knowledgebase_client.py rename sdk/search/azure-search-documents/azure/search/documents/knowledgebases/{_generated/operations => _operations}/__init__.py (64%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebases/{_generated/operations/_knowledge_retrieval_operations.py => _operations/_operations.py} (50%) rename sdk/search/azure-search-documents/azure/search/documents/{_generated/aio/operations => knowledgebases/_operations}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{_generated/models => knowledgebases}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebases/{_generated => }/_utils/__init__.py (52%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/model_base.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated => knowledgebases}/_utils/serialization.py (98%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/utils.py rename sdk/search/azure-search-documents/azure/search/documents/knowledgebases/{_generated/aio/_knowledge_base_retrieval_client.py => aio/_client.py} (63%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_knowledgebase_client_async.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/aio/operations => knowledgebases/aio/_operations}/__init__.py (64%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/operations => knowledgebases/aio/_operations}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated => knowledgebases/aio}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebases/{_generated/models/_knowledge_base_retrieval_client_enums.py => models/_enums.py} (55%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_models.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated/aio => knowledgebases/models}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{_generated/models/_search_index_client_enums.py => models/_enums.py} (95%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/models/_models.py rename sdk/search/azure-search-documents/azure/search/documents/{_index_documents_batch.py => models/_patch.py} (51%) delete mode 100644 sdk/search/azure-search-documents/setup.py delete mode 100644 sdk/search/azure-search-documents/tests/test_models.py delete mode 100644 sdk/search/azure-search-documents/tests/test_queries.py delete mode 100644 sdk/search/azure-search-documents/tests/test_regex_flags.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client.py create mode 100644 sdk/search/azure-search-documents/tsp-location.yaml diff --git a/sdk/search/azure-search-documents/MANIFEST.in b/sdk/search/azure-search-documents/MANIFEST.in index c65fe9f8b1a3..9ae9a22b29e4 100644 --- a/sdk/search/azure-search-documents/MANIFEST.in +++ b/sdk/search/azure-search-documents/MANIFEST.in @@ -1,7 +1,7 @@ include *.md -include azure/__init__.py -include azure/search/__init__.py include LICENSE +include azure/search/documents/py.typed recursive-include tests *.py recursive-include samples *.py *.md -include azure/search/documents/py.typed +include azure/__init__.py +include azure/search/__init__.py diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index 5750b4c0a2d5..b8419b4b4546 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -248,17 +248,15 @@ from azure.search.documents.indexes.models import ( index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="HotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="HotelName", type=SearchFieldDataType.STRING, searchable=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), ], collection=True, ), diff --git a/sdk/search/azure-search-documents/_metadata.json b/sdk/search/azure-search-documents/_metadata.json new file mode 100644 index 000000000000..66892d1cb69d --- /dev/null +++ b/sdk/search/azure-search-documents/_metadata.json @@ -0,0 +1,3 @@ +{ + "apiVersion": "2025-11-01-preview" +} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/apiview-properties.json b/sdk/search/azure-search-documents/apiview-properties.json new file mode 100644 index 000000000000..f26cb866984b --- /dev/null +++ b/sdk/search/azure-search-documents/apiview-properties.json @@ -0,0 +1,448 @@ +{ + "CrossLanguagePackageId": "Search", + "CrossLanguageDefinitionId": { + "azure.search.documents.knowledgebases.models.AIServices": "Search.AIServices", + "azure.search.documents.indexes.models.CognitiveServicesAccount": "Search.CognitiveServicesAccount", + "azure.search.documents.indexes.models.AIServicesAccountIdentity": "Search.AIServicesAccountIdentity", + "azure.search.documents.indexes.models.AIServicesAccountKey": "Search.AIServicesAccountKey", + "azure.search.documents.indexes.models.AIServicesVisionParameters": "Search.AIServicesVisionParameters", + "azure.search.documents.indexes.models.VectorSearchVectorizer": "Search.VectorSearchVectorizer", + "azure.search.documents.indexes.models.AIServicesVisionVectorizer": "Search.AIServicesVisionVectorizer", + "azure.search.documents.indexes.models.AnalyzedTokenInfo": "Search.AnalyzedTokenInfo", + "azure.search.documents.indexes.models.AnalyzeResult": "Search.AnalyzeResult", + "azure.search.documents.indexes.models.AnalyzeTextOptions": "Search.AnalyzeRequest", + "azure.search.documents.indexes.models.TokenFilter": "Search.TokenFilter", + "azure.search.documents.indexes.models.AsciiFoldingTokenFilter": "Search.AsciiFoldingTokenFilter", + "azure.search.documents.models.AutocompleteItem": "Search.AutocompleteItem", + "azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials": "Search.AzureActiveDirectoryApplicationCredentials", + "azure.search.documents.indexes.models.KnowledgeSource": "Search.KnowledgeSource", + "azure.search.documents.indexes.models.AzureBlobKnowledgeSource": "Search.AzureBlobKnowledgeSource", + "azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters": "Search.AzureBlobKnowledgeSourceParameters", + "azure.search.documents.knowledgebases.models.KnowledgeSourceParams": "Search.KnowledgeSourceParams", + "azure.search.documents.knowledgebases.models.AzureBlobKnowledgeSourceParams": "Search.AzureBlobKnowledgeSourceParams", + "azure.search.documents.indexes.models.AzureMachineLearningParameters": "Search.AMLParameters", + "azure.search.documents.indexes.models.SearchIndexerSkill": "Search.SearchIndexerSkill", + "azure.search.documents.indexes.models.AzureMachineLearningSkill": "Search.AzureMachineLearningSkill", + "azure.search.documents.indexes.models.AzureMachineLearningVectorizer": "Search.AMLVectorizer", + "azure.search.documents.indexes.models.AzureOpenAIEmbeddingSkill": "Search.AzureOpenAIEmbeddingSkill", + "azure.search.documents.indexes.models.AzureOpenAITokenizerParameters": "Search.AzureOpenAITokenizerParameters", + "azure.search.documents.indexes.models.AzureOpenAIVectorizer": "Search.AzureOpenAIVectorizer", + "azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters": "Search.AzureOpenAIVectorizerParameters", + "azure.search.documents.indexes.models.VectorSearchCompression": "Search.VectorSearchCompression", + "azure.search.documents.indexes.models.BinaryQuantizationCompression": "Search.BinaryQuantizationCompression", + "azure.search.documents.indexes.models.SimilarityAlgorithm": "Search.SimilarityAlgorithm", + "azure.search.documents.indexes.models.BM25SimilarityAlgorithm": "Search.BM25SimilarityAlgorithm", + "azure.search.documents.indexes.models.CharFilter": "Search.CharFilter", + "azure.search.documents.indexes.models.ChatCompletionCommonModelParameters": "Search.ChatCompletionCommonModelParameters", + "azure.search.documents.indexes.models.ChatCompletionResponseFormat": "Search.ChatCompletionResponseFormat", + "azure.search.documents.indexes.models.ChatCompletionSchema": "Search.ChatCompletionSchema", + "azure.search.documents.indexes.models.ChatCompletionSchemaProperties": "Search.ChatCompletionSchemaProperties", + "azure.search.documents.indexes.models.ChatCompletionSkill": "Search.ChatCompletionSkill", + "azure.search.documents.indexes.models.CjkBigramTokenFilter": "Search.CjkBigramTokenFilter", + "azure.search.documents.indexes.models.ClassicSimilarityAlgorithm": "Search.ClassicSimilarityAlgorithm", + "azure.search.documents.indexes.models.LexicalTokenizer": "Search.LexicalTokenizer", + "azure.search.documents.indexes.models.ClassicTokenizer": "Search.ClassicTokenizer", + "azure.search.documents.indexes.models.CognitiveServicesAccountKey": "Search.CognitiveServicesAccountKey", + "azure.search.documents.indexes.models.CommonGramTokenFilter": "Search.CommonGramTokenFilter", + "azure.search.documents.knowledgebases.models.CompletedSynchronizationState": "Search.CompletedSynchronizationState", + "azure.search.documents.indexes.models.ConditionalSkill": "Search.ConditionalSkill", + "azure.search.documents.indexes.models.ContentUnderstandingSkill": "Search.ContentUnderstandingSkill", + "azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties": "Search.ContentUnderstandingSkillChunkingProperties", + "azure.search.documents.indexes.models.CorsOptions": "Search.CorsOptions", + "azure.search.documents.indexes.models.CreatedResources": "Search.CreatedResources", + "azure.search.documents.indexes.models.LexicalAnalyzer": "Search.LexicalAnalyzer", + "azure.search.documents.indexes.models.CustomAnalyzer": "Search.CustomAnalyzer", + "azure.search.documents.indexes.models.CustomEntity": "Search.CustomEntity", + "azure.search.documents.indexes.models.CustomEntityAlias": "Search.CustomEntityAlias", + "azure.search.documents.indexes.models.CustomEntityLookupSkill": "Search.CustomEntityLookupSkill", + "azure.search.documents.indexes.models.LexicalNormalizer": "Search.LexicalNormalizer", + "azure.search.documents.indexes.models.CustomNormalizer": "Search.CustomNormalizer", + "azure.search.documents.indexes.models.DataChangeDetectionPolicy": "Search.DataChangeDetectionPolicy", + "azure.search.documents.indexes.models.DataDeletionDetectionPolicy": "Search.DataDeletionDetectionPolicy", + "azure.search.documents.indexes.models.DataSourceCredentials": "Search.DataSourceCredentials", + "azure.search.documents.models.DebugInfo": "Search.DebugInfo", + "azure.search.documents.indexes.models.DefaultCognitiveServicesAccount": "Search.DefaultCognitiveServicesAccount", + "azure.search.documents.indexes.models.DictionaryDecompounderTokenFilter": "Search.DictionaryDecompounderTokenFilter", + "azure.search.documents.indexes.models.ScoringFunction": "Search.ScoringFunction", + "azure.search.documents.indexes.models.DistanceScoringFunction": "Search.DistanceScoringFunction", + "azure.search.documents.indexes.models.DistanceScoringParameters": "Search.DistanceScoringParameters", + "azure.search.documents.models.DocumentDebugInfo": "Search.DocumentDebugInfo", + "azure.search.documents.indexes.models.DocumentExtractionSkill": "Search.DocumentExtractionSkill", + "azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkill": "Search.DocumentIntelligenceLayoutSkill", + "azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties": "Search.DocumentIntelligenceLayoutSkillChunkingProperties", + "azure.search.documents.indexes.models.DocumentKeysOrIds": "Search.DocumentKeysOrIds", + "azure.search.documents.indexes.models.EdgeNGramTokenFilter": "Search.EdgeNGramTokenFilter", + "azure.search.documents.indexes.models.EdgeNGramTokenFilterV2": "Search.EdgeNGramTokenFilterV2", + "azure.search.documents.indexes.models.EdgeNGramTokenizer": "Search.EdgeNGramTokenizer", + "azure.search.documents.indexes.models.ElisionTokenFilter": "Search.ElisionTokenFilter", + "azure.search.documents.indexes.models.EntityLinkingSkill": "Search.EntityLinkingSkill", + "azure.search.documents.indexes.models.EntityRecognitionSkillV3": "Search.EntityRecognitionSkillV3", + "azure.search.documents.models.ErrorAdditionalInfo": "Search.ErrorAdditionalInfo", + "azure.search.documents.models.ErrorDetail": "Search.ErrorDetail", + "azure.search.documents.models.ErrorResponse": "Search.ErrorResponse", + "azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration": "Search.VectorSearchAlgorithmConfiguration", + "azure.search.documents.indexes.models.ExhaustiveKnnAlgorithmConfiguration": "Search.ExhaustiveKnnAlgorithmConfiguration", + "azure.search.documents.indexes.models.ExhaustiveKnnParameters": "Search.ExhaustiveKnnParameters", + "azure.search.documents.models.FacetResult": "Search.FacetResult", + "azure.search.documents.indexes.models.FieldMapping": "Search.FieldMapping", + "azure.search.documents.indexes.models.FieldMappingFunction": "Search.FieldMappingFunction", + "azure.search.documents.indexes.models.FreshnessScoringFunction": "Search.FreshnessScoringFunction", + "azure.search.documents.indexes.models.FreshnessScoringParameters": "Search.FreshnessScoringParameters", + "azure.search.documents.indexes.models.GetIndexStatisticsResult": "Search.GetIndexStatisticsResult", + "azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy": "Search.HighWaterMarkChangeDetectionPolicy", + "azure.search.documents.indexes.models.HnswAlgorithmConfiguration": "Search.HnswAlgorithmConfiguration", + "azure.search.documents.indexes.models.HnswParameters": "Search.HnswParameters", + "azure.search.documents.models.HybridSearch": "Search.HybridSearch", + "azure.search.documents.indexes.models.ImageAnalysisSkill": "Search.ImageAnalysisSkill", + "azure.search.documents.models.IndexAction": "Search.IndexAction", + "azure.search.documents.models.IndexDocumentsBatch": "Search.IndexBatch", + "azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSource": "Search.IndexedOneLakeKnowledgeSource", + "azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSourceParameters": "Search.IndexedOneLakeKnowledgeSourceParameters", + "azure.search.documents.knowledgebases.models.IndexedOneLakeKnowledgeSourceParams": "Search.IndexedOneLakeKnowledgeSourceParams", + "azure.search.documents.indexes.models.IndexedSharePointKnowledgeSource": "Search.IndexedSharePointKnowledgeSource", + "azure.search.documents.indexes.models.IndexedSharePointKnowledgeSourceParameters": "Search.IndexedSharePointKnowledgeSourceParameters", + "azure.search.documents.knowledgebases.models.IndexedSharePointKnowledgeSourceParams": "Search.IndexedSharePointKnowledgeSourceParams", + "azure.search.documents.indexes.models.IndexerCurrentState": "Search.IndexerCurrentState", + "azure.search.documents.indexes.models.IndexerExecutionResult": "Search.IndexerExecutionResult", + "azure.search.documents.indexes.models.IndexerResyncBody": "Search.IndexerResyncBody", + "azure.search.documents.indexes.models.IndexerRuntime": "Search.IndexerRuntime", + "azure.search.documents.indexes.models.IndexingParameters": "Search.IndexingParameters", + "azure.search.documents.indexes.models.IndexingParametersConfiguration": "Search.IndexingParametersConfiguration", + "azure.search.documents.models.IndexingResult": "Search.IndexingResult", + "azure.search.documents.indexes.models.IndexingSchedule": "Search.IndexingSchedule", + "azure.search.documents.indexes.models.IndexStatisticsSummary": "Search.IndexStatisticsSummary", + "azure.search.documents.indexes.models.InputFieldMappingEntry": "Search.InputFieldMappingEntry", + "azure.search.documents.indexes.models.KeepTokenFilter": "Search.KeepTokenFilter", + "azure.search.documents.indexes.models.KeyPhraseExtractionSkill": "Search.KeyPhraseExtractionSkill", + "azure.search.documents.indexes.models.KeywordMarkerTokenFilter": "Search.KeywordMarkerTokenFilter", + "azure.search.documents.indexes.models.KeywordTokenizer": "Search.KeywordTokenizer", + "azure.search.documents.indexes.models.KeywordTokenizerV2": "Search.KeywordTokenizerV2", + "azure.search.documents.indexes.models.KnowledgeBase": "Search.KnowledgeBase", + "azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecord": "Search.KnowledgeBaseActivityRecord", + "azure.search.documents.knowledgebases.models.KnowledgeBaseAgenticReasoningActivityRecord": "Search.KnowledgeBaseAgenticReasoningActivityRecord", + "azure.search.documents.knowledgebases.models.KnowledgeBaseReference": "Search.KnowledgeBaseReference", + "azure.search.documents.knowledgebases.models.KnowledgeBaseAzureBlobReference": "Search.KnowledgeBaseAzureBlobReference", + "azure.search.documents.indexes.models.KnowledgeBaseModel": "Search.KnowledgeBaseModel", + "azure.search.documents.indexes.models.KnowledgeBaseAzureOpenAIModel": "Search.KnowledgeBaseAzureOpenAIModel", + "azure.search.documents.knowledgebases.models.KnowledgeBaseErrorAdditionalInfo": "Search.KnowledgeBaseErrorAdditionalInfo", + "azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail": "Search.KnowledgeBaseErrorDetail", + "azure.search.documents.knowledgebases.models.KnowledgeBaseImageContent": "Search.KnowledgeBaseImageContent", + "azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedOneLakeReference": "Search.KnowledgeBaseIndexedOneLakeReference", + "azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedSharePointReference": "Search.KnowledgeBaseIndexedSharePointReference", + "azure.search.documents.knowledgebases.models.KnowledgeBaseMessage": "Search.KnowledgeBaseMessage", + "azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContent": "Search.KnowledgeBaseMessageContent", + "azure.search.documents.knowledgebases.models.KnowledgeBaseMessageImageContent": "Search.KnowledgeBaseMessageImageContent", + "azure.search.documents.knowledgebases.models.KnowledgeBaseMessageTextContent": "Search.KnowledgeBaseMessageTextContent", + "azure.search.documents.knowledgebases.models.KnowledgeBaseModelAnswerSynthesisActivityRecord": "Search.KnowledgeBaseModelAnswerSynthesisActivityRecord", + "azure.search.documents.knowledgebases.models.KnowledgeBaseModelQueryPlanningActivityRecord": "Search.KnowledgeBaseModelQueryPlanningActivityRecord", + "azure.search.documents.knowledgebases.models.KnowledgeBaseRemoteSharePointReference": "Search.KnowledgeBaseRemoteSharePointReference", + "azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest": "Search.KnowledgeBaseRetrievalRequest", + "azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse": "Search.KnowledgeBaseRetrievalResponse", + "azure.search.documents.knowledgebases.models.KnowledgeBaseSearchIndexReference": "Search.KnowledgeBaseSearchIndexReference", + "azure.search.documents.knowledgebases.models.KnowledgeBaseWebReference": "Search.KnowledgeBaseWebReference", + "azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntent": "Search.KnowledgeRetrievalIntent", + "azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort": "Search.KnowledgeRetrievalReasoningEffort", + "azure.search.documents.knowledgebases.models.KnowledgeRetrievalLowReasoningEffort": "Search.KnowledgeRetrievalLowReasoningEffort", + "azure.search.documents.knowledgebases.models.KnowledgeRetrievalMediumReasoningEffort": "Search.KnowledgeRetrievalMediumReasoningEffort", + "azure.search.documents.knowledgebases.models.KnowledgeRetrievalMinimalReasoningEffort": "Search.KnowledgeRetrievalMinimalReasoningEffort", + "azure.search.documents.knowledgebases.models.KnowledgeRetrievalSemanticIntent": "Search.KnowledgeRetrievalSemanticIntent", + "azure.search.documents.knowledgebases.models.KnowledgeSourceVectorizer": "Search.KnowledgeSourceVectorizer", + "azure.search.documents.knowledgebases.models.KnowledgeSourceAzureOpenAIVectorizer": "Search.KnowledgeSourceAzureOpenAIVectorizer", + "azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters": "Search.KnowledgeSourceIngestionParameters", + "azure.search.documents.indexes.models.KnowledgeSourceReference": "Search.KnowledgeSourceReference", + "azure.search.documents.knowledgebases.models.KnowledgeSourceStatistics": "Search.KnowledgeSourceStatistics", + "azure.search.documents.knowledgebases.models.KnowledgeSourceStatus": "Search.KnowledgeSourceStatus", + "azure.search.documents.indexes.models.LanguageDetectionSkill": "Search.LanguageDetectionSkill", + "azure.search.documents.indexes.models.LengthTokenFilter": "Search.LengthTokenFilter", + "azure.search.documents.indexes.models.LimitTokenFilter": "Search.LimitTokenFilter", + "azure.search.documents.models.LookupDocument": "Search.LookupDocument", + "azure.search.documents.indexes.models.LuceneStandardAnalyzer": "Search.LuceneStandardAnalyzer", + "azure.search.documents.indexes.models.LuceneStandardTokenizer": "Search.LuceneStandardTokenizer", + "azure.search.documents.indexes.models.LuceneStandardTokenizerV2": "Search.LuceneStandardTokenizerV2", + "azure.search.documents.indexes.models.MagnitudeScoringFunction": "Search.MagnitudeScoringFunction", + "azure.search.documents.indexes.models.MagnitudeScoringParameters": "Search.MagnitudeScoringParameters", + "azure.search.documents.indexes.models.MappingCharFilter": "Search.MappingCharFilter", + "azure.search.documents.indexes.models.MergeSkill": "Search.MergeSkill", + "azure.search.documents.indexes.models.MicrosoftLanguageStemmingTokenizer": "Search.MicrosoftLanguageStemmingTokenizer", + "azure.search.documents.indexes.models.MicrosoftLanguageTokenizer": "Search.MicrosoftLanguageTokenizer", + "azure.search.documents.indexes.models.NativeBlobSoftDeleteDeletionDetectionPolicy": "Search.NativeBlobSoftDeleteDeletionDetectionPolicy", + "azure.search.documents.indexes.models.NGramTokenFilter": "Search.NGramTokenFilter", + "azure.search.documents.indexes.models.NGramTokenFilterV2": "Search.NGramTokenFilterV2", + "azure.search.documents.indexes.models.NGramTokenizer": "Search.NGramTokenizer", + "azure.search.documents.indexes.models.OcrSkill": "Search.OcrSkill", + "azure.search.documents.indexes.models.OutputFieldMappingEntry": "Search.OutputFieldMappingEntry", + "azure.search.documents.indexes.models.PathHierarchyTokenizerV2": "Search.PathHierarchyTokenizerV2", + "azure.search.documents.indexes.models.PatternAnalyzer": "Search.PatternAnalyzer", + "azure.search.documents.indexes.models.PatternCaptureTokenFilter": "Search.PatternCaptureTokenFilter", + "azure.search.documents.indexes.models.PatternReplaceCharFilter": "Search.PatternReplaceCharFilter", + "azure.search.documents.indexes.models.PatternReplaceTokenFilter": "Search.PatternReplaceTokenFilter", + "azure.search.documents.indexes.models.PatternTokenizer": "Search.PatternTokenizer", + "azure.search.documents.indexes.models.PhoneticTokenFilter": "Search.PhoneticTokenFilter", + "azure.search.documents.indexes.models.PIIDetectionSkill": "Search.PIIDetectionSkill", + "azure.search.documents.models.QueryAnswerResult": "Search.QueryAnswerResult", + "azure.search.documents.models.QueryCaptionResult": "Search.QueryCaptionResult", + "azure.search.documents.models.QueryResultDocumentInnerHit": "Search.QueryResultDocumentInnerHit", + "azure.search.documents.models.QueryResultDocumentRerankerInput": "Search.QueryResultDocumentRerankerInput", + "azure.search.documents.models.QueryResultDocumentSemanticField": "Search.QueryResultDocumentSemanticField", + "azure.search.documents.models.QueryResultDocumentSubscores": "Search.QueryResultDocumentSubscores", + "azure.search.documents.models.QueryRewritesDebugInfo": "Search.QueryRewritesDebugInfo", + "azure.search.documents.models.QueryRewritesValuesDebugInfo": "Search.QueryRewritesValuesDebugInfo", + "azure.search.documents.indexes.models.RemoteSharePointKnowledgeSource": "Search.RemoteSharePointKnowledgeSource", + "azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters": "Search.RemoteSharePointKnowledgeSourceParameters", + "azure.search.documents.knowledgebases.models.RemoteSharePointKnowledgeSourceParams": "Search.RemoteSharePointKnowledgeSourceParams", + "azure.search.documents.indexes.models.RescoringOptions": "Search.RescoringOptions", + "azure.search.documents.indexes.models.ResourceCounter": "Search.ResourceCounter", + "azure.search.documents.indexes.models.ScalarQuantizationCompression": "Search.ScalarQuantizationCompression", + "azure.search.documents.indexes.models.ScalarQuantizationParameters": "Search.ScalarQuantizationParameters", + "azure.search.documents.indexes.models.ScoringProfile": "Search.ScoringProfile", + "azure.search.documents.indexes.models.SearchAlias": "Search.SearchAlias", + "azure.search.documents.models.SearchDocumentsResult": "Search.SearchDocumentsResult", + "azure.search.documents.indexes.models.SearchField": "Search.SearchField", + "azure.search.documents.indexes.models.SearchIndex": "Search.SearchIndex", + "azure.search.documents.indexes.models.SearchIndexer": "Search.SearchIndexer", + "azure.search.documents.indexes.models.SearchIndexerCache": "Search.SearchIndexerCache", + "azure.search.documents.indexes.models.SearchIndexerDataContainer": "Search.SearchIndexerDataContainer", + "azure.search.documents.indexes.models.SearchIndexerDataIdentity": "Search.SearchIndexerDataIdentity", + "azure.search.documents.indexes.models.SearchIndexerDataNoneIdentity": "Search.SearchIndexerDataNoneIdentity", + "azure.search.documents.indexes.models.SearchIndexerDataSourceConnection": "Search.SearchIndexerDataSource", + "azure.search.documents.indexes.models.SearchIndexerDataUserAssignedIdentity": "Search.SearchIndexerDataUserAssignedIdentity", + "azure.search.documents.indexes.models.SearchIndexerError": "Search.SearchIndexerError", + "azure.search.documents.indexes.models.SearchIndexerIndexProjection": "Search.SearchIndexerIndexProjection", + "azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector": "Search.SearchIndexerIndexProjectionSelector", + "azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters": "Search.SearchIndexerIndexProjectionsParameters", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStore": "Search.SearchIndexerKnowledgeStore", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjectionSelector": "Search.SearchIndexerKnowledgeStoreProjectionSelector", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreBlobProjectionSelector": "Search.SearchIndexerKnowledgeStoreBlobProjectionSelector", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector": "Search.SearchIndexerKnowledgeStoreFileProjectionSelector", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector": "Search.SearchIndexerKnowledgeStoreObjectProjectionSelector", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters": "Search.SearchIndexerKnowledgeStoreParameters", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection": "Search.SearchIndexerKnowledgeStoreProjection", + "azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector": "Search.SearchIndexerKnowledgeStoreTableProjectionSelector", + "azure.search.documents.indexes.models.SearchIndexerLimits": "Search.SearchIndexerLimits", + "azure.search.documents.indexes.models.SearchIndexerSkillset": "Search.SearchIndexerSkillset", + "azure.search.documents.indexes.models.SearchIndexerStatus": "Search.SearchIndexerStatus", + "azure.search.documents.indexes.models.SearchIndexerWarning": "Search.SearchIndexerWarning", + "azure.search.documents.indexes.models.SearchIndexFieldReference": "Search.SearchIndexFieldReference", + "azure.search.documents.indexes.models.SearchIndexKnowledgeSource": "Search.SearchIndexKnowledgeSource", + "azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters": "Search.SearchIndexKnowledgeSourceParameters", + "azure.search.documents.knowledgebases.models.SearchIndexKnowledgeSourceParams": "Search.SearchIndexKnowledgeSourceParams", + "azure.search.documents.models.SearchRequest": "Search.SearchRequest", + "azure.search.documents.indexes.models.SearchResourceEncryptionKey": "Search.SearchResourceEncryptionKey", + "azure.search.documents.models.SearchResult": "Search.SearchResult", + "azure.search.documents.models.VectorThreshold": "Search.VectorThreshold", + "azure.search.documents.models.SearchScoreThreshold": "Search.SearchScoreThreshold", + "azure.search.documents.indexes.models.SearchServiceCounters": "Search.SearchServiceCounters", + "azure.search.documents.indexes.models.SearchServiceLimits": "Search.SearchServiceLimits", + "azure.search.documents.indexes.models.SearchServiceStatistics": "Search.SearchServiceStatistics", + "azure.search.documents.indexes.models.SearchSuggester": "Search.SearchSuggester", + "azure.search.documents.indexes.models.SemanticConfiguration": "Search.SemanticConfiguration", + "azure.search.documents.models.SemanticDebugInfo": "Search.SemanticDebugInfo", + "azure.search.documents.indexes.models.SemanticField": "Search.SemanticField", + "azure.search.documents.indexes.models.SemanticPrioritizedFields": "Search.SemanticPrioritizedFields", + "azure.search.documents.indexes.models.SemanticSearch": "Search.SemanticSearch", + "azure.search.documents.indexes.models.SentimentSkillV3": "Search.SentimentSkillV3", + "azure.search.documents.indexes.models.ServiceIndexersRuntime": "Search.ServiceIndexersRuntime", + "azure.search.documents.indexes.models.ShaperSkill": "Search.ShaperSkill", + "azure.search.documents.knowledgebases.models.SharePointSensitivityLabelInfo": "Search.SharePointSensitivityLabelInfo", + "azure.search.documents.indexes.models.ShingleTokenFilter": "Search.ShingleTokenFilter", + "azure.search.documents.models.SingleVectorFieldResult": "Search.SingleVectorFieldResult", + "azure.search.documents.indexes.models.SkillNames": "Search.SkillNames", + "azure.search.documents.indexes.models.SnowballTokenFilter": "Search.SnowballTokenFilter", + "azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy": "Search.SoftDeleteColumnDeletionDetectionPolicy", + "azure.search.documents.indexes.models.SplitSkill": "Search.SplitSkill", + "azure.search.documents.indexes.models.SqlIntegratedChangeTrackingPolicy": "Search.SqlIntegratedChangeTrackingPolicy", + "azure.search.documents.indexes.models.StemmerOverrideTokenFilter": "Search.StemmerOverrideTokenFilter", + "azure.search.documents.indexes.models.StemmerTokenFilter": "Search.StemmerTokenFilter", + "azure.search.documents.indexes.models.StopAnalyzer": "Search.StopAnalyzer", + "azure.search.documents.indexes.models.StopwordsTokenFilter": "Search.StopwordsTokenFilter", + "azure.search.documents.models.SuggestResult": "Search.SuggestResult", + "azure.search.documents.knowledgebases.models.SynchronizationState": "Search.SynchronizationState", + "azure.search.documents.indexes.models.SynonymMap": "Search.SynonymMap", + "azure.search.documents.indexes.models.SynonymTokenFilter": "Search.SynonymTokenFilter", + "azure.search.documents.indexes.models.TagScoringFunction": "Search.TagScoringFunction", + "azure.search.documents.indexes.models.TagScoringParameters": "Search.TagScoringParameters", + "azure.search.documents.models.TextResult": "Search.TextResult", + "azure.search.documents.indexes.models.TextTranslationSkill": "Search.TextTranslationSkill", + "azure.search.documents.indexes.models.TextWeights": "Search.TextWeights", + "azure.search.documents.indexes.models.TruncateTokenFilter": "Search.TruncateTokenFilter", + "azure.search.documents.indexes.models.UaxUrlEmailTokenizer": "Search.UaxUrlEmailTokenizer", + "azure.search.documents.indexes.models.UniqueTokenFilter": "Search.UniqueTokenFilter", + "azure.search.documents.models.VectorQuery": "Search.VectorQuery", + "azure.search.documents.models.VectorizableImageBinaryQuery": "Search.VectorizableImageBinaryQuery", + "azure.search.documents.models.VectorizableImageUrlQuery": "Search.VectorizableImageUrlQuery", + "azure.search.documents.models.VectorizableTextQuery": "Search.VectorizableTextQuery", + "azure.search.documents.models.VectorizedQuery": "Search.VectorizedQuery", + "azure.search.documents.models.VectorsDebugInfo": "Search.VectorsDebugInfo", + "azure.search.documents.indexes.models.VectorSearch": "Search.VectorSearch", + "azure.search.documents.indexes.models.VectorSearchProfile": "Search.VectorSearchProfile", + "azure.search.documents.models.VectorSimilarityThreshold": "Search.VectorSimilarityThreshold", + "azure.search.documents.indexes.models.VisionVectorizeSkill": "Search.VisionVectorizeSkill", + "azure.search.documents.indexes.models.WebApiHttpHeaders": "Search.WebApiHttpHeaders", + "azure.search.documents.indexes.models.WebApiSkill": "Search.WebApiSkill", + "azure.search.documents.indexes.models.WebApiVectorizer": "Search.WebApiVectorizer", + "azure.search.documents.indexes.models.WebApiVectorizerParameters": "Search.WebApiVectorizerParameters", + "azure.search.documents.indexes.models.WebKnowledgeSource": "Search.WebKnowledgeSource", + "azure.search.documents.indexes.models.WebKnowledgeSourceDomain": "Search.WebKnowledgeSourceDomain", + "azure.search.documents.indexes.models.WebKnowledgeSourceDomains": "Search.WebKnowledgeSourceDomains", + "azure.search.documents.indexes.models.WebKnowledgeSourceParameters": "Search.WebKnowledgeSourceParameters", + "azure.search.documents.knowledgebases.models.WebKnowledgeSourceParams": "Search.WebKnowledgeSourceParams", + "azure.search.documents.indexes.models.WordDelimiterTokenFilter": "Search.WordDelimiterTokenFilter", + "azure.search.documents.models.QueryType": "Search.QueryType", + "azure.search.documents.models.ScoringStatistics": "Search.ScoringStatistics", + "azure.search.documents.models.QueryDebugMode": "Search.QueryDebugMode", + "azure.search.documents.models.SearchMode": "Search.SearchMode", + "azure.search.documents.models.QueryLanguage": "Search.QueryLanguage", + "azure.search.documents.models.QuerySpellerType": "Search.QuerySpellerType", + "azure.search.documents.models.SemanticErrorMode": "Search.SemanticErrorMode", + "azure.search.documents.models.QueryAnswerType": "Search.QueryAnswerType", + "azure.search.documents.models.QueryCaptionType": "Search.QueryCaptionType", + "azure.search.documents.models.QueryRewritesType": "Search.QueryRewritesType", + "azure.search.documents.models.VectorThresholdKind": "Search.VectorThresholdKind", + "azure.search.documents.models.VectorQueryKind": "Search.VectorQueryKind", + "azure.search.documents.models.VectorFilterMode": "Search.VectorFilterMode", + "azure.search.documents.models.HybridCountAndFacetMode": "Search.HybridCountAndFacetMode", + "azure.search.documents.models.SemanticFieldState": "Search.SemanticFieldState", + "azure.search.documents.models.SemanticErrorReason": "Search.SemanticErrorReason", + "azure.search.documents.models.SemanticSearchResultsType": "Search.SemanticSearchResultsType", + "azure.search.documents.models.SemanticQueryRewritesResultType": "Search.SemanticQueryRewritesResultType", + "azure.search.documents.models.IndexActionType": "Search.IndexActionType", + "azure.search.documents.models.AutocompleteMode": "Search.AutocompleteMode", + "azure.search.documents.models.SearchFieldDataType": "Search.SearchFieldDataType", + "azure.search.documents.models.PermissionFilter": "Search.PermissionFilter", + "azure.search.documents.models.LexicalAnalyzerName": "Search.LexicalAnalyzerName", + "azure.search.documents.models.LexicalNormalizerName": "Search.LexicalNormalizerName", + "azure.search.documents.models.VectorEncodingFormat": "Search.VectorEncodingFormat", + "azure.search.documents.models.ScoringFunctionInterpolation": "Search.ScoringFunctionInterpolation", + "azure.search.documents.models.ScoringFunctionAggregation": "Search.ScoringFunctionAggregation", + "azure.search.documents.models.LexicalTokenizerName": "Search.LexicalTokenizerName", + "azure.search.documents.models.TokenFilterName": "Search.TokenFilterName", + "azure.search.documents.models.CharFilterName": "Search.CharFilterName", + "azure.search.documents.models.RegexFlags": "Search.RegexFlags", + "azure.search.documents.models.TokenCharacterKind": "Search.TokenCharacterKind", + "azure.search.documents.models.MicrosoftStemmingTokenizerLanguage": "Search.MicrosoftStemmingTokenizerLanguage", + "azure.search.documents.models.MicrosoftTokenizerLanguage": "Search.MicrosoftTokenizerLanguage", + "azure.search.documents.models.CjkBigramTokenFilterScripts": "Search.CjkBigramTokenFilterScripts", + "azure.search.documents.models.EdgeNGramTokenFilterSide": "Search.EdgeNGramTokenFilterSide", + "azure.search.documents.models.PhoneticEncoder": "Search.PhoneticEncoder", + "azure.search.documents.models.SnowballTokenFilterLanguage": "Search.SnowballTokenFilterLanguage", + "azure.search.documents.models.StemmerTokenFilterLanguage": "Search.StemmerTokenFilterLanguage", + "azure.search.documents.models.StopwordsList": "Search.StopwordsList", + "azure.search.documents.models.RankingOrder": "Search.RankingOrder", + "azure.search.documents.models.VectorSearchAlgorithmKind": "Search.VectorSearchAlgorithmKind", + "azure.search.documents.models.VectorSearchAlgorithmMetric": "Search.VectorSearchAlgorithmMetric", + "azure.search.documents.models.VectorSearchVectorizerKind": "Search.VectorSearchVectorizerKind", + "azure.search.documents.models.AIFoundryModelCatalogName": "Search.AIFoundryModelCatalogName", + "azure.search.documents.models.AzureOpenAIModelName": "Search.AzureOpenAIModelName", + "azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod": "Search.VectorSearchCompressionRescoreStorageMethod", + "azure.search.documents.models.VectorSearchCompressionKind": "Search.VectorSearchCompressionKind", + "azure.search.documents.models.VectorSearchCompressionTarget": "Search.VectorSearchCompressionTarget", + "azure.search.documents.models.SearchIndexPermissionFilterOption": "Search.SearchIndexPermissionFilterOption", + "azure.search.documents.models.KnowledgeBaseModelKind": "Search.KnowledgeBaseModelKind", + "azure.search.documents.models.KnowledgeRetrievalReasoningEffortKind": "Search.KnowledgeRetrievalReasoningEffortKind", + "azure.search.documents.models.KnowledgeRetrievalOutputMode": "Search.KnowledgeRetrievalOutputMode", + "azure.search.documents.models.KnowledgeSourceKind": "Search.KnowledgeSourceKind", + "azure.search.documents.models.KnowledgeSourceIngestionPermissionOption": "Search.KnowledgeSourceIngestionPermissionOption", + "azure.search.documents.models.KnowledgeSourceContentExtractionMode": "Search.KnowledgeSourceContentExtractionMode", + "azure.search.documents.models.IndexedSharePointContainerName": "Search.IndexedSharePointContainerName", + "azure.search.documents.models.KnowledgeSourceSynchronizationStatus": "Search.KnowledgeSourceSynchronizationStatus", + "azure.search.documents.models.SearchIndexerDataSourceType": "Search.SearchIndexerDataSourceType", + "azure.search.documents.models.IndexerPermissionOption": "Search.IndexerPermissionOption", + "azure.search.documents.models.IndexerResyncOption": "Search.IndexerResyncOption", + "azure.search.documents.models.BlobIndexerParsingMode": "Search.BlobIndexerParsingMode", + "azure.search.documents.models.MarkdownParsingSubmode": "Search.MarkdownParsingSubmode", + "azure.search.documents.models.MarkdownHeaderDepth": "Search.MarkdownHeaderDepth", + "azure.search.documents.models.BlobIndexerDataToExtract": "Search.BlobIndexerDataToExtract", + "azure.search.documents.models.BlobIndexerImageAction": "Search.BlobIndexerImageAction", + "azure.search.documents.models.BlobIndexerPDFTextRotationAlgorithm": "Search.BlobIndexerPDFTextRotationAlgorithm", + "azure.search.documents.models.IndexerExecutionEnvironment": "Search.IndexerExecutionEnvironment", + "azure.search.documents.models.IndexerStatus": "Search.IndexerStatus", + "azure.search.documents.models.IndexerExecutionStatus": "Search.IndexerExecutionStatus", + "azure.search.documents.models.IndexerExecutionStatusDetail": "Search.IndexerExecutionStatusDetail", + "azure.search.documents.models.IndexingMode": "Search.IndexingMode", + "azure.search.documents.models.ChatCompletionExtraParametersBehavior": "Search.ChatCompletionExtraParametersBehavior", + "azure.search.documents.models.ChatCompletionResponseFormatType": "Search.ChatCompletionResponseFormatType", + "azure.search.documents.models.CustomEntityLookupSkillLanguage": "Search.CustomEntityLookupSkillLanguage", + "azure.search.documents.models.KeyPhraseExtractionSkillLanguage": "Search.KeyPhraseExtractionSkillLanguage", + "azure.search.documents.models.PIIDetectionSkillMaskingMode": "Search.PIIDetectionSkillMaskingMode", + "azure.search.documents.models.SplitSkillLanguage": "Search.SplitSkillLanguage", + "azure.search.documents.models.TextSplitMode": "Search.TextSplitMode", + "azure.search.documents.models.SplitSkillUnit": "Search.SplitSkillUnit", + "azure.search.documents.models.SplitSkillEncoderModelName": "Search.SplitSkillEncoderModelName", + "azure.search.documents.models.TextTranslationSkillLanguage": "Search.TextTranslationSkillLanguage", + "azure.search.documents.models.ContentUnderstandingSkillExtractionOptions": "Search.ContentUnderstandingSkillExtractionOptions", + "azure.search.documents.models.ContentUnderstandingSkillChunkingUnit": "Search.ContentUnderstandingSkillChunkingUnit", + "azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputFormat": "Search.DocumentIntelligenceLayoutSkillOutputFormat", + "azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputMode": "Search.DocumentIntelligenceLayoutSkillOutputMode", + "azure.search.documents.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth": "Search.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", + "azure.search.documents.models.DocumentIntelligenceLayoutSkillExtractionOptions": "Search.DocumentIntelligenceLayoutSkillExtractionOptions", + "azure.search.documents.models.DocumentIntelligenceLayoutSkillChunkingUnit": "Search.DocumentIntelligenceLayoutSkillChunkingUnit", + "azure.search.documents.models.ImageAnalysisSkillLanguage": "Search.ImageAnalysisSkillLanguage", + "azure.search.documents.models.VisualFeature": "Search.VisualFeature", + "azure.search.documents.models.ImageDetail": "Search.ImageDetail", + "azure.search.documents.models.OcrSkillLanguage": "Search.OcrSkillLanguage", + "azure.search.documents.models.OcrLineEnding": "Search.OcrLineEnding", + "azure.search.documents.models.IndexProjectionMode": "Search.IndexProjectionMode", + "azure.search.documents.models.KnowledgeBaseMessageContentType": "Search.KnowledgeBaseMessageContentType", + "azure.search.documents.models.KnowledgeBaseActivityRecordType": "Search.KnowledgeBaseActivityRecordType", + "azure.search.documents.models.KnowledgeBaseReferenceType": "Search.KnowledgeBaseReferenceType", + "azure.search.documents.models.KnowledgeRetrievalIntentType": "Search.KnowledgeRetrievalIntentType", + "azure.search.documents.SearchClient.get_document_count": "Customizations.SearchClient.Documents.count", + "azure.search.documents.aio.SearchClient.get_document_count": "Customizations.SearchClient.Documents.count", + "azure.search.documents.SearchClient.get_document": "Customizations.SearchClient.Documents.get", + "azure.search.documents.aio.SearchClient.get_document": "Customizations.SearchClient.Documents.get", + "azure.search.documents.SearchIndexClient.get_synonym_map": "Customizations.SearchIndexClient.SynonymMaps.get", + "azure.search.documents.aio.SearchIndexClient.get_synonym_map": "Customizations.SearchIndexClient.SynonymMaps.get", + "azure.search.documents.SearchIndexClient.create_synonym_map": "Customizations.SearchIndexClient.SynonymMaps.create", + "azure.search.documents.aio.SearchIndexClient.create_synonym_map": "Customizations.SearchIndexClient.SynonymMaps.create", + "azure.search.documents.SearchIndexClient.get_index": "Customizations.SearchIndexClient.Indexes.get", + "azure.search.documents.aio.SearchIndexClient.get_index": "Customizations.SearchIndexClient.Indexes.get", + "azure.search.documents.SearchIndexClient.list_indexes": "Customizations.SearchIndexClient.Indexes.list", + "azure.search.documents.aio.SearchIndexClient.list_indexes": "Customizations.SearchIndexClient.Indexes.list", + "azure.search.documents.SearchIndexClient.create_index": "Customizations.SearchIndexClient.Indexes.create", + "azure.search.documents.aio.SearchIndexClient.create_index": "Customizations.SearchIndexClient.Indexes.create", + "azure.search.documents.SearchIndexClient.get_alias": "Customizations.SearchIndexClient.Aliases.get", + "azure.search.documents.aio.SearchIndexClient.get_alias": "Customizations.SearchIndexClient.Aliases.get", + "azure.search.documents.SearchIndexClient.list_aliases": "Customizations.SearchIndexClient.Aliases.list", + "azure.search.documents.aio.SearchIndexClient.list_aliases": "Customizations.SearchIndexClient.Aliases.list", + "azure.search.documents.SearchIndexClient.create_alias": "Customizations.SearchIndexClient.Aliases.create", + "azure.search.documents.aio.SearchIndexClient.create_alias": "Customizations.SearchIndexClient.Aliases.create", + "azure.search.documents.SearchIndexClient.get_knowledge_base": "Customizations.SearchIndexClient.KnowledgeBases.get", + "azure.search.documents.aio.SearchIndexClient.get_knowledge_base": "Customizations.SearchIndexClient.KnowledgeBases.get", + "azure.search.documents.SearchIndexClient.list_knowledge_bases": "Customizations.SearchIndexClient.KnowledgeBases.list", + "azure.search.documents.aio.SearchIndexClient.list_knowledge_bases": "Customizations.SearchIndexClient.KnowledgeBases.list", + "azure.search.documents.SearchIndexClient.create_knowledge_base": "Customizations.SearchIndexClient.KnowledgeBases.create", + "azure.search.documents.aio.SearchIndexClient.create_knowledge_base": "Customizations.SearchIndexClient.KnowledgeBases.create", + "azure.search.documents.SearchIndexClient.get_knowledge_source": "Customizations.SearchIndexClient.Sources.get", + "azure.search.documents.aio.SearchIndexClient.get_knowledge_source": "Customizations.SearchIndexClient.Sources.get", + "azure.search.documents.SearchIndexClient.list_knowledge_sources": "Customizations.SearchIndexClient.Sources.list", + "azure.search.documents.aio.SearchIndexClient.list_knowledge_sources": "Customizations.SearchIndexClient.Sources.list", + "azure.search.documents.SearchIndexClient.create_knowledge_source": "Customizations.SearchIndexClient.Sources.create", + "azure.search.documents.aio.SearchIndexClient.create_knowledge_source": "Customizations.SearchIndexClient.Sources.create", + "azure.search.documents.SearchIndexClient.get_knowledge_source_status": "Customizations.SearchIndexClient.Sources.getStatus", + "azure.search.documents.aio.SearchIndexClient.get_knowledge_source_status": "Customizations.SearchIndexClient.Sources.getStatus", + "azure.search.documents.SearchIndexClient.get_service_statistics": "Customizations.SearchIndexClient.Root.getServiceStatistics", + "azure.search.documents.aio.SearchIndexClient.get_service_statistics": "Customizations.SearchIndexClient.Root.getServiceStatistics", + "azure.search.documents.SearchIndexClient.list_index_stats_summary": "Customizations.SearchIndexClient.Root.getIndexStatsSummary", + "azure.search.documents.aio.SearchIndexClient.list_index_stats_summary": "Customizations.SearchIndexClient.Root.getIndexStatsSummary", + "azure.search.documents.SearchIndexerClient.get_data_source_connection": "Customizations.SearchIndexerClient.DataSources.get", + "azure.search.documents.aio.SearchIndexerClient.get_data_source_connection": "Customizations.SearchIndexerClient.DataSources.get", + "azure.search.documents.SearchIndexerClient.create_data_source_connection": "Customizations.SearchIndexerClient.DataSources.create", + "azure.search.documents.aio.SearchIndexerClient.create_data_source_connection": "Customizations.SearchIndexerClient.DataSources.create", + "azure.search.documents.SearchIndexerClient.reset_indexer": "Customizations.SearchIndexerClient.Indexers.reset", + "azure.search.documents.aio.SearchIndexerClient.reset_indexer": "Customizations.SearchIndexerClient.Indexers.reset", + "azure.search.documents.SearchIndexerClient.run_indexer": "Customizations.SearchIndexerClient.Indexers.run", + "azure.search.documents.aio.SearchIndexerClient.run_indexer": "Customizations.SearchIndexerClient.Indexers.run", + "azure.search.documents.SearchIndexerClient.get_indexer": "Customizations.SearchIndexerClient.Indexers.get", + "azure.search.documents.aio.SearchIndexerClient.get_indexer": "Customizations.SearchIndexerClient.Indexers.get", + "azure.search.documents.SearchIndexerClient.create_indexer": "Customizations.SearchIndexerClient.Indexers.create", + "azure.search.documents.aio.SearchIndexerClient.create_indexer": "Customizations.SearchIndexerClient.Indexers.create", + "azure.search.documents.SearchIndexerClient.get_indexer_status": "Customizations.SearchIndexerClient.Indexers.getStatus", + "azure.search.documents.aio.SearchIndexerClient.get_indexer_status": "Customizations.SearchIndexerClient.Indexers.getStatus", + "azure.search.documents.SearchIndexerClient.get_skillset": "Customizations.SearchIndexerClient.Skillsets.get", + "azure.search.documents.aio.SearchIndexerClient.get_skillset": "Customizations.SearchIndexerClient.Skillsets.get", + "azure.search.documents.SearchIndexerClient.create_skillset": "Customizations.SearchIndexerClient.Skillsets.create", + "azure.search.documents.aio.SearchIndexerClient.create_skillset": "Customizations.SearchIndexerClient.Skillsets.create", + "azure.search.documents.KnowledgeBaseRetrievalClient.retrieve": "Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve", + "azure.search.documents.aio.KnowledgeBaseRetrievalClient.retrieve": "Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve" + } +} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/assets.json b/sdk/search/azure-search-documents/assets.json index 4ab0734b6c11..ca6d7fed44dc 100644 --- a/sdk/search/azure-search-documents/assets.json +++ b/sdk/search/azure-search-documents/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/search/azure-search-documents", - "Tag": "python/search/azure-search-documents_5403fd605d" + "Tag": "python/search/azure-search-documents_b7fcd768c2" } diff --git a/sdk/search/azure-search-documents/azure/__init__.py b/sdk/search/azure-search-documents/azure/__init__.py index 4c33a0853ef3..d55ccad1f573 100644 --- a/sdk/search/azure-search-documents/azure/__init__.py +++ b/sdk/search/azure-search-documents/azure/__init__.py @@ -1,6 +1 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint:disable=missing-docstring -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/__init__.py b/sdk/search/azure-search-documents/azure/search/__init__.py index 4c33a0853ef3..d55ccad1f573 100644 --- a/sdk/search/azure-search-documents/azure/search/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/__init__.py @@ -1,6 +1 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint:disable=missing-docstring -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/__init__.py index cdb1217ba956..63ab1b900961 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/__init__.py @@ -1,44 +1,32 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._index_documents_batch import IndexDocumentsBatch -from ._search_documents_error import RequestEntityTooLargeError -from ._search_client import SearchClient, SearchItemPaged -from ._search_indexing_buffered_sender import SearchIndexingBufferedSender -from ._api_versions import ApiVersion +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchClient # type: ignore from ._version import VERSION __version__ = VERSION +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk -__all__ = ( - "ApiVersion", - "IndexDocumentsBatch", +__all__ = [ "SearchClient", - "SearchItemPaged", - "SearchIndexingBufferedSender", - "RequestEntityTooLargeError", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py b/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py deleted file mode 100644 index d5a084e0fd25..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py +++ /dev/null @@ -1,17 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - V2020_06_30 = "2020-06-30" - V2023_11_01 = "2023-11-01" - V2024_07_01 = "2024-07-01" - V2025_11_01_PREVIEW = "2025-11-01-preview" - - -DEFAULT_VERSION = ApiVersion.V2025_11_01_PREVIEW diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/_client.py similarity index 65% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py rename to sdk/search/azure-search-documents/azure/search/documents/_client.py index 8cde28c7d859..5f688aa13b44 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_client.py @@ -1,42 +1,52 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import PipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import SearchIndexClientConfiguration +from ._configuration import SearchClientConfiguration +from ._operations import _SearchClientOperationsMixin from ._utils.serialization import Deserializer, Serializer -from .operations import DocumentsOperations +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class SearchIndexClient: - """Client that can be used to query an index and upload, merge, or delete documents. - :ivar documents: DocumentsOperations operations - :vartype documents: azure.search.documents.operations.DocumentsOperations - :param endpoint: The endpoint URL of the search service. Required. +class SearchClient(_SearchClientOperationsMixin): + """SearchClient. + + :param endpoint: Service host. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential :param index_name: The name of the index. Required. :type index_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, index_name: str, **kwargs: Any + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], index_name: str, **kwargs: Any ) -> None: - _endpoint = "{endpoint}/indexes('{indexName}')" - self._config = SearchIndexClientConfiguration(endpoint=endpoint, index_name=index_name, **kwargs) + _endpoint = "{endpoint}" + self._config = SearchClientConfiguration( + endpoint=endpoint, credential=credential, index_name=index_name, **kwargs + ) _policies = kwargs.pop("policies", None) if _policies is None: @@ -57,19 +67,17 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.documents = DocumentsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -84,7 +92,6 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_configuration.py new file mode 100644 index 000000000000..f6f346ca1211 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_configuration.py @@ -0,0 +1,79 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class SearchClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], index_name: str, **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if index_name is None: + raise ValueError("Parameter 'index_name' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.index_name = index_name + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py deleted file mode 100644 index c6cd95396f11..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_index_client import SearchIndexClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchIndexClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py deleted file mode 100644 index 5677faaf28d6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchIndexClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param index_name: The name of the index. Required. - :type index_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, index_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-11-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if index_name is None: - raise ValueError("Parameter 'index_name' must not be None.") - - self.endpoint = endpoint - self.index_name = index_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchindexclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py deleted file mode 100644 index c6cd95396f11..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_index_client import SearchIndexClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchIndexClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py deleted file mode 100644 index 562d704a6973..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchIndexClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param index_name: The name of the index. Required. - :type index_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, index_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-11-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if index_name is None: - raise ValueError("Parameter 'index_name' must not be None.") - - self.endpoint = endpoint - self.index_name = index_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchindexclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py deleted file mode 100644 index f35b4acec1c7..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py +++ /dev/null @@ -1,1180 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._documents_operations import ( - build_autocomplete_get_request, - build_autocomplete_post_request, - build_count_request, - build_get_request, - build_index_request, - build_search_get_request, - build_search_post_request, - build_suggest_get_request, - build_suggest_post_request, -) -from .._configuration import SearchIndexClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class DocumentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`documents` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def count(self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any) -> int: - """Queries the number of documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Count-Documents - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: int or the result of cls(response) - :rtype: int - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[int] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_count_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("int", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def search_get( - self, - search_text: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - search_options: Optional[_models.SearchOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. Default value is None. - :type search_text: str - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param search_options: Parameter group. Default value is None. - :type search_options: ~azure.search.documents.models.SearchOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _include_total_result_count = None - _facets = None - _filter = None - _highlight_fields = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _query_type = None - _scoring_parameters = None - _scoring_profile = None - _search_fields = None - _search_mode = None - _scoring_statistics = None - _session_id = None - _select = None - _skip = None - _top = None - _x_ms_client_request_id = None - _semantic_configuration = None - _semantic_error_handling = None - _semantic_max_wait_in_milliseconds = None - _answers = None - _captions = None - _semantic_query = None - _query_rewrites = None - _debug = None - _query_language = None - _speller = None - _semantic_fields = None - if search_options is not None: - _answers = search_options.answers - _captions = search_options.captions - _debug = search_options.debug - _facets = search_options.facets - _filter = search_options.filter - _highlight_fields = search_options.highlight_fields - _highlight_post_tag = search_options.highlight_post_tag - _highlight_pre_tag = search_options.highlight_pre_tag - _include_total_result_count = search_options.include_total_result_count - _minimum_coverage = search_options.minimum_coverage - _order_by = search_options.order_by - _query_language = search_options.query_language - _query_rewrites = search_options.query_rewrites - _query_type = search_options.query_type - _scoring_parameters = search_options.scoring_parameters - _scoring_profile = search_options.scoring_profile - _scoring_statistics = search_options.scoring_statistics - _search_fields = search_options.search_fields - _search_mode = search_options.search_mode - _select = search_options.select - _semantic_configuration = search_options.semantic_configuration - _semantic_error_handling = search_options.semantic_error_handling - _semantic_fields = search_options.semantic_fields - _semantic_max_wait_in_milliseconds = search_options.semantic_max_wait_in_milliseconds - _semantic_query = search_options.semantic_query - _session_id = search_options.session_id - _skip = search_options.skip - _speller = search_options.speller - _top = search_options.top - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_search_get_request( - search_text=search_text, - include_total_result_count=_include_total_result_count, - facets=_facets, - filter=_filter, - highlight_fields=_highlight_fields, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - query_type=_query_type, - scoring_parameters=_scoring_parameters, - scoring_profile=_scoring_profile, - search_fields=_search_fields, - search_mode=_search_mode, - scoring_statistics=_scoring_statistics, - session_id=_session_id, - select=_select, - skip=_skip, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - semantic_configuration=_semantic_configuration, - semantic_error_handling=_semantic_error_handling, - semantic_max_wait_in_milliseconds=_semantic_max_wait_in_milliseconds, - answers=_answers, - captions=_captions, - semantic_query=_semantic_query, - query_rewrites=_query_rewrites, - debug=_debug, - query_language=_query_language, - speller=_speller, - semantic_fields=_semantic_fields, - x_ms_query_source_authorization=x_ms_query_source_authorization, - x_ms_enable_elevated_read=x_ms_enable_elevated_read, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def search_post( - self, - search_request: _models.SearchRequest, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: ~azure.search.documents.models.SearchRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def search_post( - self, - search_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def search_post( - self, - search_request: Union[_models.SearchRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Is either a SearchRequest type or - a IO[bytes] type. Required. - :type search_request: ~azure.search.documents.models.SearchRequest or IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(search_request, (IOBase, bytes)): - _content = search_request - else: - _json = self._serialize.body(search_request, "SearchRequest") - - _request = build_search_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - x_ms_enable_elevated_read=x_ms_enable_elevated_read, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get( - self, - key: str, - selected_fields: Optional[list[str]] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> dict[str, Any]: - """Retrieves a document from the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/lookup-document - - :param key: The key of the document to retrieve. Required. - :type key: str - :param selected_fields: List of field names to retrieve for the document; Any field not - retrieved will be missing from the returned document. Default value is None. - :type selected_fields: list[str] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: dict mapping str to any or the result of cls(response) - :rtype: dict[str, any] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[dict[str, Any]] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - key=key, - selected_fields=selected_fields, - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - x_ms_enable_elevated_read=x_ms_enable_elevated_read, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("{object}", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def suggest_get( - self, - search_text: str, - suggester_name: str, - suggest_options: Optional[_models.SuggestOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param suggest_options: Parameter group. Default value is None. - :type suggest_options: ~azure.search.documents.models.SuggestOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _search_fields = None - _select = None - _top = None - _x_ms_client_request_id = None - if suggest_options is not None: - _filter = suggest_options.filter - _highlight_post_tag = suggest_options.highlight_post_tag - _highlight_pre_tag = suggest_options.highlight_pre_tag - _minimum_coverage = suggest_options.minimum_coverage - _order_by = suggest_options.order_by - _search_fields = suggest_options.search_fields - _select = suggest_options.select - _top = suggest_options.top - _use_fuzzy_matching = suggest_options.use_fuzzy_matching - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_suggest_get_request( - search_text=search_text, - suggester_name=suggester_name, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - search_fields=_search_fields, - select=_select, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def suggest_post( - self, - suggest_request: _models.SuggestRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def suggest_post( - self, - suggest_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def suggest_post( - self, - suggest_request: Union[_models.SuggestRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Is either a SuggestRequest type or a IO[bytes] - type. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(suggest_request, (IOBase, bytes)): - _content = suggest_request - else: - _json = self._serialize.body(suggest_request, "SuggestRequest") - - _request = build_suggest_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def index( - self, - batch: _models.IndexBatch, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexBatch - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def index( - self, - batch: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def index( - self, - batch: Union[_models.IndexBatch, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Is either a IndexBatch type or a IO[bytes] type. - Required. - :type batch: ~azure.search.documents.models.IndexBatch or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.IndexDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(batch, (IOBase, bytes)): - _content = batch - else: - _json = self._serialize.body(batch, "IndexBatch") - - _request = build_index_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 207]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("IndexDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def autocomplete_get( - self, - search_text: str, - suggester_name: str, - request_options: Optional[_models.RequestOptions] = None, - autocomplete_options: Optional[_models.AutocompleteOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param search_text: The incomplete term which should be auto-completed. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :param autocomplete_options: Parameter group. Default value is None. - :type autocomplete_options: ~azure.search.documents.models.AutocompleteOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - _autocomplete_mode = None - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _search_fields = None - _top = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - if autocomplete_options is not None: - _autocomplete_mode = autocomplete_options.autocomplete_mode - _filter = autocomplete_options.filter - _highlight_post_tag = autocomplete_options.highlight_post_tag - _highlight_pre_tag = autocomplete_options.highlight_pre_tag - _minimum_coverage = autocomplete_options.minimum_coverage - _search_fields = autocomplete_options.search_fields - _top = autocomplete_options.top - _use_fuzzy_matching = autocomplete_options.use_fuzzy_matching - - _request = build_autocomplete_get_request( - search_text=search_text, - suggester_name=suggester_name, - x_ms_client_request_id=_x_ms_client_request_id, - autocomplete_mode=_autocomplete_mode, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - search_fields=_search_fields, - top=_top, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def autocomplete_post( - self, - autocomplete_request: _models.AutocompleteRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def autocomplete_post( - self, - autocomplete_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def autocomplete_post( - self, - autocomplete_request: Union[_models.AutocompleteRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Is either a - AutocompleteRequest type or a IO[bytes] type. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(autocomplete_request, (IOBase, bytes)): - _content = autocomplete_request - else: - _json = self._serialize.body(autocomplete_request, "AutocompleteRequest") - - _request = build_autocomplete_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py deleted file mode 100644 index e91cb0f48750..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py +++ /dev/null @@ -1,154 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AutocompleteItem, - AutocompleteOptions, - AutocompleteRequest, - AutocompleteResult, - DebugInfo, - DocumentDebugInfo, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - FacetResult, - HybridSearch, - IndexAction, - IndexBatch, - IndexDocumentsResult, - IndexingResult, - QueryAnswerResult, - QueryCaptionResult, - QueryResultDocumentInnerHit, - QueryResultDocumentRerankerInput, - QueryResultDocumentSemanticField, - QueryResultDocumentSubscores, - QueryRewritesDebugInfo, - QueryRewritesValuesDebugInfo, - RequestOptions, - SearchDocumentsResult, - SearchOptions, - SearchRequest, - SearchResult, - SearchScoreThreshold, - SemanticDebugInfo, - SingleVectorFieldResult, - SuggestDocumentsResult, - SuggestOptions, - SuggestRequest, - SuggestResult, - TextResult, - VectorQuery, - VectorSimilarityThreshold, - VectorThreshold, - VectorizableImageBinaryQuery, - VectorizableImageUrlQuery, - VectorizableTextQuery, - VectorizedQuery, - VectorsDebugInfo, -) - -from ._search_index_client_enums import ( # type: ignore - AutocompleteMode, - HybridCountAndFacetMode, - IndexActionType, - QueryAnswerType, - QueryCaptionType, - QueryDebugMode, - QueryLanguage, - QueryRewritesType, - QuerySpellerType, - QueryType, - ScoringStatistics, - SearchMode, - SemanticErrorMode, - SemanticErrorReason, - SemanticFieldState, - SemanticQueryRewritesResultType, - SemanticSearchResultsType, - VectorFilterMode, - VectorQueryKind, - VectorThresholdKind, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AutocompleteItem", - "AutocompleteOptions", - "AutocompleteRequest", - "AutocompleteResult", - "DebugInfo", - "DocumentDebugInfo", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "FacetResult", - "HybridSearch", - "IndexAction", - "IndexBatch", - "IndexDocumentsResult", - "IndexingResult", - "QueryAnswerResult", - "QueryCaptionResult", - "QueryResultDocumentInnerHit", - "QueryResultDocumentRerankerInput", - "QueryResultDocumentSemanticField", - "QueryResultDocumentSubscores", - "QueryRewritesDebugInfo", - "QueryRewritesValuesDebugInfo", - "RequestOptions", - "SearchDocumentsResult", - "SearchOptions", - "SearchRequest", - "SearchResult", - "SearchScoreThreshold", - "SemanticDebugInfo", - "SingleVectorFieldResult", - "SuggestDocumentsResult", - "SuggestOptions", - "SuggestRequest", - "SuggestResult", - "TextResult", - "VectorQuery", - "VectorSimilarityThreshold", - "VectorThreshold", - "VectorizableImageBinaryQuery", - "VectorizableImageUrlQuery", - "VectorizableTextQuery", - "VectorizedQuery", - "VectorsDebugInfo", - "AutocompleteMode", - "HybridCountAndFacetMode", - "IndexActionType", - "QueryAnswerType", - "QueryCaptionType", - "QueryDebugMode", - "QueryLanguage", - "QueryRewritesType", - "QuerySpellerType", - "QueryType", - "ScoringStatistics", - "SearchMode", - "SemanticErrorMode", - "SemanticErrorReason", - "SemanticFieldState", - "SemanticQueryRewritesResultType", - "SemanticSearchResultsType", - "VectorFilterMode", - "VectorQueryKind", - "VectorThresholdKind", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py deleted file mode 100644 index 3d761266bc2b..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py +++ /dev/null @@ -1,3119 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class AutocompleteItem(_serialization.Model): - """The result of Autocomplete requests. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar text: The completed term. Required. - :vartype text: str - :ivar query_plus_text: The query along with the completed term. Required. - :vartype query_plus_text: str - """ - - _validation = { - "text": {"required": True, "readonly": True}, - "query_plus_text": {"required": True, "readonly": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "str"}, - "query_plus_text": {"key": "queryPlusText", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.text: Optional[str] = None - self.query_plus_text: Optional[str] = None - - -class AutocompleteOptions(_serialization.Model): - """Parameter group. - - :ivar autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :vartype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :ivar filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the autocomplete - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :vartype search_fields: list[str] - :ivar top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :vartype top: int - """ - - _attribute_map = { - "autocomplete_mode": {"key": "autocompleteMode", "type": "str"}, - "filter": {"key": "$filter", "type": "str"}, - "use_fuzzy_matching": {"key": "UseFuzzyMatching", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "search_fields": {"key": "searchFields", "type": "[str]"}, - "top": {"key": "$top", "type": "int"}, - } - - def __init__( - self, - *, - autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[list[str]] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by an autocomplete query in order for the query to be reported as a - success. This parameter can be useful for ensuring search availability even for services with - only one replica. The default is 80. - :paramtype minimum_coverage: float - :keyword search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :paramtype search_fields: list[str] - :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 - and 100. The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.autocomplete_mode = autocomplete_mode - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.search_fields = search_fields - self.top = top - - -class AutocompleteRequest(_serialization.Model): - """Parameters for fuzzy matching, and other autocomplete query behaviors. - - All required parameters must be populated in order to send to server. - - :ivar search_text: The search text on which to base autocomplete results. Required. - :vartype search_text: str - :ivar autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :vartype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :ivar filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the autocomplete - query. Default is false. When set to true, the query will autocomplete terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. - :vartype search_fields: str - :ivar suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :vartype suggester_name: str - :ivar top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :vartype top: int - """ - - _validation = { - "search_text": {"required": True}, - "suggester_name": {"required": True}, - } - - _attribute_map = { - "search_text": {"key": "search", "type": "str"}, - "autocomplete_mode": {"key": "autocompleteMode", "type": "str"}, - "filter": {"key": "filter", "type": "str"}, - "use_fuzzy_matching": {"key": "fuzzy", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "search_fields": {"key": "searchFields", "type": "str"}, - "suggester_name": {"key": "suggesterName", "type": "str"}, - "top": {"key": "top", "type": "int"}, - } - - def __init__( - self, - *, - search_text: str, - suggester_name: str, - autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword search_text: The search text on which to base autocomplete results. Required. - :paramtype search_text: str - :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will autocomplete terms even - if there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by an autocomplete query in order for the query to be reported as a - success. This parameter can be useful for ensuring search availability even for services with - only one replica. The default is 80. - :paramtype minimum_coverage: float - :keyword search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. - :paramtype search_fields: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 - and 100. The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.search_text = search_text - self.autocomplete_mode = autocomplete_mode - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.search_fields = search_fields - self.suggester_name = suggester_name - self.top = top - - -class AutocompleteResult(_serialization.Model): - """The result of Autocomplete query. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar coverage: A value indicating the percentage of the index that was considered by the - autocomplete request, or null if minimumCoverage was not specified in the request. - :vartype coverage: float - :ivar results: The list of returned Autocompleted items. Required. - :vartype results: list[~azure.search.documents.models.AutocompleteItem] - """ - - _validation = { - "coverage": {"readonly": True}, - "results": {"required": True, "readonly": True}, - } - - _attribute_map = { - "coverage": {"key": "@search\\.coverage", "type": "float"}, - "results": {"key": "value", "type": "[AutocompleteItem]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.coverage: Optional[float] = None - self.results: Optional[list["_models.AutocompleteItem"]] = None - - -class DebugInfo(_serialization.Model): - """Contains debugging information that can be used to further explore your search results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar query_rewrites: Contains debugging information specific to query rewrites. - :vartype query_rewrites: ~azure.search.documents.models.QueryRewritesDebugInfo - """ - - _validation = { - "query_rewrites": {"readonly": True}, - } - - _attribute_map = { - "query_rewrites": {"key": "queryRewrites", "type": "QueryRewritesDebugInfo"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.query_rewrites: Optional["_models.QueryRewritesDebugInfo"] = None - - -class DocumentDebugInfo(_serialization.Model): - """Contains debugging information that can be used to further explore your search results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar semantic: Contains debugging information specific to semantic ranking requests. - :vartype semantic: ~azure.search.documents.models.SemanticDebugInfo - :ivar vectors: Contains debugging information specific to vector and hybrid search. - :vartype vectors: ~azure.search.documents.models.VectorsDebugInfo - :ivar inner_hits: Contains debugging information specific to vectors matched within a - collection of complex types. - :vartype inner_hits: dict[str, - list[~azure.search.documents.models.QueryResultDocumentInnerHit]] - """ - - _validation = { - "semantic": {"readonly": True}, - "vectors": {"readonly": True}, - "inner_hits": {"readonly": True}, - } - - _attribute_map = { - "semantic": {"key": "semantic", "type": "SemanticDebugInfo"}, - "vectors": {"key": "vectors", "type": "VectorsDebugInfo"}, - "inner_hits": {"key": "innerHits", "type": "{[QueryResultDocumentInnerHit]}"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.semantic: Optional["_models.SemanticDebugInfo"] = None - self.vectors: Optional["_models.VectorsDebugInfo"] = None - self.inner_hits: Optional[dict[str, list["_models.QueryResultDocumentInnerHit"]]] = None - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.search.documents.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.search.documents.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.search.documents.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class FacetResult(_serialization.Model): - """A single bucket of a facet query result. Reports the number of documents with a field value - falling within a particular range or having a particular value or interval. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar count: The approximate count of documents falling within the bucket described by this - facet. - :vartype count: int - :ivar avg: The resulting total avg for the facet when a avg metric is requested. - :vartype avg: float - :ivar min: The resulting total min for the facet when a min metric is requested. - :vartype min: float - :ivar max: The resulting total max for the facet when a max metric is requested. - :vartype max: float - :ivar sum: The resulting total sum for the facet when a sum metric is requested. - :vartype sum: float - :ivar cardinality: The resulting total cardinality for the facet when a cardinality metric is - requested. - :vartype cardinality: int - :ivar facets: The nested facet query results for the search operation, organized as a - collection of buckets for each faceted field; null if the query did not contain any nested - facets. - :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] - """ - - _validation = { - "count": {"readonly": True}, - "avg": {"readonly": True}, - "min": {"readonly": True}, - "max": {"readonly": True}, - "sum": {"readonly": True}, - "cardinality": {"readonly": True}, - "facets": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "count": {"key": "count", "type": "int"}, - "avg": {"key": "avg", "type": "float"}, - "min": {"key": "min", "type": "float"}, - "max": {"key": "max", "type": "float"}, - "sum": {"key": "sum", "type": "float"}, - "cardinality": {"key": "cardinality", "type": "int"}, - "facets": {"key": "@search\\.facets", "type": "{[FacetResult]}"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.count: Optional[int] = None - self.avg: Optional[float] = None - self.min: Optional[float] = None - self.max: Optional[float] = None - self.sum: Optional[float] = None - self.cardinality: Optional[int] = None - self.facets: Optional[dict[str, list["_models.FacetResult"]]] = None - - -class HybridSearch(_serialization.Model): - """TThe query parameters to configure hybrid search behaviors. - - :ivar max_text_recall_size: Determines the maximum number of documents to be retrieved by the - text query portion of a hybrid search request. Those documents will be combined with the - documents matching the vector queries to produce a single final list of results. Choosing a - larger maxTextRecallSize value will allow retrieving and paging through more documents (using - the top and skip parameters), at the cost of higher resource utilization and higher latency. - The value needs to be between 1 and 10,000. Default is 1000. - :vartype max_text_recall_size: int - :ivar count_and_facet_mode: Determines whether the count and facets should includes all - documents that matched the search query, or only the documents that are retrieved within the - 'maxTextRecallSize' window. Known values are: "countRetrievableResults" and "countAllResults". - :vartype count_and_facet_mode: str or ~azure.search.documents.models.HybridCountAndFacetMode - """ - - _attribute_map = { - "max_text_recall_size": {"key": "maxTextRecallSize", "type": "int"}, - "count_and_facet_mode": {"key": "countAndFacetMode", "type": "str"}, - } - - def __init__( - self, - *, - max_text_recall_size: Optional[int] = None, - count_and_facet_mode: Optional[Union[str, "_models.HybridCountAndFacetMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword max_text_recall_size: Determines the maximum number of documents to be retrieved by - the text query portion of a hybrid search request. Those documents will be combined with the - documents matching the vector queries to produce a single final list of results. Choosing a - larger maxTextRecallSize value will allow retrieving and paging through more documents (using - the top and skip parameters), at the cost of higher resource utilization and higher latency. - The value needs to be between 1 and 10,000. Default is 1000. - :paramtype max_text_recall_size: int - :keyword count_and_facet_mode: Determines whether the count and facets should includes all - documents that matched the search query, or only the documents that are retrieved within the - 'maxTextRecallSize' window. Known values are: "countRetrievableResults" and "countAllResults". - :paramtype count_and_facet_mode: str or ~azure.search.documents.models.HybridCountAndFacetMode - """ - super().__init__(**kwargs) - self.max_text_recall_size = max_text_recall_size - self.count_and_facet_mode = count_and_facet_mode - - -class IndexAction(_serialization.Model): - """Represents an index action that operates on a document. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar action_type: The operation to perform on a document in an indexing batch. Known values - are: "upload", "merge", "mergeOrUpload", and "delete". - :vartype action_type: str or ~azure.search.documents.models.IndexActionType - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "action_type": {"key": "@search\\.action", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - action_type: Optional[Union[str, "_models.IndexActionType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword action_type: The operation to perform on a document in an indexing batch. Known values - are: "upload", "merge", "mergeOrUpload", and "delete". - :paramtype action_type: str or ~azure.search.documents.models.IndexActionType - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.action_type = action_type - - -class IndexBatch(_serialization.Model): - """Contains a batch of document write actions to send to the index. - - All required parameters must be populated in order to send to server. - - :ivar actions: The actions in the batch. Required. - :vartype actions: list[~azure.search.documents.models.IndexAction] - """ - - _validation = { - "actions": {"required": True}, - } - - _attribute_map = { - "actions": {"key": "value", "type": "[IndexAction]"}, - } - - def __init__(self, *, actions: list["_models.IndexAction"], **kwargs: Any) -> None: - """ - :keyword actions: The actions in the batch. Required. - :paramtype actions: list[~azure.search.documents.models.IndexAction] - """ - super().__init__(**kwargs) - self.actions = actions - - -class IndexDocumentsResult(_serialization.Model): - """Response containing the status of operations for all documents in the indexing request. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar results: The list of status information for each document in the indexing request. - Required. - :vartype results: list[~azure.search.documents.models.IndexingResult] - """ - - _validation = { - "results": {"required": True, "readonly": True}, - } - - _attribute_map = { - "results": {"key": "value", "type": "[IndexingResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.results: Optional[list["_models.IndexingResult"]] = None - - -class IndexingResult(_serialization.Model): - """Status of an indexing operation for a single document. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar key: The key of a document that was in the indexing request. Required. - :vartype key: str - :ivar error_message: The error message explaining why the indexing operation failed for the - document identified by the key; null if indexing succeeded. - :vartype error_message: str - :ivar succeeded: A value indicating whether the indexing operation succeeded for the document - identified by the key. Required. - :vartype succeeded: bool - :ivar status_code: The status code of the indexing operation. Possible values include: 200 for - a successful update or delete, 201 for successful document creation, 400 for a malformed input - document, 404 for document not found, 409 for a version conflict, 422 when the index is - temporarily unavailable, or 503 for when the service is too busy. Required. - :vartype status_code: int - """ - - _validation = { - "key": {"required": True, "readonly": True}, - "error_message": {"readonly": True}, - "succeeded": {"required": True, "readonly": True}, - "status_code": {"required": True, "readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "error_message": {"key": "errorMessage", "type": "str"}, - "succeeded": {"key": "status", "type": "bool"}, - "status_code": {"key": "statusCode", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.key: Optional[str] = None - self.error_message: Optional[str] = None - self.succeeded: Optional[bool] = None - self.status_code: Optional[int] = None - - -class QueryAnswerResult(_serialization.Model): - """An answer is a text passage extracted from the contents of the most relevant documents that - matched the query. Answers are extracted from the top search results. Answer candidates are - scored and the top answers are selected. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar score: The score value represents how relevant the answer is to the query relative to - other answers returned for the query. - :vartype score: float - :ivar key: The key of the document the answer was extracted from. - :vartype key: str - :ivar text: The text passage extracted from the document contents as the answer. - :vartype text: str - :ivar highlights: Same text passage as in the Text property with highlighted text phrases most - relevant to the query. - :vartype highlights: str - """ - - _validation = { - "score": {"readonly": True}, - "key": {"readonly": True}, - "text": {"readonly": True}, - "highlights": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "score": {"key": "score", "type": "float"}, - "key": {"key": "key", "type": "str"}, - "text": {"key": "text", "type": "str"}, - "highlights": {"key": "highlights", "type": "str"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.score: Optional[float] = None - self.key: Optional[str] = None - self.text: Optional[str] = None - self.highlights: Optional[str] = None - - -class QueryCaptionResult(_serialization.Model): - """Captions are the most representative passages from the document relatively to the search query. - They are often used as document summary. Captions are only returned for queries of type - ``semantic``. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar text: A representative text passage extracted from the document most relevant to the - search query. - :vartype text: str - :ivar highlights: Same text passage as in the Text property with highlighted phrases most - relevant to the query. - :vartype highlights: str - """ - - _validation = { - "text": {"readonly": True}, - "highlights": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "text": {"key": "text", "type": "str"}, - "highlights": {"key": "highlights", "type": "str"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.text: Optional[str] = None - self.highlights: Optional[str] = None - - -class QueryResultDocumentInnerHit(_serialization.Model): - """Detailed scoring information for an individual element of a complex collection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar ordinal: Position of this specific matching element within it's original collection. - Position starts at 0. - :vartype ordinal: int - :ivar vectors: Detailed scoring information for an individual element of a complex collection - that matched a vector query. - :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] - """ - - _validation = { - "ordinal": {"readonly": True}, - "vectors": {"readonly": True}, - } - - _attribute_map = { - "ordinal": {"key": "ordinal", "type": "int"}, - "vectors": {"key": "vectors", "type": "[{SingleVectorFieldResult}]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.ordinal: Optional[int] = None - self.vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = None - - -class QueryResultDocumentRerankerInput(_serialization.Model): - """The raw concatenated strings that were sent to the semantic enrichment process. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar title: The raw string for the title field that was used for semantic enrichment. - :vartype title: str - :ivar content: The raw concatenated strings for the content fields that were used for semantic - enrichment. - :vartype content: str - :ivar keywords: The raw concatenated strings for the keyword fields that were used for semantic - enrichment. - :vartype keywords: str - """ - - _validation = { - "title": {"readonly": True}, - "content": {"readonly": True}, - "keywords": {"readonly": True}, - } - - _attribute_map = { - "title": {"key": "title", "type": "str"}, - "content": {"key": "content", "type": "str"}, - "keywords": {"key": "keywords", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.title: Optional[str] = None - self.content: Optional[str] = None - self.keywords: Optional[str] = None - - -class QueryResultDocumentSemanticField(_serialization.Model): - """Description of fields that were sent to the semantic enrichment process, as well as how they - were used. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the field that was sent to the semantic enrichment process. - :vartype name: str - :ivar state: The way the field was used for the semantic enrichment process (fully used, - partially used, or unused). Known values are: "used", "unused", and "partial". - :vartype state: str or ~azure.search.documents.models.SemanticFieldState - """ - - _validation = { - "name": {"readonly": True}, - "state": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "state": {"key": "state", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.state: Optional[Union[str, "_models.SemanticFieldState"]] = None - - -class QueryResultDocumentSubscores(_serialization.Model): - """The breakdown of subscores between the text and vector query components of the search query for - this document. Each vector query is shown as a separate object in the same order they were - received. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar text: The BM25 or Classic score for the text portion of the query. - :vartype text: ~azure.search.documents.models.TextResult - :ivar vectors: The vector similarity and @search.score values for each vector query. - :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] - :ivar document_boost: The BM25 or Classic score for the text portion of the query. - :vartype document_boost: float - """ - - _validation = { - "text": {"readonly": True}, - "vectors": {"readonly": True}, - "document_boost": {"readonly": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "TextResult"}, - "vectors": {"key": "vectors", "type": "[{SingleVectorFieldResult}]"}, - "document_boost": {"key": "documentBoost", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.text: Optional["_models.TextResult"] = None - self.vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = None - self.document_boost: Optional[float] = None - - -class QueryRewritesDebugInfo(_serialization.Model): - """Contains debugging information specific to query rewrites. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar text: List of query rewrites generated for the text query. - :vartype text: ~azure.search.documents.models.QueryRewritesValuesDebugInfo - :ivar vectors: List of query rewrites generated for the vectorizable text queries. - :vartype vectors: list[~azure.search.documents.models.QueryRewritesValuesDebugInfo] - """ - - _validation = { - "text": {"readonly": True}, - "vectors": {"readonly": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "QueryRewritesValuesDebugInfo"}, - "vectors": {"key": "vectors", "type": "[QueryRewritesValuesDebugInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.text: Optional["_models.QueryRewritesValuesDebugInfo"] = None - self.vectors: Optional[list["_models.QueryRewritesValuesDebugInfo"]] = None - - -class QueryRewritesValuesDebugInfo(_serialization.Model): - """Contains debugging information specific to query rewrites. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar input_query: The input text to the generative query rewriting model. There may be cases - where the user query and the input to the generative model are not identical. - :vartype input_query: str - :ivar rewrites: List of query rewrites. - :vartype rewrites: list[str] - """ - - _validation = { - "input_query": {"readonly": True}, - "rewrites": {"readonly": True}, - } - - _attribute_map = { - "input_query": {"key": "inputQuery", "type": "str"}, - "rewrites": {"key": "rewrites", "type": "[str]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.input_query: Optional[str] = None - self.rewrites: Optional[list[str]] = None - - -class RequestOptions(_serialization.Model): - """Parameter group. - - :ivar x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :vartype x_ms_client_request_id: str - """ - - _attribute_map = { - "x_ms_client_request_id": {"key": "x-ms-client-request-id", "type": "str"}, - } - - def __init__(self, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :paramtype x_ms_client_request_id: str - """ - super().__init__(**kwargs) - self.x_ms_client_request_id = x_ms_client_request_id - - -class SearchDocumentsResult(_serialization.Model): - """Response containing search results from an index. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar count: The total count of results found by the search operation, or null if the count was - not requested. If present, the count may be greater than the number of results in this - response. This can happen if you use the $top or $skip parameters, or if the query can't return - all the requested documents in a single response. - :vartype count: int - :ivar coverage: A value indicating the percentage of the index that was included in the query, - or null if minimumCoverage was not specified in the request. - :vartype coverage: float - :ivar facets: The facet query results for the search operation, organized as a collection of - buckets for each faceted field; null if the query did not include any facet expressions. - :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] - :ivar answers: The answers query results for the search operation; null if the answers query - parameter was not specified or set to 'none'. - :vartype answers: list[~azure.search.documents.models.QueryAnswerResult] - :ivar debug_info: Debug information that applies to the search results as a whole. - :vartype debug_info: ~azure.search.documents.models.DebugInfo - :ivar next_page_parameters: Continuation JSON payload returned when the query can't return all - the requested results in a single response. You can use this JSON along with @odata.nextLink to - formulate another POST Search request to get the next part of the search response. - :vartype next_page_parameters: ~azure.search.documents.models.SearchRequest - :ivar results: The sequence of results returned by the query. Required. - :vartype results: list[~azure.search.documents.models.SearchResult] - :ivar next_link: Continuation URL returned when the query can't return all the requested - results in a single response. You can use this URL to formulate another GET or POST Search - request to get the next part of the search response. Make sure to use the same verb (GET or - POST) as the request that produced this response. - :vartype next_link: str - :ivar semantic_partial_response_reason: Reason that a partial response was returned for a - semantic ranking request. Known values are: "maxWaitExceeded", "capacityOverloaded", and - "transient". - :vartype semantic_partial_response_reason: str or - ~azure.search.documents.models.SemanticErrorReason - :ivar semantic_partial_response_type: Type of partial response that was returned for a semantic - ranking request. Known values are: "baseResults" and "rerankedResults". - :vartype semantic_partial_response_type: str or - ~azure.search.documents.models.SemanticSearchResultsType - :ivar semantic_query_rewrites_result_type: Type of query rewrite that was used to retrieve - documents. "originalQueryOnly" - :vartype semantic_query_rewrites_result_type: str or - ~azure.search.documents.models.SemanticQueryRewritesResultType - """ - - _validation = { - "count": {"readonly": True}, - "coverage": {"readonly": True}, - "facets": {"readonly": True}, - "answers": {"readonly": True}, - "debug_info": {"readonly": True}, - "next_page_parameters": {"readonly": True}, - "results": {"required": True, "readonly": True}, - "next_link": {"readonly": True}, - "semantic_partial_response_reason": {"readonly": True}, - "semantic_partial_response_type": {"readonly": True}, - "semantic_query_rewrites_result_type": {"readonly": True}, - } - - _attribute_map = { - "count": {"key": "@odata\\.count", "type": "int"}, - "coverage": {"key": "@search\\.coverage", "type": "float"}, - "facets": {"key": "@search\\.facets", "type": "{[FacetResult]}"}, - "answers": {"key": "@search\\.answers", "type": "[QueryAnswerResult]"}, - "debug_info": {"key": "@search\\.debug", "type": "DebugInfo"}, - "next_page_parameters": {"key": "@search\\.nextPageParameters", "type": "SearchRequest"}, - "results": {"key": "value", "type": "[SearchResult]"}, - "next_link": {"key": "@odata\\.nextLink", "type": "str"}, - "semantic_partial_response_reason": {"key": "@search\\.semanticPartialResponseReason", "type": "str"}, - "semantic_partial_response_type": {"key": "@search\\.semanticPartialResponseType", "type": "str"}, - "semantic_query_rewrites_result_type": {"key": "@search\\.semanticQueryRewritesResultType", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.count: Optional[int] = None - self.coverage: Optional[float] = None - self.facets: Optional[dict[str, list["_models.FacetResult"]]] = None - self.answers: Optional[list["_models.QueryAnswerResult"]] = None - self.debug_info: Optional["_models.DebugInfo"] = None - self.next_page_parameters: Optional["_models.SearchRequest"] = None - self.results: Optional[list["_models.SearchResult"]] = None - self.next_link: Optional[str] = None - self.semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = None - self.semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = None - self.semantic_query_rewrites_result_type: Optional[Union[str, "_models.SemanticQueryRewritesResultType"]] = None - - -class SearchOptions(_serialization.Model): - """Parameter group. - - :ivar include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :vartype include_total_result_count: bool - :ivar facets: The list of facet expressions to apply to the search query. Each facet expression - contains a field name, optionally followed by a comma-separated list of name:value pairs. - :vartype facets: list[str] - :ivar filter: The OData $filter expression to apply to the search query. - :vartype filter: str - :ivar highlight_fields: The list of field names to use for hit highlights. Only searchable - fields can be used for hit highlighting. - :vartype highlight_fields: list[str] - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :vartype minimum_coverage: float - :ivar order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: list[str] - :ivar query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :vartype query_type: str or ~azure.search.documents.models.QueryType - :ivar scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :vartype scoring_parameters: list[str] - :ivar scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :vartype scoring_profile: str - :ivar search_fields: The list of field names to which to scope the full-text search. When using - fielded search (fieldName:searchExpression) in a full Lucene query, the field names of each - fielded search expression take precedence over any field names listed in this parameter. - :vartype search_fields: list[str] - :ivar search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :vartype search_mode: str or ~azure.search.documents.models.SearchMode - :ivar scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. Known values are: "local", "global", and "global". - :vartype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :ivar session_id: A value to be used to create a sticky session, which can help to get more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :vartype session_id: str - :ivar select: The list of fields to retrieve. If unspecified, all fields marked as retrievable - in the schema are included. - :vartype select: list[str] - :ivar skip: The number of search results to skip. This value cannot be greater than 100,000. If - you need to scan documents in sequence, but cannot use $skip due to this limitation, consider - using $orderby on a totally-ordered key and $filter with a range query instead. - :vartype skip: int - :ivar top: The number of search results to retrieve. This can be used in conjunction with $skip - to implement client-side paging of search results. If results are truncated due to server-side - paging, the response will include a continuation token that can be used to issue another Search - request for the next page of results. - :vartype top: int - :ivar semantic_configuration: The name of the semantic configuration that lists which fields - should be used for semantic ranking, captions, highlights, and answers. - :vartype semantic_configuration: str - :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely, or to return partial results (default). Known values are: "partial" and "fail". - :vartype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :ivar semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :vartype semantic_max_wait_in_milliseconds: int - :ivar answers: This parameter is only valid if the query type is ``semantic``. If set, the - query returns answers extracted from key passages in the highest ranked documents. The number - of answers returned can be configured by appending the pipe character ``|`` followed by the - ``count-`` option after the answers parameter value, such as - ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by - appending the pipe character ``|`` followed by the ``threshold-`` option - after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is - 0.7. The maximum character length of answers can be configured by appending the pipe character - '|' followed by the 'count-\\ :code:``', such as - 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". - :vartype answers: str or ~azure.search.documents.models.QueryAnswerType - :ivar captions: This parameter is only valid if the query type is ``semantic``. If set, the - query returns captions extracted from key passages in the highest ranked documents. When - Captions is set to ``extractive``\\ , highlighting is enabled by default, and can be configured - by appending the pipe character ``|`` followed by the ``highlight-`` option, such - as ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of - captions can be configured by appending the pipe character '|' followed by the 'count-\\ - :code:``', such as 'extractive|maxcharlength-600'. Known - values are: "none" and "extractive". - :vartype captions: str or ~azure.search.documents.models.QueryCaptionType - :ivar semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :vartype semantic_query: str - :ivar query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent - to a generate model which will produce 10 (default) rewrites to help increase the recall of the - request. The requested count can be configured by appending the pipe character ``|`` followed - by the ``count-`` option, such as ``generative|count-3``. Defaults to - ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :ivar debug: Enables a debugging tool that can be used to further explore your search results. - Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and "all". - :vartype debug: str or ~azure.search.documents.models.QueryDebugMode - :ivar query_language: The language of the query. Known values are: "none", "en-us", "en-gb", - "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", - "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", - "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", - "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", - "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", - "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", - "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". - :vartype query_language: str or ~azure.search.documents.models.QueryLanguage - :ivar speller: Improve search recall by spell-correcting individual search query terms. Known - values are: "none" and "lexicon". - :vartype speller: str or ~azure.search.documents.models.QuerySpellerType - :ivar semantic_fields: The list of field names used for semantic ranking. - :vartype semantic_fields: list[str] - """ - - _validation = { - "semantic_max_wait_in_milliseconds": {"minimum": 700}, - } - - _attribute_map = { - "include_total_result_count": {"key": "IncludeTotalResultCount", "type": "bool"}, - "facets": {"key": "Facets", "type": "[str]"}, - "filter": {"key": "$filter", "type": "str"}, - "highlight_fields": {"key": "HighlightFields", "type": "[str]"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "OrderBy", "type": "[str]"}, - "query_type": {"key": "queryType", "type": "str"}, - "scoring_parameters": {"key": "ScoringParameters", "type": "[str]"}, - "scoring_profile": {"key": "scoringProfile", "type": "str"}, - "search_fields": {"key": "searchFields", "type": "[str]"}, - "search_mode": {"key": "searchMode", "type": "str"}, - "scoring_statistics": {"key": "scoringStatistics", "type": "str"}, - "session_id": {"key": "sessionId", "type": "str"}, - "select": {"key": "$select", "type": "[str]"}, - "skip": {"key": "$skip", "type": "int"}, - "top": {"key": "$top", "type": "int"}, - "semantic_configuration": {"key": "semanticConfiguration", "type": "str"}, - "semantic_error_handling": {"key": "semanticErrorHandling", "type": "str"}, - "semantic_max_wait_in_milliseconds": {"key": "semanticMaxWaitInMilliseconds", "type": "int"}, - "answers": {"key": "answers", "type": "str"}, - "captions": {"key": "captions", "type": "str"}, - "semantic_query": {"key": "semanticQuery", "type": "str"}, - "query_rewrites": {"key": "queryRewrites", "type": "str"}, - "debug": {"key": "debug", "type": "str"}, - "query_language": {"key": "queryLanguage", "type": "str"}, - "speller": {"key": "speller", "type": "str"}, - "semantic_fields": {"key": "semanticFields", "type": "[str]"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - include_total_result_count: Optional[bool] = None, - facets: Optional[list[str]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - highlight_fields: Optional[list[str]] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - query_type: Optional[Union[str, "_models.QueryType"]] = None, - scoring_parameters: Optional[list[str]] = None, - scoring_profile: Optional[str] = None, - search_fields: Optional[list[str]] = None, - search_mode: Optional[Union[str, "_models.SearchMode"]] = None, - scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = None, - session_id: Optional[str] = None, - select: Optional[list[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - semantic_configuration: Optional[str] = None, - semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - answers: Optional[Union[str, "_models.QueryAnswerType"]] = None, - captions: Optional[Union[str, "_models.QueryCaptionType"]] = None, - semantic_query: Optional[str] = None, - query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, - debug: Optional[Union[str, "_models.QueryDebugMode"]] = None, - query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, - speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, - semantic_fields: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :paramtype include_total_result_count: bool - :keyword facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :paramtype facets: list[str] - :keyword filter: The OData $filter expression to apply to the search query. - :paramtype filter: str - :keyword highlight_fields: The list of field names to use for hit highlights. Only searchable - fields can be used for hit highlighting. - :paramtype highlight_fields: list[str] - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :paramtype minimum_coverage: float - :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :paramtype order_by: list[str] - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :paramtype scoring_parameters: list[str] - :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :paramtype scoring_profile: str - :keyword search_fields: The list of field names to which to scope the full-text search. When - using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of - each fielded search expression take precedence over any field names listed in this parameter. - :paramtype search_fields: list[str] - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. Known values are: "local", "global", and "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword session_id: A value to be used to create a sticky session, which can help to get more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :paramtype session_id: str - :keyword select: The list of fields to retrieve. If unspecified, all fields marked as - retrievable in the schema are included. - :paramtype select: list[str] - :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use $skip due to this limitation, - consider using $orderby on a totally-ordered key and $filter with a range query instead. - :paramtype skip: int - :keyword top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :paramtype top: int - :keyword semantic_configuration: The name of the semantic configuration that lists which fields - should be used for semantic ranking, captions, highlights, and answers. - :paramtype semantic_configuration: str - :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely, or to return partial results (default). Known values are: "partial" and "fail". - :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount - of time it takes for semantic enrichment to finish processing before the request fails. - :paramtype semantic_max_wait_in_milliseconds: int - :keyword answers: This parameter is only valid if the query type is ``semantic``. If set, the - query returns answers extracted from key passages in the highest ranked documents. The number - of answers returned can be configured by appending the pipe character ``|`` followed by the - ``count-`` option after the answers parameter value, such as - ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by - appending the pipe character ``|`` followed by the ``threshold-`` option - after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is - 0.7. The maximum character length of answers can be configured by appending the pipe character - '|' followed by the 'count-\\ :code:``', such as - 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". - :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType - :keyword captions: This parameter is only valid if the query type is ``semantic``. If set, the - query returns captions extracted from key passages in the highest ranked documents. When - Captions is set to ``extractive``\\ , highlighting is enabled by default, and can be configured - by appending the pipe character ``|`` followed by the ``highlight-`` option, such - as ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of - captions can be configured by appending the pipe character '|' followed by the 'count-\\ - :code:``', such as 'extractive|maxcharlength-600'. Known - values are: "none" and "extractive". - :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType - :keyword semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :paramtype semantic_query: str - :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are - sent to a generate model which will produce 10 (default) rewrites to help increase the recall - of the request. The requested count can be configured by appending the pipe character ``|`` - followed by the ``count-`` option, such as ``generative|count-3``. Defaults - to ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword debug: Enables a debugging tool that can be used to further explore your search - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword query_language: The language of the query. Known values are: "none", "en-us", "en-gb", - "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", - "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", - "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", - "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", - "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", - "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", - "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword speller: Improve search recall by spell-correcting individual search query terms. - Known values are: "none" and "lexicon". - :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword semantic_fields: The list of field names used for semantic ranking. - :paramtype semantic_fields: list[str] - """ - super().__init__(**kwargs) - self.include_total_result_count = include_total_result_count - self.facets = facets - self.filter = filter - self.highlight_fields = highlight_fields - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.query_type = query_type - self.scoring_parameters = scoring_parameters - self.scoring_profile = scoring_profile - self.search_fields = search_fields - self.search_mode = search_mode - self.scoring_statistics = scoring_statistics - self.session_id = session_id - self.select = select - self.skip = skip - self.top = top - self.semantic_configuration = semantic_configuration - self.semantic_error_handling = semantic_error_handling - self.semantic_max_wait_in_milliseconds = semantic_max_wait_in_milliseconds - self.answers = answers - self.captions = captions - self.semantic_query = semantic_query - self.query_rewrites = query_rewrites - self.debug = debug - self.query_language = query_language - self.speller = speller - self.semantic_fields = semantic_fields - - -class SearchRequest(_serialization.Model): - """Parameters for filtering, sorting, faceting, paging, and other search query behaviors. - - :ivar include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :vartype include_total_result_count: bool - :ivar facets: The list of facet expressions to apply to the search query. Each facet expression - contains a field name, optionally followed by a comma-separated list of name:value pairs. - :vartype facets: list[str] - :ivar filter: The OData $filter expression to apply to the search query. - :vartype filter: str - :ivar highlight_fields: The comma-separated list of field names to use for hit highlights. Only - searchable fields can be used for hit highlighting. - :vartype highlight_fields: str - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :vartype minimum_coverage: float - :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: str - :ivar query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :vartype query_type: str or ~azure.search.documents.models.QueryType - :ivar scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. Known - values are: "local", "global", and "global". - :vartype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :ivar session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :vartype session_id: str - :ivar scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :vartype scoring_parameters: list[str] - :ivar scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :vartype scoring_profile: str - :ivar debug: Enables a debugging tool that can be used to further explore your reranked - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". - :vartype debug: str or ~azure.search.documents.models.QueryDebugMode - :ivar search_text: A full-text search query expression; Use "*" or omit this parameter to match - all documents. - :vartype search_text: str - :ivar search_fields: The comma-separated list of field names to which to scope the full-text - search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the - field names of each fielded search expression take precedence over any field names listed in - this parameter. - :vartype search_fields: str - :ivar search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :vartype search_mode: str or ~azure.search.documents.models.SearchMode - :ivar query_language: A value that specifies the language of the search query. Known values - are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", - "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", - "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", - "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", - "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", - "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", - "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", - "te-in", and "ur-pk". - :vartype query_language: str or ~azure.search.documents.models.QueryLanguage - :ivar speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Known values are: "none" and "lexicon". - :vartype speller: str or ~azure.search.documents.models.QuerySpellerType - :ivar select: The comma-separated list of fields to retrieve. If unspecified, all fields marked - as retrievable in the schema are included. - :vartype select: str - :ivar skip: The number of search results to skip. This value cannot be greater than 100,000. If - you need to scan documents in sequence, but cannot use skip due to this limitation, consider - using orderby on a totally-ordered key and filter with a range query instead. - :vartype skip: int - :ivar top: The number of search results to retrieve. This can be used in conjunction with $skip - to implement client-side paging of search results. If results are truncated due to server-side - paging, the response will include a continuation token that can be used to issue another Search - request for the next page of results. - :vartype top: int - :ivar semantic_configuration: The name of a semantic configuration that will be used when - processing documents for queries of type semantic. - :vartype semantic_configuration: str - :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :vartype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :ivar semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :vartype semantic_max_wait_in_milliseconds: int - :ivar semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :vartype semantic_query: str - :ivar answers: A value that specifies whether answers should be returned as part of the search - response. Known values are: "none" and "extractive". - :vartype answers: str or ~azure.search.documents.models.QueryAnswerType - :ivar captions: A value that specifies whether captions should be returned as part of the - search response. Known values are: "none" and "extractive". - :vartype captions: str or ~azure.search.documents.models.QueryCaptionType - :ivar query_rewrites: A value that specifies whether query rewrites should be generated to - augment the search query. Known values are: "none" and "generative". - :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :ivar semantic_fields: The comma-separated list of field names used for semantic ranking. - :vartype semantic_fields: str - :ivar vector_queries: The query parameters for vector and hybrid search queries. - :vartype vector_queries: list[~azure.search.documents.models.VectorQuery] - :ivar vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter' for new indexes. Known values are: - "postFilter", "preFilter", and "strictPostFilter". - :vartype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode - :ivar hybrid_search: The query parameters to configure hybrid search behaviors. - :vartype hybrid_search: ~azure.search.documents.models.HybridSearch - """ - - _validation = { - "semantic_max_wait_in_milliseconds": {"minimum": 700}, - } - - _attribute_map = { - "include_total_result_count": {"key": "count", "type": "bool"}, - "facets": {"key": "facets", "type": "[str]"}, - "filter": {"key": "filter", "type": "str"}, - "highlight_fields": {"key": "highlight", "type": "str"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "orderby", "type": "str"}, - "query_type": {"key": "queryType", "type": "str"}, - "scoring_statistics": {"key": "scoringStatistics", "type": "str"}, - "session_id": {"key": "sessionId", "type": "str"}, - "scoring_parameters": {"key": "scoringParameters", "type": "[str]"}, - "scoring_profile": {"key": "scoringProfile", "type": "str"}, - "debug": {"key": "debug", "type": "str"}, - "search_text": {"key": "search", "type": "str"}, - "search_fields": {"key": "searchFields", "type": "str"}, - "search_mode": {"key": "searchMode", "type": "str"}, - "query_language": {"key": "queryLanguage", "type": "str"}, - "speller": {"key": "speller", "type": "str"}, - "select": {"key": "select", "type": "str"}, - "skip": {"key": "skip", "type": "int"}, - "top": {"key": "top", "type": "int"}, - "semantic_configuration": {"key": "semanticConfiguration", "type": "str"}, - "semantic_error_handling": {"key": "semanticErrorHandling", "type": "str"}, - "semantic_max_wait_in_milliseconds": {"key": "semanticMaxWaitInMilliseconds", "type": "int"}, - "semantic_query": {"key": "semanticQuery", "type": "str"}, - "answers": {"key": "answers", "type": "str"}, - "captions": {"key": "captions", "type": "str"}, - "query_rewrites": {"key": "queryRewrites", "type": "str"}, - "semantic_fields": {"key": "semanticFields", "type": "str"}, - "vector_queries": {"key": "vectorQueries", "type": "[VectorQuery]"}, - "vector_filter_mode": {"key": "vectorFilterMode", "type": "str"}, - "hybrid_search": {"key": "hybridSearch", "type": "HybridSearch"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - include_total_result_count: Optional[bool] = None, - facets: Optional[list[str]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - highlight_fields: Optional[str] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[str] = None, - query_type: Optional[Union[str, "_models.QueryType"]] = None, - scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = None, - session_id: Optional[str] = None, - scoring_parameters: Optional[list[str]] = None, - scoring_profile: Optional[str] = None, - debug: Optional[Union[str, "_models.QueryDebugMode"]] = None, - search_text: Optional[str] = None, - search_fields: Optional[str] = None, - search_mode: Optional[Union[str, "_models.SearchMode"]] = None, - query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, - speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, - select: Optional[str] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - semantic_configuration: Optional[str] = None, - semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - semantic_query: Optional[str] = None, - answers: Optional[Union[str, "_models.QueryAnswerType"]] = None, - captions: Optional[Union[str, "_models.QueryCaptionType"]] = None, - query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, - semantic_fields: Optional[str] = None, - vector_queries: Optional[list["_models.VectorQuery"]] = None, - vector_filter_mode: Optional[Union[str, "_models.VectorFilterMode"]] = None, - hybrid_search: Optional["_models.HybridSearch"] = None, - **kwargs: Any - ) -> None: - """ - :keyword include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :paramtype include_total_result_count: bool - :keyword facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :paramtype facets: list[str] - :keyword filter: The OData $filter expression to apply to the search query. - :paramtype filter: str - :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. - :paramtype highlight_fields: str - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :paramtype order_by: str - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. Known - values are: "local", "global", and "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :paramtype session_id: str - :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :paramtype scoring_parameters: list[str] - :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :paramtype scoring_profile: str - :keyword debug: Enables a debugging tool that can be used to further explore your reranked - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. - :paramtype search_text: str - :keyword search_fields: The comma-separated list of field names to which to scope the full-text - search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the - field names of each fielded search expression take precedence over any field names listed in - this parameter. - :paramtype search_fields: str - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: A value that specifies the language of the search query. Known values - are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", - "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", - "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", - "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", - "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", - "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", - "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", - "te-in", and "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Known values are: "none" and "lexicon". - :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields - marked as retrievable in the schema are included. - :paramtype select: str - :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use skip due to this limitation, consider - using orderby on a totally-ordered key and filter with a range query instead. - :paramtype skip: int - :keyword top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :paramtype top: int - :keyword semantic_configuration: The name of a semantic configuration that will be used when - processing documents for queries of type semantic. - :paramtype semantic_configuration: str - :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount - of time it takes for semantic enrichment to finish processing before the request fails. - :paramtype semantic_max_wait_in_milliseconds: int - :keyword semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :paramtype semantic_query: str - :keyword answers: A value that specifies whether answers should be returned as part of the - search response. Known values are: "none" and "extractive". - :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType - :keyword captions: A value that specifies whether captions should be returned as part of the - search response. Known values are: "none" and "extractive". - :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType - :keyword query_rewrites: A value that specifies whether query rewrites should be generated to - augment the search query. Known values are: "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. - :paramtype semantic_fields: str - :keyword vector_queries: The query parameters for vector and hybrid search queries. - :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter' for new indexes. Known values are: - "postFilter", "preFilter", and "strictPostFilter". - :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - """ - super().__init__(**kwargs) - self.include_total_result_count = include_total_result_count - self.facets = facets - self.filter = filter - self.highlight_fields = highlight_fields - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.query_type = query_type - self.scoring_statistics = scoring_statistics - self.session_id = session_id - self.scoring_parameters = scoring_parameters - self.scoring_profile = scoring_profile - self.debug = debug - self.search_text = search_text - self.search_fields = search_fields - self.search_mode = search_mode - self.query_language = query_language - self.speller = speller - self.select = select - self.skip = skip - self.top = top - self.semantic_configuration = semantic_configuration - self.semantic_error_handling = semantic_error_handling - self.semantic_max_wait_in_milliseconds = semantic_max_wait_in_milliseconds - self.semantic_query = semantic_query - self.answers = answers - self.captions = captions - self.query_rewrites = query_rewrites - self.semantic_fields = semantic_fields - self.vector_queries = vector_queries - self.vector_filter_mode = vector_filter_mode - self.hybrid_search = hybrid_search - - -class SearchResult(_serialization.Model): - """Contains a document found by a search query, plus associated metadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar score: The relevance score of the document compared to other documents returned by the - query. Required. - :vartype score: float - :ivar reranker_score: The relevance score computed by the semantic ranker for the top search - results. Search results are sorted by the RerankerScore first and then by the Score. - RerankerScore is only returned for queries of type 'semantic'. - :vartype reranker_score: float - :ivar reranker_boosted_score: The relevance score computed by boosting the Reranker Score. - Search results are sorted by the RerankerScore/RerankerBoostedScore based on - useScoringProfileBoostedRanking in the Semantic Config. RerankerBoostedScore is only returned - for queries of type 'semantic'. - :vartype reranker_boosted_score: float - :ivar highlights: Text fragments from the document that indicate the matching search terms, - organized by each applicable field; null if hit highlighting was not enabled for the query. - :vartype highlights: dict[str, list[str]] - :ivar captions: Captions are the most representative passages from the document relatively to - the search query. They are often used as document summary. Captions are only returned for - queries of type 'semantic'. - :vartype captions: list[~azure.search.documents.models.QueryCaptionResult] - :ivar document_debug_info: Contains debugging information that can be used to further explore - your search results. - :vartype document_debug_info: ~azure.search.documents.models.DocumentDebugInfo - """ - - _validation = { - "score": {"required": True, "readonly": True}, - "reranker_score": {"readonly": True}, - "reranker_boosted_score": {"readonly": True}, - "highlights": {"readonly": True}, - "captions": {"readonly": True}, - "document_debug_info": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "score": {"key": "@search\\.score", "type": "float"}, - "reranker_score": {"key": "@search\\.rerankerScore", "type": "float"}, - "reranker_boosted_score": {"key": "@search\\.rerankerBoostedScore", "type": "float"}, - "highlights": {"key": "@search\\.highlights", "type": "{[str]}"}, - "captions": {"key": "@search\\.captions", "type": "[QueryCaptionResult]"}, - "document_debug_info": {"key": "@search\\.documentDebugInfo", "type": "DocumentDebugInfo"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.score: Optional[float] = None - self.reranker_score: Optional[float] = None - self.reranker_boosted_score: Optional[float] = None - self.highlights: Optional[dict[str, list[str]]] = None - self.captions: Optional[list["_models.QueryCaptionResult"]] = None - self.document_debug_info: Optional["_models.DocumentDebugInfo"] = None - - -class VectorThreshold(_serialization.Model): - """The threshold used for vector queries. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - SearchScoreThreshold, VectorSimilarityThreshold - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of threshold used to filter vector queries. Required. Known values are: - "vectorSimilarity" and "searchScore". - :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = {"kind": {"searchScore": "SearchScoreThreshold", "vectorSimilarity": "VectorSimilarityThreshold"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class SearchScoreThreshold(VectorThreshold): - """The results of the vector query will filter based on the '@search.score' value. Note this is - the @search.score returned as part of the search response. The threshold direction will be - chosen for higher @search.score. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of threshold used to filter vector queries. Required. Known values are: - "vectorSimilarity" and "searchScore". - :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind - :ivar value: The threshold will filter based on the '@search.score' value. Note this is the - @search.score returned as part of the search response. The threshold direction will be chosen - for higher @search.score. Required. - :vartype value: float - """ - - _validation = { - "kind": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, *, value: float, **kwargs: Any) -> None: - """ - :keyword value: The threshold will filter based on the '@search.score' value. Note this is the - @search.score returned as part of the search response. The threshold direction will be chosen - for higher @search.score. Required. - :paramtype value: float - """ - super().__init__(**kwargs) - self.kind: str = "searchScore" - self.value = value - - -class SemanticDebugInfo(_serialization.Model): - """SemanticDebugInfo. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar title_field: The title field that was sent to the semantic enrichment process, as well as - how it was used. - :vartype title_field: ~azure.search.documents.models.QueryResultDocumentSemanticField - :ivar content_fields: The content fields that were sent to the semantic enrichment process, as - well as how they were used. - :vartype content_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] - :ivar keyword_fields: The keyword fields that were sent to the semantic enrichment process, as - well as how they were used. - :vartype keyword_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] - :ivar reranker_input: The raw concatenated strings that were sent to the semantic enrichment - process. - :vartype reranker_input: ~azure.search.documents.models.QueryResultDocumentRerankerInput - """ - - _validation = { - "title_field": {"readonly": True}, - "content_fields": {"readonly": True}, - "keyword_fields": {"readonly": True}, - "reranker_input": {"readonly": True}, - } - - _attribute_map = { - "title_field": {"key": "titleField", "type": "QueryResultDocumentSemanticField"}, - "content_fields": {"key": "contentFields", "type": "[QueryResultDocumentSemanticField]"}, - "keyword_fields": {"key": "keywordFields", "type": "[QueryResultDocumentSemanticField]"}, - "reranker_input": {"key": "rerankerInput", "type": "QueryResultDocumentRerankerInput"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.title_field: Optional["_models.QueryResultDocumentSemanticField"] = None - self.content_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = None - self.keyword_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = None - self.reranker_input: Optional["_models.QueryResultDocumentRerankerInput"] = None - - -class SingleVectorFieldResult(_serialization.Model): - """A single vector field result. Both @search.score and vector similarity values are returned. - Vector similarity is related to @search.score by an equation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar search_score: The @search.score value that is calculated from the vector similarity - score. This is the score that's visible in a pure single-field single-vector query. - :vartype search_score: float - :ivar vector_similarity: The vector similarity score for this document. Note this is the - canonical definition of similarity metric, not the 'distance' version. For example, cosine - similarity instead of cosine distance. - :vartype vector_similarity: float - """ - - _validation = { - "search_score": {"readonly": True}, - "vector_similarity": {"readonly": True}, - } - - _attribute_map = { - "search_score": {"key": "searchScore", "type": "float"}, - "vector_similarity": {"key": "vectorSimilarity", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.search_score: Optional[float] = None - self.vector_similarity: Optional[float] = None - - -class SuggestDocumentsResult(_serialization.Model): - """Response containing suggestion query results from an index. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar results: The sequence of results returned by the query. Required. - :vartype results: list[~azure.search.documents.models.SuggestResult] - :ivar coverage: A value indicating the percentage of the index that was included in the query, - or null if minimumCoverage was not set in the request. - :vartype coverage: float - """ - - _validation = { - "results": {"required": True, "readonly": True}, - "coverage": {"readonly": True}, - } - - _attribute_map = { - "results": {"key": "value", "type": "[SuggestResult]"}, - "coverage": {"key": "@search\\.coverage", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.results: Optional[list["_models.SuggestResult"]] = None - self.coverage: Optional[float] = None - - -class SuggestOptions(_serialization.Model): - """Parameter group. - - :ivar filter: An OData expression that filters the documents considered for suggestions. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestions - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestions queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestions query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :vartype order_by: list[str] - :ivar search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :vartype search_fields: list[str] - :ivar select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :vartype select: list[str] - :ivar top: The number of suggestions to retrieve. The value must be a number between 1 and 100. - The default is 5. - :vartype top: int - """ - - _attribute_map = { - "filter": {"key": "$filter", "type": "str"}, - "use_fuzzy_matching": {"key": "UseFuzzyMatching", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "OrderBy", "type": "[str]"}, - "search_fields": {"key": "searchFields", "type": "[str]"}, - "select": {"key": "$select", "type": "[str]"}, - "top": {"key": "$top", "type": "int"}, - } - - def __init__( - self, - *, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - search_fields: Optional[list[str]] = None, - select: Optional[list[str]] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword filter: An OData expression that filters the documents considered for suggestions. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - suggestions query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy suggestions queries are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a suggestions query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :paramtype minimum_coverage: float - :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :paramtype order_by: list[str] - :keyword search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :paramtype search_fields: list[str] - :keyword select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :paramtype select: list[str] - :keyword top: The number of suggestions to retrieve. The value must be a number between 1 and - 100. The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.search_fields = search_fields - self.select = select - self.top = top - - -class SuggestRequest(_serialization.Model): - """Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors. - - All required parameters must be populated in order to send to server. - - :ivar filter: An OData expression that filters the documents considered for suggestions. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestion - query. Default is false. When set to true, the query will find suggestions even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestion searches are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestion query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: str - :ivar search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :vartype search_text: str - :ivar search_fields: The comma-separated list of field names to search for the specified search - text. Target fields must be included in the specified suggester. - :vartype search_fields: str - :ivar select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. - :vartype select: str - :ivar suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :vartype suggester_name: str - :ivar top: The number of suggestions to retrieve. This must be a value between 1 and 100. The - default is 5. - :vartype top: int - """ - - _validation = { - "search_text": {"required": True}, - "suggester_name": {"required": True}, - } - - _attribute_map = { - "filter": {"key": "filter", "type": "str"}, - "use_fuzzy_matching": {"key": "fuzzy", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "orderby", "type": "str"}, - "search_text": {"key": "search", "type": "str"}, - "search_fields": {"key": "searchFields", "type": "str"}, - "select": {"key": "select", "type": "str"}, - "suggester_name": {"key": "suggesterName", "type": "str"}, - "top": {"key": "top", "type": "int"}, - } - - def __init__( - self, - *, - search_text: str, - suggester_name: str, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[str] = None, - search_fields: Optional[str] = None, - select: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword filter: An OData expression that filters the documents considered for suggestions. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - suggestion query. Default is false. When set to true, the query will find suggestions even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a suggestion query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :paramtype order_by: str - :keyword search_text: The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. Required. - :paramtype search_text: str - :keyword search_fields: The comma-separated list of field names to search for the specified - search text. Target fields must be included in the specified suggester. - :paramtype search_fields: str - :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. - :paramtype select: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. - The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.search_text = search_text - self.search_fields = search_fields - self.select = select - self.suggester_name = suggester_name - self.top = top - - -class SuggestResult(_serialization.Model): - """A result containing a document found by a suggestion query, plus associated metadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar text: The text of the suggestion result. Required. - :vartype text: str - """ - - _validation = { - "text": {"required": True, "readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "text": {"key": "@search\\.text", "type": "str"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.text: Optional[str] = None - - -class TextResult(_serialization.Model): - """The BM25 or Classic score for the text portion of the query. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar search_score: The BM25 or Classic score for the text portion of the query. - :vartype search_score: float - """ - - _validation = { - "search_score": {"readonly": True}, - } - - _attribute_map = { - "search_score": {"key": "searchScore", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.search_score: Optional[float] = None - - -class VectorQuery(_serialization.Model): - """The query parameters for vector and hybrid search queries. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - VectorizableImageBinaryQuery, VectorizableImageUrlQuery, VectorizableTextQuery, VectorizedQuery - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k: Number of nearest neighbors to return as top hits. - :vartype k: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - } - - _subtype_map = { - "kind": { - "imageBinary": "VectorizableImageBinaryQuery", - "imageUrl": "VectorizableImageUrlQuery", - "text": "VectorizableTextQuery", - "vector": "VectorizedQuery", - } - } - - def __init__( - self, - *, - k: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword k: Number of nearest neighbors to return as top hits. - :paramtype k: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - self.k = k - self.fields = fields - self.exhaustive = exhaustive - self.oversampling = oversampling - self.weight = weight - self.threshold = threshold - self.filter_override = filter_override - self.per_document_vector_limit = per_document_vector_limit - - -class VectorizableImageBinaryQuery(VectorQuery): - """The query parameters to use for vector search when a base 64 encoded binary of an image that - needs to be vectorized is provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k: Number of nearest neighbors to return as top hits. - :vartype k: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar base64_image: The base 64 encoded binary of an image to be vectorized to perform a vector - search query. - :vartype base64_image: str - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "base64_image": {"key": "base64Image", "type": "str"}, - } - - def __init__( - self, - *, - k: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - base64_image: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword k: Number of nearest neighbors to return as top hits. - :paramtype k: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword base64_image: The base 64 encoded binary of an image to be vectorized to perform a - vector search query. - :paramtype base64_image: str - """ - super().__init__( - k=k, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "imageBinary" - self.base64_image = base64_image - - -class VectorizableImageUrlQuery(VectorQuery): - """The query parameters to use for vector search when an url that represents an image value that - needs to be vectorized is provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k: Number of nearest neighbors to return as top hits. - :vartype k: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar url: The URL of an image to be vectorized to perform a vector search query. - :vartype url: str - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "url": {"key": "url", "type": "str"}, - } - - def __init__( - self, - *, - k: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - url: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword k: Number of nearest neighbors to return as top hits. - :paramtype k: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword url: The URL of an image to be vectorized to perform a vector search query. - :paramtype url: str - """ - super().__init__( - k=k, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "imageUrl" - self.url = url - - -class VectorizableTextQuery(VectorQuery): - """The query parameters to use for vector search when a text value that needs to be vectorized is - provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k: Number of nearest neighbors to return as top hits. - :vartype k: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar text: The text to be vectorized to perform a vector search query. Required. - :vartype text: str - :ivar query_rewrites: Can be configured to let a generative model rewrite the query before - sending it to be vectorized. Known values are: "none" and "generative". - :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - """ - - _validation = { - "kind": {"required": True}, - "text": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "text": {"key": "text", "type": "str"}, - "query_rewrites": {"key": "queryRewrites", "type": "str"}, - } - - def __init__( - self, - *, - text: str, - k: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword k: Number of nearest neighbors to return as top hits. - :paramtype k: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword text: The text to be vectorized to perform a vector search query. Required. - :paramtype text: str - :keyword query_rewrites: Can be configured to let a generative model rewrite the query before - sending it to be vectorized. Known values are: "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - """ - super().__init__( - k=k, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "text" - self.text = text - self.query_rewrites = query_rewrites - - -class VectorizedQuery(VectorQuery): - """The query parameters to use for vector search when a raw vector value is provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k: Number of nearest neighbors to return as top hits. - :vartype k: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar vector: The vector representation of a search query. Required. - :vartype vector: list[float] - """ - - _validation = { - "kind": {"required": True}, - "vector": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "vector": {"key": "vector", "type": "[float]"}, - } - - def __init__( - self, - *, - vector: list[float], - k: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword k: Number of nearest neighbors to return as top hits. - :paramtype k: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword vector: The vector representation of a search query. Required. - :paramtype vector: list[float] - """ - super().__init__( - k=k, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "vector" - self.vector = vector - - -class VectorsDebugInfo(_serialization.Model): - """VectorsDebugInfo. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar subscores: The breakdown of subscores of the document prior to the chosen result set - fusion/combination method such as RRF. - :vartype subscores: ~azure.search.documents.models.QueryResultDocumentSubscores - """ - - _validation = { - "subscores": {"readonly": True}, - } - - _attribute_map = { - "subscores": {"key": "subscores", "type": "QueryResultDocumentSubscores"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.subscores: Optional["_models.QueryResultDocumentSubscores"] = None - - -class VectorSimilarityThreshold(VectorThreshold): - """The results of the vector query will be filtered based on the vector similarity metric. Note - this is the canonical definition of similarity metric, not the 'distance' version. The - threshold direction (larger or smaller) will be chosen automatically according to the metric - used by the field. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of threshold used to filter vector queries. Required. Known values are: - "vectorSimilarity" and "searchScore". - :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind - :ivar value: The threshold will filter based on the similarity metric value. Note this is the - canonical definition of similarity metric, not the 'distance' version. The threshold direction - (larger or smaller) will be chosen automatically according to the metric used by the field. - Required. - :vartype value: float - """ - - _validation = { - "kind": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, *, value: float, **kwargs: Any) -> None: - """ - :keyword value: The threshold will filter based on the similarity metric value. Note this is - the canonical definition of similarity metric, not the 'distance' version. The threshold - direction (larger or smaller) will be chosen automatically according to the metric used by the - field. Required. - :paramtype value: float - """ - super().__init__(**kwargs) - self.kind: str = "vectorSimilarity" - self.value = value diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py deleted file mode 100644 index 75b753900867..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py +++ /dev/null @@ -1,1585 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchIndexClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_count_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/$count") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_search_get_request( - *, - search_text: Optional[str] = None, - include_total_result_count: Optional[bool] = None, - facets: Optional[list[str]] = None, - filter: Optional[str] = None, - highlight_fields: Optional[list[str]] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - query_type: Optional[Union[str, _models.QueryType]] = None, - scoring_parameters: Optional[list[str]] = None, - scoring_profile: Optional[str] = None, - search_fields: Optional[list[str]] = None, - search_mode: Optional[Union[str, _models.SearchMode]] = None, - scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, - session_id: Optional[str] = None, - select: Optional[list[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - x_ms_client_request_id: Optional[str] = None, - semantic_configuration: Optional[str] = None, - semantic_error_handling: Optional[Union[str, _models.SemanticErrorMode]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - answers: Optional[Union[str, _models.QueryAnswerType]] = None, - captions: Optional[Union[str, _models.QueryCaptionType]] = None, - semantic_query: Optional[str] = None, - query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, - debug: Optional[Union[str, _models.QueryDebugMode]] = None, - query_language: Optional[Union[str, _models.QueryLanguage]] = None, - speller: Optional[Union[str, _models.QuerySpellerType]] = None, - semantic_fields: Optional[list[str]] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs") - - # Construct parameters - if search_text is not None: - _params["search"] = _SERIALIZER.query("search_text", search_text, "str") - if include_total_result_count is not None: - _params["$count"] = _SERIALIZER.query("include_total_result_count", include_total_result_count, "bool") - if facets is not None: - _params["facet"] = [_SERIALIZER.query("facets", q, "str") if q is not None else "" for q in facets] - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if highlight_fields is not None: - _params["highlight"] = _SERIALIZER.query("highlight_fields", highlight_fields, "[str]", div=",") - if highlight_post_tag is not None: - _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") - if highlight_pre_tag is not None: - _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") - if minimum_coverage is not None: - _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") - if order_by is not None: - _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") - if query_type is not None: - _params["queryType"] = _SERIALIZER.query("query_type", query_type, "str") - if scoring_parameters is not None: - _params["scoringParameter"] = [ - _SERIALIZER.query("scoring_parameters", q, "str") if q is not None else "" for q in scoring_parameters - ] - if scoring_profile is not None: - _params["scoringProfile"] = _SERIALIZER.query("scoring_profile", scoring_profile, "str") - if search_fields is not None: - _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") - if search_mode is not None: - _params["searchMode"] = _SERIALIZER.query("search_mode", search_mode, "str") - if scoring_statistics is not None: - _params["scoringStatistics"] = _SERIALIZER.query("scoring_statistics", scoring_statistics, "str") - if session_id is not None: - _params["sessionId"] = _SERIALIZER.query("session_id", session_id, "str") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") - if skip is not None: - _params["$skip"] = _SERIALIZER.query("skip", skip, "int") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if semantic_configuration is not None: - _params["semanticConfiguration"] = _SERIALIZER.query("semantic_configuration", semantic_configuration, "str") - if semantic_error_handling is not None: - _params["semanticErrorHandling"] = _SERIALIZER.query("semantic_error_handling", semantic_error_handling, "str") - if semantic_max_wait_in_milliseconds is not None: - _params["semanticMaxWaitInMilliseconds"] = _SERIALIZER.query( - "semantic_max_wait_in_milliseconds", semantic_max_wait_in_milliseconds, "int", minimum=700 - ) - if answers is not None: - _params["answers"] = _SERIALIZER.query("answers", answers, "str") - if captions is not None: - _params["captions"] = _SERIALIZER.query("captions", captions, "str") - if semantic_query is not None: - _params["semanticQuery"] = _SERIALIZER.query("semantic_query", semantic_query, "str") - if query_rewrites is not None: - _params["queryRewrites"] = _SERIALIZER.query("query_rewrites", query_rewrites, "str") - if debug is not None: - _params["debug"] = _SERIALIZER.query("debug", debug, "str") - if query_language is not None: - _params["queryLanguage"] = _SERIALIZER.query("query_language", query_language, "str") - if speller is not None: - _params["speller"] = _SERIALIZER.query("speller", speller, "str") - if semantic_fields is not None: - _params["semanticFields"] = _SERIALIZER.query("semantic_fields", semantic_fields, "[str]", div=",") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - if x_ms_enable_elevated_read is not None: - _headers["x-ms-enable-elevated-read"] = _SERIALIZER.header( - "x_ms_enable_elevated_read", x_ms_enable_elevated_read, "bool" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_search_post_request( - *, - x_ms_client_request_id: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.post.search") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - if x_ms_enable_elevated_read is not None: - _headers["x-ms-enable-elevated-read"] = _SERIALIZER.header( - "x_ms_enable_elevated_read", x_ms_enable_elevated_read, "bool" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - key: str, - *, - selected_fields: Optional[list[str]] = None, - x_ms_client_request_id: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs('{key}')") - path_format_arguments = { - "key": _SERIALIZER.url("key", key, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if selected_fields is not None: - _params["$select"] = _SERIALIZER.query("selected_fields", selected_fields, "[str]", div=",") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - if x_ms_enable_elevated_read is not None: - _headers["x-ms-enable-elevated-read"] = _SERIALIZER.header( - "x_ms_enable_elevated_read", x_ms_enable_elevated_read, "bool" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_suggest_get_request( - *, - search_text: str, - suggester_name: str, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - search_fields: Optional[list[str]] = None, - select: Optional[list[str]] = None, - top: Optional[int] = None, - x_ms_client_request_id: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.suggest") - - # Construct parameters - _params["search"] = _SERIALIZER.query("search_text", search_text, "str") - _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if use_fuzzy_matching is not None: - _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") - if highlight_post_tag is not None: - _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") - if highlight_pre_tag is not None: - _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") - if minimum_coverage is not None: - _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") - if order_by is not None: - _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") - if search_fields is not None: - _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_suggest_post_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.post.suggest") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_index_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.index") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_autocomplete_get_request( - *, - search_text: str, - suggester_name: str, - x_ms_client_request_id: Optional[str] = None, - autocomplete_mode: Optional[Union[str, _models.AutocompleteMode]] = None, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[list[str]] = None, - top: Optional[int] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.autocomplete") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["search"] = _SERIALIZER.query("search_text", search_text, "str") - _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") - if autocomplete_mode is not None: - _params["autocompleteMode"] = _SERIALIZER.query("autocomplete_mode", autocomplete_mode, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if use_fuzzy_matching is not None: - _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") - if highlight_post_tag is not None: - _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") - if highlight_pre_tag is not None: - _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") - if minimum_coverage is not None: - _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") - if search_fields is not None: - _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_autocomplete_post_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.post.autocomplete") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class DocumentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`documents` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def count(self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any) -> int: - """Queries the number of documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Count-Documents - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: int or the result of cls(response) - :rtype: int - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[int] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_count_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("int", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def search_get( - self, - search_text: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - search_options: Optional[_models.SearchOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. Default value is None. - :type search_text: str - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param search_options: Parameter group. Default value is None. - :type search_options: ~azure.search.documents.models.SearchOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _include_total_result_count = None - _facets = None - _filter = None - _highlight_fields = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _query_type = None - _scoring_parameters = None - _scoring_profile = None - _search_fields = None - _search_mode = None - _scoring_statistics = None - _session_id = None - _select = None - _skip = None - _top = None - _x_ms_client_request_id = None - _semantic_configuration = None - _semantic_error_handling = None - _semantic_max_wait_in_milliseconds = None - _answers = None - _captions = None - _semantic_query = None - _query_rewrites = None - _debug = None - _query_language = None - _speller = None - _semantic_fields = None - if search_options is not None: - _answers = search_options.answers - _captions = search_options.captions - _debug = search_options.debug - _facets = search_options.facets - _filter = search_options.filter - _highlight_fields = search_options.highlight_fields - _highlight_post_tag = search_options.highlight_post_tag - _highlight_pre_tag = search_options.highlight_pre_tag - _include_total_result_count = search_options.include_total_result_count - _minimum_coverage = search_options.minimum_coverage - _order_by = search_options.order_by - _query_language = search_options.query_language - _query_rewrites = search_options.query_rewrites - _query_type = search_options.query_type - _scoring_parameters = search_options.scoring_parameters - _scoring_profile = search_options.scoring_profile - _scoring_statistics = search_options.scoring_statistics - _search_fields = search_options.search_fields - _search_mode = search_options.search_mode - _select = search_options.select - _semantic_configuration = search_options.semantic_configuration - _semantic_error_handling = search_options.semantic_error_handling - _semantic_fields = search_options.semantic_fields - _semantic_max_wait_in_milliseconds = search_options.semantic_max_wait_in_milliseconds - _semantic_query = search_options.semantic_query - _session_id = search_options.session_id - _skip = search_options.skip - _speller = search_options.speller - _top = search_options.top - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_search_get_request( - search_text=search_text, - include_total_result_count=_include_total_result_count, - facets=_facets, - filter=_filter, - highlight_fields=_highlight_fields, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - query_type=_query_type, - scoring_parameters=_scoring_parameters, - scoring_profile=_scoring_profile, - search_fields=_search_fields, - search_mode=_search_mode, - scoring_statistics=_scoring_statistics, - session_id=_session_id, - select=_select, - skip=_skip, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - semantic_configuration=_semantic_configuration, - semantic_error_handling=_semantic_error_handling, - semantic_max_wait_in_milliseconds=_semantic_max_wait_in_milliseconds, - answers=_answers, - captions=_captions, - semantic_query=_semantic_query, - query_rewrites=_query_rewrites, - debug=_debug, - query_language=_query_language, - speller=_speller, - semantic_fields=_semantic_fields, - x_ms_query_source_authorization=x_ms_query_source_authorization, - x_ms_enable_elevated_read=x_ms_enable_elevated_read, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def search_post( - self, - search_request: _models.SearchRequest, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: ~azure.search.documents.models.SearchRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def search_post( - self, - search_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def search_post( - self, - search_request: Union[_models.SearchRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Is either a SearchRequest type or - a IO[bytes] type. Required. - :type search_request: ~azure.search.documents.models.SearchRequest or IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(search_request, (IOBase, bytes)): - _content = search_request - else: - _json = self._serialize.body(search_request, "SearchRequest") - - _request = build_search_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - x_ms_enable_elevated_read=x_ms_enable_elevated_read, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get( - self, - key: str, - selected_fields: Optional[list[str]] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> dict[str, Any]: - """Retrieves a document from the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/lookup-document - - :param key: The key of the document to retrieve. Required. - :type key: str - :param selected_fields: List of field names to retrieve for the document; Any field not - retrieved will be missing from the returned document. Default value is None. - :type selected_fields: list[str] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :type x_ms_enable_elevated_read: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: dict mapping str to any or the result of cls(response) - :rtype: dict[str, any] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[dict[str, Any]] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - key=key, - selected_fields=selected_fields, - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - x_ms_enable_elevated_read=x_ms_enable_elevated_read, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("{object}", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def suggest_get( - self, - search_text: str, - suggester_name: str, - suggest_options: Optional[_models.SuggestOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param suggest_options: Parameter group. Default value is None. - :type suggest_options: ~azure.search.documents.models.SuggestOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _search_fields = None - _select = None - _top = None - _x_ms_client_request_id = None - if suggest_options is not None: - _filter = suggest_options.filter - _highlight_post_tag = suggest_options.highlight_post_tag - _highlight_pre_tag = suggest_options.highlight_pre_tag - _minimum_coverage = suggest_options.minimum_coverage - _order_by = suggest_options.order_by - _search_fields = suggest_options.search_fields - _select = suggest_options.select - _top = suggest_options.top - _use_fuzzy_matching = suggest_options.use_fuzzy_matching - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_suggest_get_request( - search_text=search_text, - suggester_name=suggester_name, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - search_fields=_search_fields, - select=_select, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def suggest_post( - self, - suggest_request: _models.SuggestRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def suggest_post( - self, - suggest_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def suggest_post( - self, - suggest_request: Union[_models.SuggestRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Is either a SuggestRequest type or a IO[bytes] - type. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(suggest_request, (IOBase, bytes)): - _content = suggest_request - else: - _json = self._serialize.body(suggest_request, "SuggestRequest") - - _request = build_suggest_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def index( - self, - batch: _models.IndexBatch, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexBatch - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def index( - self, - batch: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def index( - self, - batch: Union[_models.IndexBatch, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Is either a IndexBatch type or a IO[bytes] type. - Required. - :type batch: ~azure.search.documents.models.IndexBatch or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.IndexDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(batch, (IOBase, bytes)): - _content = batch - else: - _json = self._serialize.body(batch, "IndexBatch") - - _request = build_index_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 207]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("IndexDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def autocomplete_get( - self, - search_text: str, - suggester_name: str, - request_options: Optional[_models.RequestOptions] = None, - autocomplete_options: Optional[_models.AutocompleteOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param search_text: The incomplete term which should be auto-completed. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :param autocomplete_options: Parameter group. Default value is None. - :type autocomplete_options: ~azure.search.documents.models.AutocompleteOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - _autocomplete_mode = None - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _search_fields = None - _top = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - if autocomplete_options is not None: - _autocomplete_mode = autocomplete_options.autocomplete_mode - _filter = autocomplete_options.filter - _highlight_post_tag = autocomplete_options.highlight_post_tag - _highlight_pre_tag = autocomplete_options.highlight_pre_tag - _minimum_coverage = autocomplete_options.minimum_coverage - _search_fields = autocomplete_options.search_fields - _top = autocomplete_options.top - _use_fuzzy_matching = autocomplete_options.use_fuzzy_matching - - _request = build_autocomplete_get_request( - search_text=search_text, - suggester_name=suggester_name, - x_ms_client_request_id=_x_ms_client_request_id, - autocomplete_mode=_autocomplete_mode, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - search_fields=_search_fields, - top=_top, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def autocomplete_post( - self, - autocomplete_request: _models.AutocompleteRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def autocomplete_post( - self, - autocomplete_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def autocomplete_post( - self, - autocomplete_request: Union[_models.AutocompleteRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Is either a - AutocompleteRequest type or a IO[bytes] type. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(autocomplete_request, (IOBase, bytes)): - _content = autocomplete_request - else: - _json = self._serialize.body(autocomplete_request, "AutocompleteRequest") - - _request = build_autocomplete_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed b/sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py b/sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py deleted file mode 100644 index e57206ead1ad..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py +++ /dev/null @@ -1,21 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from typing import Optional, Dict, Any, MutableMapping - - -class HeadersMixin: - @property - def _headers(self) -> Dict[str, Any]: - if self._aad: # type: ignore - return {"Accept": self._ODATA_ACCEPT} # type: ignore - return {"api-key": self._credential.key, "Accept": self._ODATA_ACCEPT} # type: ignore - - def _merge_client_headers(self, headers: Optional[MutableMapping[str, str]]) -> MutableMapping[str, str]: - headers = headers or {} - combined = self._headers - combined.update(headers) - return combined diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/__init__.py similarity index 65% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_operations/__init__.py index 749e5a6ba198..3d57eee2949f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._documents_operations import DocumentsOperations # type: ignore +from ._operations import _SearchClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "DocumentsOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py new file mode 100644 index 000000000000..b2a620ff97e0 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -0,0 +1,1973 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1 +from .._configuration import SearchClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC + +JSON = MutableMapping[str, Any] +_Unset: Any = object() +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_search_get_document_count_request(index_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/$count" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_search_get_request( # pylint: disable=too-many-locals,too-many-statements,too-many-branches + index_name: str, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + search_text: Optional[str] = None, + include_total_result_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + semantic_query: Optional[str] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + semantic_fields: Optional[list[str]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if search_text is not None: + _params["search"] = _SERIALIZER.query("search_text", search_text, "str") + if include_total_result_count is not None: + _params["$count"] = _SERIALIZER.query("include_total_result_count", include_total_result_count, "bool") + if facets is not None: + _params["facet"] = [_SERIALIZER.query("facets", q, "str") if q is not None else "" for q in facets] + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if highlight_fields is not None: + _params["highlight"] = _SERIALIZER.query("highlight_fields", highlight_fields, "[str]", div=",") + if highlight_post_tag is not None: + _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") + if highlight_pre_tag is not None: + _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") + if minimum_coverage is not None: + _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") + if query_type is not None: + _params["queryType"] = _SERIALIZER.query("query_type", query_type, "str") + if scoring_parameters is not None: + _params["scoringParameter"] = [ + _SERIALIZER.query("scoring_parameters", q, "str") if q is not None else "" for q in scoring_parameters + ] + if scoring_profile is not None: + _params["scoringProfile"] = _SERIALIZER.query("scoring_profile", scoring_profile, "str") + if search_fields is not None: + _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") + if search_mode is not None: + _params["searchMode"] = _SERIALIZER.query("search_mode", search_mode, "str") + if scoring_statistics is not None: + _params["scoringStatistics"] = _SERIALIZER.query("scoring_statistics", scoring_statistics, "str") + if session_id is not None: + _params["sessionId"] = _SERIALIZER.query("session_id", session_id, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + if skip is not None: + _params["$skip"] = _SERIALIZER.query("skip", skip, "int") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if semantic_configuration is not None: + _params["semanticConfiguration"] = _SERIALIZER.query("semantic_configuration", semantic_configuration, "str") + if semantic_error_handling is not None: + _params["semanticErrorHandling"] = _SERIALIZER.query("semantic_error_handling", semantic_error_handling, "str") + if semantic_max_wait_in_milliseconds is not None: + _params["semanticMaxWaitInMilliseconds"] = _SERIALIZER.query( + "semantic_max_wait_in_milliseconds", semantic_max_wait_in_milliseconds, "int" + ) + if answers is not None: + _params["answers"] = _SERIALIZER.query("answers", answers, "str") + if captions is not None: + _params["captions"] = _SERIALIZER.query("captions", captions, "str") + if semantic_query is not None: + _params["semanticQuery"] = _SERIALIZER.query("semantic_query", semantic_query, "str") + if query_rewrites is not None: + _params["queryRewrites"] = _SERIALIZER.query("query_rewrites", query_rewrites, "str") + if debug is not None: + _params["debug"] = _SERIALIZER.query("debug", debug, "str") + if query_language is not None: + _params["queryLanguage"] = _SERIALIZER.query("query_language", query_language, "str") + if speller is not None: + _params["speller"] = _SERIALIZER.query("speller", speller, "str") + if semantic_fields is not None: + _params["semanticFields"] = _SERIALIZER.query("semantic_fields", semantic_fields, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if enable_elevated_read is not None: + _headers["x-ms-enable-elevated-read"] = _SERIALIZER.header("enable_elevated_read", enable_elevated_read, "bool") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_search_post_request( + index_name: str, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.post.search" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if enable_elevated_read is not None: + _headers["x-ms-enable-elevated-read"] = _SERIALIZER.header("enable_elevated_read", enable_elevated_read, "bool") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_get_document_request( + key: str, + index_name: str, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + selected_fields: Optional[list[str]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs('{key}')" + path_format_arguments = { + "key": _SERIALIZER.url("key", key, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if selected_fields is not None: + _params["$select"] = _SERIALIZER.query("selected_fields", selected_fields, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if enable_elevated_read is not None: + _headers["x-ms-enable-elevated-read"] = _SERIALIZER.header("enable_elevated_read", enable_elevated_read, "bool") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_suggest_get_request( + index_name: str, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.suggest" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["search"] = _SERIALIZER.query("search_text", search_text, "str") + _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if use_fuzzy_matching is not None: + _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") + if highlight_post_tag is not None: + _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") + if highlight_pre_tag is not None: + _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") + if minimum_coverage is not None: + _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") + if search_fields is not None: + _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_suggest_post_request(index_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.post.suggest" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_request(index_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.index" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_autocomplete_get_request( + index_name: str, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.autocomplete" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["search"] = _SERIALIZER.query("search_text", search_text, "str") + _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") + if autocomplete_mode is not None: + _params["autocompleteMode"] = _SERIALIZER.query("autocomplete_mode", autocomplete_mode, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if use_fuzzy_matching is not None: + _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") + if highlight_post_tag is not None: + _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") + if highlight_pre_tag is not None: + _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") + if minimum_coverage is not None: + _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") + if search_fields is not None: + _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_autocomplete_post_request(index_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=none") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.post.autocomplete" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class _SearchClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchClientConfiguration] +): + + @distributed_trace + def get_document_count(self, **kwargs: Any) -> int: + """Queries the number of documents in the index. + + :return: int + :rtype: int + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[int] = kwargs.pop("cls", None) + + _request = build_search_get_document_count_request( + index_name=self._config.index_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(int, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _search_get( # pylint: disable=too-many-locals + self, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + search_text: Optional[str] = None, + include_total_result_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + semantic_query: Optional[str] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + semantic_fields: Optional[list[str]] = None, + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword include_total_result_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_result_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The list of field names to use for hit highlights. Only searchable + fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: list[str] + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword search_fields: The list of field names to which to scope the full-text search. When + using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of + each fielded search expression take precedence over any field names listed in this parameter. + Default value is None. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. Known values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help to get more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as + retrievable in the schema are included. Default value is None. + :paramtype select: list[str] + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + Default value is None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration: The name of the semantic configuration that lists which fields + should be used for semantic ranking, captions, highlights, and answers. Default value is None. + :paramtype semantic_configuration: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely, or to return partial results (default). Known values are: "partial" and "fail". + Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword answers: This parameter is only valid if the query type is ``semantic``. If set, the + query returns answers extracted from key passages in the highest ranked documents. The number + of answers returned can be configured by appending the pipe character ``|`` followed by the + ``count-`` option after the answers parameter value, such as + ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by + appending the pipe character ``|`` followed by the ``threshold-`` option + after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is + 0.7. The maximum character length of answers can be configured by appending the pipe character + '|' followed by the 'count-', such as + 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". Default value is + None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: This parameter is only valid if the query type is ``semantic``. If set, the + query returns captions extracted from key passages in the highest ranked documents. When + Captions is set to ``extractive``, highlighting is enabled by default, and can be configured by + appending the pipe character ``|`` followed by the ``highlight-`` option, such as + ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of captions + can be configured by appending the pipe character '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. Known values are: "none" and + "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword query_rewrites: When QueryRewrites is set to ``generative``, the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword debug: Enables a debugging tool that can be used to further explore your search + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword query_language: The language of the query. Known values are: "none", "en-us", "en-gb", + "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", + "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", + "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", + "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", + "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", + "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". Default + value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword speller: Improve search recall by spell-correcting individual search query terms. + Known values are: "none" and "lexicon". Default value is None. + :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword semantic_fields: The list of field names used for semantic ranking. Default value is + None. + :paramtype semantic_fields: list[str] + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchDocumentsResult] = kwargs.pop("cls", None) + + _request = build_search_search_get_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + enable_elevated_read=enable_elevated_read, + search_text=search_text, + include_total_result_count=include_total_result_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + search_fields=search_fields, + search_mode=search_mode, + scoring_statistics=scoring_statistics, + session_id=session_id, + select=select, + skip=skip, + top=top, + semantic_configuration=semantic_configuration, + semantic_error_handling=semantic_error_handling, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + answers=answers, + captions=captions, + semantic_query=semantic_query, + query_rewrites=query_rewrites, + debug=debug, + query_language=query_language, + speller=speller, + semantic_fields=semantic_fields, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _search_post( # pylint: disable=too-many-locals + self, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + content_type: str = "application/json", + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + semantic_fields: Optional[list[str]] = None, + vector_queries: Optional[list[_models1.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models1.VectorFilterMode]] = None, + hybrid_search: Optional[_models1.HybridSearch] = None, + **kwargs: Any + ) -> _models1.SearchDocumentsResult: ... + @overload + def _search_post( + self, + body: JSON, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SearchDocumentsResult: ... + @overload + def _search_post( + self, + body: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SearchDocumentsResult: ... + + @distributed_trace + def _search_post( # pylint: disable=too-many-locals + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + semantic_fields: Optional[list[str]] = None, + vector_queries: Optional[list[_models1.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models1.VectorFilterMode]] = None, + hybrid_search: Optional[_models1.HybridSearch] = None, + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :keyword include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: list[str] + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. Default value is None. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". Default value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specifies the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". Default value is None. + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields + marked as retrievable in the schema are included. Default value is None. + :paramtype select: list[str] + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. Default value is + None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration_name: The name of a semantic configuration that will be used + when processing documents for queries of type semantic. Default value is None. + :paramtype semantic_configuration_name: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword answers: A value that specifies whether answers should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + Default value is None. + :paramtype semantic_fields: list[str] + :keyword vector_queries: The query parameters for vector and hybrid search queries. Default + value is None. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". Default value is None. + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default + value is None. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchDocumentsResult] = kwargs.pop("cls", None) + + if body is _Unset: + body = { + "answers": answers, + "captions": captions, + "count": include_total_count, + "debug": debug, + "facets": facets, + "filter": filter, + "highlight": highlight_fields, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "hybridSearch": hybrid_search, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "queryLanguage": query_language, + "queryRewrites": query_rewrites, + "queryType": query_type, + "scoringParameters": scoring_parameters, + "scoringProfile": scoring_profile, + "scoringStatistics": scoring_statistics, + "search": search_text, + "searchFields": search_fields, + "searchMode": search_mode, + "select": select, + "semanticConfiguration": semantic_configuration_name, + "semanticErrorHandling": semantic_error_handling, + "semanticFields": semantic_fields, + "semanticMaxWaitInMilliseconds": semantic_max_wait_in_milliseconds, + "semanticQuery": semantic_query, + "sessionId": session_id, + "skip": skip, + "speller": query_speller, + "top": top, + "vectorFilterMode": vector_filter_mode, + "vectorQueries": vector_queries, + } + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_search_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + enable_elevated_read=enable_elevated_read, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_document( + self, + key: str, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + selected_fields: Optional[list[str]] = None, + **kwargs: Any + ) -> _models1.LookupDocument: + """Retrieves a document from the index. + + :param key: The key of the document to retrieve. Required. + :type key: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :keyword selected_fields: List of field names to retrieve for the document; Any field not + retrieved will be missing from the returned document. Default value is None. + :paramtype selected_fields: list[str] + :return: LookupDocument. The LookupDocument is compatible with MutableMapping + :rtype: ~azure.search.documents.models.LookupDocument + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.LookupDocument] = kwargs.pop("cls", None) + + _request = build_search_get_document_request( + key=key, + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + enable_elevated_read=enable_elevated_read, + selected_fields=selected_fields, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.LookupDocument, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _suggest_get( + self, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models1._models.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestions query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestions queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestions query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword search_fields: The list of field names to search for the specified search text. Target + fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword select: The list of fields to retrieve. If unspecified, only the key field will be + included in the results. Default value is None. + :paramtype select: list[str] + :keyword top: The number of suggestions to retrieve. The value must be a number between 1 and + 100. The default is 5. Default value is None. + :paramtype top: int + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.SuggestDocumentsResult] = kwargs.pop("cls", None) + + _request = build_search_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _suggest_post( + self, + *, + search_text: str, + suggester_name: str, + content_type: str = "application/json", + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models1._models.SuggestDocumentsResult: ... + @overload + def _suggest_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.SuggestDocumentsResult: ... + @overload + def _suggest_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.SuggestDocumentsResult: ... + + @distributed_trace + def _suggest_post( # pylint: disable=too-many-locals + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + search_text: str = _Unset, + suggester_name: str = _Unset, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models1._models.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. Default value is None. + :paramtype select: list[str] + :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. Default value is None. + :paramtype top: int + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1._models.SuggestDocumentsResult] = kwargs.pop("cls", None) + + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "search": search_text, + "searchFields": search_fields, + "select": select, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_suggest_post_request( + index_name=self._config.index_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _index( + self, batch: _models1.IndexDocumentsBatch, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.IndexDocumentsResult: ... + @overload + def _index( + self, batch: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.IndexDocumentsResult: ... + @overload + def _index( + self, batch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.IndexDocumentsResult: ... + + @distributed_trace + def _index( + self, batch: Union[_models1.IndexDocumentsBatch, JSON, IO[bytes]], **kwargs: Any + ) -> _models1._models.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, + JSON, IO[bytes] Required. + :type batch: ~azure.search.documents.models.IndexDocumentsBatch or JSON or IO[bytes] + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1._models.IndexDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(batch, (IOBase, bytes)): + _content = batch + else: + _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_request( + index_name=self._config.index_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 207]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.IndexDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _autocomplete_get( + self, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models1._models.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :keyword search_text: The incomplete term which should be auto-completed. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The list of field names to consider when querying for auto-completed + terms. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.AutocompleteResult] = kwargs.pop("cls", None) + + _request = build_search_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _autocomplete_post( + self, + *, + search_text: str, + suggester_name: str, + content_type: str = "application/json", + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models1._models.AutocompleteResult: ... + @overload + def _autocomplete_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.AutocompleteResult: ... + @overload + def _autocomplete_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1._models.AutocompleteResult: ... + + @distributed_trace + def _autocomplete_post( # pylint: disable=too-many-locals + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + search_text: str = _Unset, + suggester_name: str = _Unset, + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models1._models.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text on which to base autocomplete results. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will autocomplete terms even + if there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: list[str] + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1._models.AutocompleteResult] = kwargs.pop("cls", None) + + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "autocompleteMode": autocomplete_mode, + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "search": search_text, + "searchFields": search_fields, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_autocomplete_post_request( + index_name=self._config.index_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py new file mode 100644 index 000000000000..95ae9f41edb2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -0,0 +1,959 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Dict, List, Optional, Union, cast +import base64 +import itertools +import json + +from azure.core.paging import ItemPaged, PageIterator, ReturnType +from azure.core.tracing.decorator import distributed_trace + +from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated +from ..models._patch import RequestEntityTooLargeError +from .. import models as _models + + +def _convert_search_result(result: _models.SearchResult) -> Dict[str, Any]: + """Convert SearchResult model to dictionary with @search.* metadata. + + :param ~azure.search.documents.models.SearchResult result: The search result to convert. + :return: The converted search result. + :rtype: dict + """ + ret = dict(result) + ret["@search.score"] = result.score + ret["@search.reranker_score"] = result.reranker_score + ret["@search.highlights"] = result.highlights + ret["@search.captions"] = result.captions + ret["@search.document_debug_info"] = result.document_debug_info + ret["@search.reranker_boosted_score"] = result.reranker_boosted_score + return ret + + +def _pack_continuation_token(response: _models.SearchDocumentsResult, api_version: str) -> Optional[bytes]: + """Pack continuation token from search response. + :param ~azure.search.documents.models.SearchDocumentsResult response: The search response. + :param str api_version: The API version used in the request. + :return: The continuation token. + :rtype: bytes or None + """ + if response.next_page_parameters is not None: + token = { + "apiVersion": api_version, + "nextLink": response.next_link, + "nextPageParameters": response.next_page_parameters.as_dict(), + } + return base64.b64encode(json.dumps(token).encode("utf-8")) + return None + + +def _unpack_continuation_token(token: bytes) -> tuple: + """Unpack continuation token to get next link and request. + :param bytes token: The continuation token to unpack. + :return: A tuple of next link and next page request. + :rtype: tuple[str, ~azure.search.documents.models.SearchRequest] + """ + unpacked_token = json.loads(base64.b64decode(token)) + next_link = unpacked_token["nextLink"] + next_page_parameters = unpacked_token["nextPageParameters"] + next_page_request = _models.SearchRequest._deserialize(next_page_parameters, []) # pylint: disable=protected-access + return next_link, next_page_request + + +def _ensure_response(f): + # pylint:disable=protected-access + """Decorator to ensure response is fetched before accessing metadata. + :param f: The function to decorate. + :type f: function + + :return: The wrapper function. + :rtype: function + """ + + def wrapper(self, *args, **kw): + if self._current_page is None: + self._response = self._get_next(self.continuation_token) + self.continuation_token, self._current_page = self._extract_data(self._response) + return f(self, *args, **kw) + + return wrapper + + +def _build_search_request( + search_text: Optional[str] = None, + *, + include_total_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + query_type: Optional[Union[str, _models.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + semantic_query: Optional[str] = None, + search_fields: Optional[List[str]] = None, + search_mode: Optional[Union[str, _models.SearchMode]] = None, + query_language: Optional[Union[str, _models.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models.QuerySpellerType]] = None, + query_answer: Optional[Union[str, _models.QueryAnswerType]] = None, + query_answer_count: Optional[int] = None, + query_answer_threshold: Optional[float] = None, + query_caption: Optional[Union[str, _models.QueryCaptionType]] = None, + query_caption_highlight_enabled: Optional[bool] = None, + semantic_fields: Optional[List[str]] = None, + semantic_configuration_name: Optional[str] = None, + select: Optional[List[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, + session_id: Optional[str] = None, + vector_queries: Optional[List[_models.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models.VectorFilterMode]] = None, + semantic_error_mode: Optional[Union[str, _models.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, + query_rewrites_count: Optional[int] = None, + debug: Optional[Union[str, _models.QueryDebugMode]] = None, + hybrid_search: Optional[_models.HybridSearch] = None, +) -> _models.SearchRequest: + # pylint:disable=too-many-locals + """Build a SearchRequest from search parameters. + + This is a shared helper function used by both sync and async search methods. + + :param str search_text: A full-text search query expression; Use "*" or omit this parameter to search all fields. + :keyword bool include_total_count: A value that specifies whether to fetch the total count of results. + :keyword list[str] facets: The list of facet expressions to apply to the search query. + :keyword str filter: The OData $filter expression to apply to the search query. + :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with highlightPreTag. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with highlightPostTag. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. + :keyword order_by: The list of OData $orderby expressions by which to sort the results. + :paramtype order_by: list[str] + :keyword query_type: The type of query syntax to use for the search text. + :keyword list[str] scoring_parameters: The list of scoring parameters to use for the search query. + :keyword str scoring_profile: The name of the scoring profile to evaluate match scores for the search query. + :keyword str semantic_query: The semantic query to be used for the search. + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. + :paramtype search_fields: list[str] + :keyword search_mode: The search mode to use for the search query. + :keyword query_language: The language of the search query. + :keyword query_speller: The type of spell checking to use for the search query. + :keyword query_answer: The type of answers to retrieve for a semantic search query. + :keyword int query_answer_count: The maximum number of answers to retrieve. + :keyword float query_answer_threshold: The confidence score threshold for answers to be included in the results. + :keyword query_caption: The type of captions to retrieve for a semantic search query. + :keyword bool query_caption_highlight_enabled: A value indicating whether caption highlights are enabled. + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + :paramtype semantic_fields: list[str] + :keyword str semantic_configuration_name: The name of the semantic configuration to use for the search. + :keyword list[str] select: The list of field names to retrieve in the search results. + :keyword int skip: The number of search results to skip. + :keyword int top: The maximum number of search results to retrieve. + :keyword scoring_statistics: The scoring statistics to retrieve for the search query. + :keyword str session_id: The session ID for the search query. + :keyword list[~azure.search.documents.models.VectorQuery] vector_queries: The list of vector queries to use for the search. + :keyword vector_filter_mode: The vector filter mode to use for the search query. + :keyword semantic_error_mode: The semantic error handling mode to use for the search query. + :keyword int semantic_max_wait_in_milliseconds: The maximum wait time in milliseconds for semantic search. + :keyword query_rewrites: The type of query rewrites to apply for the search query. + :keyword int query_rewrites_count: The maximum number of query rewrites to apply. + :keyword debug: The debug mode for the search query. + :keyword hybrid_search: The hybrid search configuration for the search query. + :return: SearchRequest + :rtype: ~azure.search.documents.models.SearchRequest + """ + # Build complex query parameters + answers = None + if query_answer: + answers = str(query_answer) + if query_answer_count is not None: + answers = f"{answers}|count-{query_answer_count}" + if query_answer_threshold is not None: + answers = f"{answers},threshold-{query_answer_threshold}" + + captions = None + if query_caption: + captions = str(query_caption) + if query_caption_highlight_enabled is not None: + captions = f"{captions}|highlight-{str(query_caption_highlight_enabled).lower()}" + + rewrites = None + if query_rewrites: + rewrites = str(query_rewrites) + if query_rewrites_count is not None: + rewrites = f"{rewrites}|count-{query_rewrites_count}" + + # Convert highlight_fields from comma-separated string to list + highlight_fields_list: Optional[List[str]] = None + if highlight_fields is not None: + highlight_fields_list = [f.strip() for f in highlight_fields.split(",") if f.strip()] + + # Build and return the search request + return _models.SearchRequest( # type: ignore[misc] + search_text=search_text, + include_total_count=include_total_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields_list, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + semantic_query=semantic_query, + search_fields=search_fields, + search_mode=search_mode, + query_language=query_language, + query_speller=query_speller, + answers=answers, + captions=captions, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, + skip=skip, + top=top, + session_id=session_id, + scoring_statistics=scoring_statistics, + vector_queries=vector_queries, + vector_filter_mode=vector_filter_mode, + semantic_error_handling=semantic_error_mode, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + query_rewrites=rewrites, + debug=debug, + hybrid_search=hybrid_search, + ) + + +class SearchPageIterator(PageIterator): + """An iterator over search result pages.""" + + def __init__(self, client, initial_request: _models.SearchRequest, kwargs, continuation_token=None) -> None: + super(SearchPageIterator, self).__init__( + get_next=self._get_next_cb, + extract_data=self._extract_data_cb, + continuation_token=continuation_token, + ) + self._client = client + self._initial_request = initial_request + self._kwargs = kwargs + self._facets: Optional[Dict[str, List[Dict[str, Any]]]] = None + self._api_version = kwargs.get("api_version", "2025-11-01-preview") + + def _get_next_cb(self, continuation_token): + if continuation_token is None: + return self._client._search_post( # pylint:disable=protected-access + body=self._initial_request, **self._kwargs + ) + + _next_link, next_page_request = _unpack_continuation_token(continuation_token) + return self._client._search_post(body=next_page_request, **self._kwargs) # pylint:disable=protected-access + + def _extract_data_cb(self, response: _models.SearchDocumentsResult): + continuation_token = _pack_continuation_token(response, api_version=self._api_version) + results = [_convert_search_result(r) for r in response.results] + return continuation_token, results + + @_ensure_response + def get_facets(self) -> Optional[Dict[str, Any]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + if response.facets is not None and self._facets is None: + self._facets = { + k: [x.as_dict() if hasattr(x, "as_dict") else dict(x) for x in v] for k, v in response.facets.items() + } + return self._facets + + @_ensure_response + def get_coverage(self) -> Optional[float]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.coverage + + @_ensure_response + def get_count(self) -> Optional[int]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.count + + @_ensure_response + def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return cast(Optional[List[_models.QueryAnswerResult]], response.answers) + + @_ensure_response + def get_debug_info(self) -> Optional[_models.DebugInfo]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.debug_info + + +class SearchItemPaged(ItemPaged[ReturnType]): + """A pageable list of search results.""" + + def __init__(self, *args, **kwargs) -> None: + super(SearchItemPaged, self).__init__(*args, **kwargs) + self._first_page_iterator_instance: Optional[SearchPageIterator] = None + + def __next__(self) -> ReturnType: + if self._page_iterator is None: + first_iterator = self._first_iterator_instance() + self._page_iterator = itertools.chain.from_iterable(first_iterator) + return next(self._page_iterator) + + def _first_iterator_instance(self) -> SearchPageIterator: + if self._first_page_iterator_instance is None: + self._first_page_iterator_instance = cast(SearchPageIterator, self.by_page()) + return self._first_page_iterator_instance + + def get_facets(self) -> Optional[Dict]: + """Return any facet results if faceting was requested. + + :return: facet results + :rtype: dict or None + """ + return cast(Dict, self._first_iterator_instance().get_facets()) + + def get_coverage(self) -> float: + """Return the coverage percentage, if `minimum_coverage` was + specificied for the query. + + :return: coverage percentage + :rtype: float + """ + return cast(float, self._first_iterator_instance().get_coverage()) + + def get_count(self) -> int: + """Return the count of results if `include_total_count` was + set for the query. + + :return: count of results + :rtype: int + """ + return cast(int, self._first_iterator_instance().get_count()) + + def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + """Return semantic answers. Only included if the semantic ranker is used + and answers are requested in the search query via the query_answer parameter. + + :return: answers + :rtype: list[~azure.search.documents.models.QueryAnswerResult] or None + """ + return cast(Optional[List[_models.QueryAnswerResult]], self._first_iterator_instance().get_answers()) + + def get_debug_info(self) -> _models.DebugInfo: + """Return the debug information for the query. + + :return: the debug information for the query + :rtype: ~azure.search.documents.models.DebugInfo + """ + return cast(_models.DebugInfo, self._first_iterator_instance().get_debug_info()) + + +class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): + """SearchClient operations mixin customizations.""" + + @distributed_trace + def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + """Specify a document operations to perform as a batch. + + :param batch: A batch of document operations to perform. + :type batch: IndexDocumentsBatch + :return: List of IndexingResult + :rtype: list[IndexingResult] + + :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. + """ + return self._index_documents_actions(batch=batch, **kwargs) + + def _index_documents_actions( + self, batch: _models.IndexDocumentsBatch, **kwargs: Any + ) -> List[_models.IndexingResult]: + error_map = {413: RequestEntityTooLargeError} + try: + batch_response = self._index(batch=batch, error_map=error_map, **kwargs) + typed_result = [cast(_models.IndexingResult, x) for x in batch_response.results] + return typed_result + except RequestEntityTooLargeError: + if len(batch.actions) == 1: + raise + pos = round(len(batch.actions) / 2) + batch_response_first_half = self._index_documents_actions( + batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs + ) + if batch_response_first_half: + result_first_half = batch_response_first_half + else: + result_first_half = [] + batch_response_second_half = self._index_documents_actions( + batch=_models.IndexDocumentsBatch(actions=batch.actions[pos:]), **kwargs + ) + if batch_response_second_half: + result_second_half = batch_response_second_half + else: + result_second_half = [] + result_first_half.extend(result_second_half) + return result_first_half + + def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Upload documents to the Azure search index. + + An upload action is similar to an "upsert" where the document will be + inserted if it is new and updated/replaced if it exists. All fields are + replaced in the update case. + + :param documents: A list of documents to upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_documents_crud.py + :start-after: [START upload_document] + :end-before: [END upload_document] + :language: python + :dedent: 4 + :caption: Upload new documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_upload_actions(documents) + + result = self.index_documents(batch, **kwargs) + return result + + def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Delete documents from the Azure search index. + + Delete removes the specified documents from the index. Any field you + specify in a delete operation, other than the key field, will be ignored. + If you want to remove a field from a document, use merge instead and + set the field explicitly to None. + + :param documents: A list of documents to delete. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_documents_crud.py + :start-after: [START delete_document] + :end-before: [END delete_document] + :language: python + :dedent: 4 + :caption: Delete documents from an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_delete_actions(documents) + + result = self.index_documents(batch, **kwargs) + return result + + def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge documents in the Azure search index. + + Merge updates an existing document with the specified fields. If the + document doesn't exist, the merge will fail. Any field you specify in + a merge will replace the existing field in the document. This also + applies to collections of primitive and complex types. + + :param documents: A list of documents to merge. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_documents_crud.py + :start-after: [START merge_document] + :end-before: [END merge_document] + :language: python + :dedent: 4 + :caption: Merge documents in an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_actions(documents) + + result = self.index_documents(batch, **kwargs) + return result + + def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge or upload documents to the Azure search index. + + Merge or upload behaves like merge if a document with the given key + already exists in the index. If the document does not exist, it behaves + like upload with a new document. + + :param documents: A list of documents to merge or upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_documents_crud.py + :start-after: [START merge_or_upload_document] + :end-before: [END merge_or_upload_document] + :language: python + :dedent: 4 + :caption: Merge or upload documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_or_upload_actions(documents) + + result = self.index_documents(batch, **kwargs) + return result + + @distributed_trace + def search( + self, + search_text: Optional[str] = None, + *, + include_total_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + query_type: Optional[Union[str, _models.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + semantic_query: Optional[str] = None, + search_fields: Optional[List[str]] = None, + search_mode: Optional[Union[str, _models.SearchMode]] = None, + query_language: Optional[Union[str, _models.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models.QuerySpellerType]] = None, + query_answer: Optional[Union[str, _models.QueryAnswerType]] = None, + query_answer_count: Optional[int] = None, + query_answer_threshold: Optional[float] = None, + query_caption: Optional[Union[str, _models.QueryCaptionType]] = None, + query_caption_highlight_enabled: Optional[bool] = None, + semantic_fields: Optional[List[str]] = None, + semantic_configuration_name: Optional[str] = None, + select: Optional[List[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, + session_id: Optional[str] = None, + vector_queries: Optional[List[_models.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models.VectorFilterMode]] = None, + semantic_error_mode: Optional[Union[str, _models.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, + query_rewrites_count: Optional[int] = None, + debug: Optional[Union[str, _models.QueryDebugMode]] = None, + hybrid_search: Optional[_models.HybridSearch] = None, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + **kwargs: Any, + ) -> SearchItemPaged[Dict]: + # pylint:disable=too-many-locals + """Search the Azure search index for documents. + + :param str search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. + :keyword bool include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. + :keyword list[str] facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. + :keyword str filter: The OData $filter expression to apply to the search query. + :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is . + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is . + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: + 'simple', 'full', "semantic". + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword list[str] scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). + :keyword str scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. + :keyword str semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Possible values include: 'any', 'all'. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: The language of the search query. Possible values include: "none", "en-us", + "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", + "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", + "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", + "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", + "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", + "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", + "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk". + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Possible values include: "none", "lexicon". + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword query_answer: This parameter is only valid if the query type is 'semantic'. If set, + the query returns answers extracted from key passages in the highest ranked documents. + Possible values include: "none", "extractive". + :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType + :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and + query answer is 'extractive'. Configures the number of answers returned. Default count is 1. + :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and + query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. + :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the + query returns captions extracted from key passages in the highest ranked documents. + Defaults to 'None'. Possible values include: "none", "extractive". + :paramtype query_caption: str or ~azure.search.documents.models.QueryCaptionType + :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when + query caption is set to 'extractive'. Determines whether highlighting is enabled. + Defaults to 'true'. + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + :paramtype semantic_fields: list[str] + :keyword semantic_configuration_name: The name of the semantic configuration that will be used when + processing documents for queries of type semantic. + :paramtype semantic_configuration_name: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as retrievable + in the schema are included. + :paramtype select: list[str] + :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + :keyword int top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. + Possible values include: "local", "global". + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword str session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. + :keyword semantic_error_mode: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". + :paramtype semantic_error_mode: str or ~azure.search.documents.models.SemanticErrorMode + :keyword int semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of + time it takes for semantic enrichment to finish processing before the request fails. + :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword int query_rewrites_count: This parameter is only valid if the query rewrites type is 'generative'. + Configures the number of rewrites returned. Default count is 10. + :keyword debug: Enables a debugging tool that can be used to further explore your Semantic search + results. Known values are: "disabled", "speller", "semantic", and "all". + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword vector_queries: The query parameters for vector and hybrid search queries. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :return: List of search results. + :rtype: SearchItemPaged[dict] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_query_simple.py + :start-after: [START simple_query] + :end-before: [END simple_query] + :language: python + :dedent: 4 + :caption: Search on a simple text term. + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_query_filter.py + :start-after: [START filter_query] + :end-before: [END filter_query] + :language: python + :dedent: 4 + :caption: Filter and sort search results. + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_query_facets.py + :start-after: [START facet_query] + :end-before: [END facet_query] + :language: python + :dedent: 4 + :caption: Get search result facets. + """ + # Build the search request using shared helper + search_request = _build_search_request( + search_text=search_text, + include_total_count=include_total_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + semantic_query=semantic_query, + search_fields=search_fields, + search_mode=search_mode, + query_language=query_language, + query_speller=query_speller, + query_answer=query_answer, + query_answer_count=query_answer_count, + query_answer_threshold=query_answer_threshold, + query_caption=query_caption, + query_caption_highlight_enabled=query_caption_highlight_enabled, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, + skip=skip, + top=top, + scoring_statistics=scoring_statistics, + session_id=session_id, + vector_queries=vector_queries, + vector_filter_mode=vector_filter_mode, + semantic_error_mode=semantic_error_mode, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + query_rewrites=query_rewrites, + query_rewrites_count=query_rewrites_count, + debug=debug, + hybrid_search=hybrid_search, + ) + + # Create kwargs for the search_post call + search_kwargs = dict(kwargs) + if query_source_authorization is not None: + search_kwargs["query_source_authorization"] = query_source_authorization + if enable_elevated_read is not None: + search_kwargs["enable_elevated_read"] = enable_elevated_read + + return SearchItemPaged(self, search_request, search_kwargs, page_iterator_class=SearchPageIterator) + + @distributed_trace + def autocomplete( + self, + search_text: str, + suggester_name: str, + *, + mode: Optional[Union[str, _models.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> List[_models.AutocompleteItem]: + """Autocomplete incomplete search terms based on input text and matching terms in the index. + + :param str search_text: The search text on which to base autocomplete results. + :param str suggester_name: The name of the suggester as specified in the suggesters + collection that's part of the index definition. + :keyword mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. + Use 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while + producing auto-completed terms. Known values are: "oneTerm", "twoTerms", and + "oneTermWithContext". + :paramtype mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword str filter: An OData expression that filters the documents used to produce completed + terms for the Autocomplete result. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: list[str] + :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. + :return: List of autocomplete results. + :rtype: list[dict[str, Any]] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_query_autocomplete.py + :start-after: [START autocomplete_query] + :end-before: [END autocomplete_query] + :language: python + :dedent: 4 + :caption: Get autocomplete suggestions. + """ + # Call the generated _autocomplete_post method + response = self._autocomplete_post( + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + **kwargs, + ) + + assert response.results is not None # Hint for mypy + return response.results + + @distributed_trace + def suggest( + self, + search_text: str, + suggester_name: str, + *, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + search_fields: Optional[List[str]] = None, + select: Optional[List[str]] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> List[_models.SuggestResult]: + """Get search suggestions for documents in the Azure search index. + + :param str search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. + :param str suggester_name: The name of the suggester as specified in the suggesters + collection that's part of the index definition. + :keyword str filter: An OData expression that filters the documents considered for suggestions. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. + :keyword list[str] order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :keyword list[str] search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. + :keyword list[str] select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. + :keyword int top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. + :return: List of suggestion results. + :rtype: list[dict[str, Any]] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_query_suggestions.py + :start-after: [START suggest_query] + :end-before: [END suggest_query] + :language: python + :dedent: 4 + :caption: Get search suggestions. + """ + # Call the generated _suggest_post method + response = self._suggest_post( + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + **kwargs, + ) + + assert response.results is not None # Hint for mypy + return response.results + + +__all__: list[str] = [ + "_SearchClientOperationsMixin", + "SearchItemPaged", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/_paging.py b/sdk/search/azure-search-documents/azure/search/documents/_paging.py deleted file mode 100644 index de431227e160..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_paging.py +++ /dev/null @@ -1,182 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import List, Optional, Dict, cast, Any, MutableMapping - -import base64 -import itertools -import json - -from azure.core.paging import ItemPaged, PageIterator, ReturnType -from ._generated.models import SearchRequest, SearchDocumentsResult, QueryAnswerResult, DebugInfo -from ._api_versions import DEFAULT_VERSION - - -def convert_search_result(result): - ret = result.additional_properties - ret["@search.score"] = result.score - ret["@search.reranker_score"] = result.reranker_score - ret["@search.highlights"] = result.highlights - ret["@search.captions"] = result.captions - ret["@search.document_debug_info"] = result.document_debug_info - ret["@search.reranker_boosted_score"] = result.reranker_boosted_score - return ret - - -def pack_continuation_token(response, api_version=DEFAULT_VERSION): - if response.next_page_parameters is not None: - token = { - "apiVersion": api_version, - "nextLink": response.next_link, - "nextPageParameters": response.next_page_parameters.serialize(), - } - return base64.b64encode(json.dumps(token).encode("utf-8")) - return None - - -def unpack_continuation_token(token): - unpacked_token = json.loads(base64.b64decode(token)) - next_link = unpacked_token["nextLink"] - next_page_parameters = unpacked_token["nextPageParameters"] - next_page_request = SearchRequest.deserialize(next_page_parameters) - return next_link, next_page_request - - -class SearchItemPaged(ItemPaged[ReturnType]): - """A pageable list of search results.""" - - def __init__(self, *args, **kwargs) -> None: - super(SearchItemPaged, self).__init__(*args, **kwargs) - self._first_page_iterator_instance: Optional[SearchPageIterator] = None - - def __next__(self) -> ReturnType: - if self._page_iterator is None: - first_iterator = self._first_iterator_instance() - self._page_iterator = itertools.chain.from_iterable(first_iterator) - return next(self._page_iterator) - - def _first_iterator_instance(self) -> "SearchPageIterator": - if self._first_page_iterator_instance is None: - self._first_page_iterator_instance = cast(SearchPageIterator, self.by_page()) - return self._first_page_iterator_instance - - def get_facets(self) -> Optional[Dict]: - """Return any facet results if faceting was requested. - - :return: facet results - :rtype: dict or None - """ - return cast(Dict, self._first_iterator_instance().get_facets()) - - def get_coverage(self) -> float: - """Return the coverage percentage, if `minimum_coverage` was - specificied for the query. - - :return: coverage percentage - :rtype: float - """ - return cast(float, self._first_iterator_instance().get_coverage()) - - def get_count(self) -> int: - """Return the count of results if `include_total_count` was - set for the query. - - :return: count of results - :rtype: int - """ - return cast(int, self._first_iterator_instance().get_count()) - - def get_answers(self) -> Optional[List[QueryAnswerResult]]: - """Return semantic answers. Only included if the semantic ranker is used - and answers are requested in the search query via the query_answer parameter. - - :return: answers - :rtype: list[~azure.search.documents.models.QueryAnswerResult] or None - """ - return cast(List[QueryAnswerResult], self._first_iterator_instance().get_answers()) - - def get_debug_info(self) -> DebugInfo: - """Return the debug information for the query. - - :return: the debug information for the query - :rtype: ~azure.search.documents.models.DebugInfo - """ - return cast(DebugInfo, self._first_iterator_instance().get_debug_info()) - - -# The pylint error silenced below seems spurious, as the inner wrapper does, in -# fact, become a method of the class when it is applied. -def _ensure_response(f): - # pylint:disable=protected-access - def wrapper(self, *args, **kw): - if self._current_page is None: - self._response = self._get_next(self.continuation_token) - self.continuation_token, self._current_page = self._extract_data(self._response) - return f(self, *args, **kw) - - return wrapper - - -class SearchPageIterator(PageIterator): - """An iterator over search results.""" - - def __init__(self, client, initial_query, kwargs, continuation_token=None) -> None: - super(SearchPageIterator, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token, - ) - self._client = client - self._initial_query = initial_query - self._kwargs = kwargs - self._facets: Optional[MutableMapping[str, List[MutableMapping[str, Any]]]] = None - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - - def _get_next_cb(self, continuation_token): - if continuation_token is None: - return self._client.documents.search_post(search_request=self._initial_query.request, **self._kwargs) - - _next_link, next_page_request = unpack_continuation_token(continuation_token) - - return self._client.documents.search_post(search_request=next_page_request, **self._kwargs) - - def _extract_data_cb(self, response): - continuation_token = pack_continuation_token(response, api_version=self._api_version) - results = [convert_search_result(r) for r in response.results] - return continuation_token, results - - @_ensure_response - def get_facets(self) -> Optional[MutableMapping[str, Any]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - facets = response.facets - if facets is not None and self._facets is None: - assert facets.items() is not None # Hint for mypy - self._facets = {k: [x.as_dict() for x in v] for k, v in facets.items()} - return self._facets - - @_ensure_response - def get_coverage(self) -> float: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(float, response.coverage) - - @_ensure_response - def get_count(self) -> int: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(int, response.count) - - @_ensure_response - def get_answers(self) -> Optional[List[QueryAnswerResult]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return response.answers - - @_ensure_response - def get_debug_info(self) -> DebugInfo: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(DebugInfo, response.debug_info) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py similarity index 66% rename from sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py rename to sdk/search/azure-search-documents/azure/search/documents/_patch.py index 394a3660bb53..32228f20cf50 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -1,27 +1,75 @@ -# ------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- -from typing import cast, List, Any, Union, Dict +# pylint: disable=too-many-instance-attributes +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Union, List, Dict, Optional, cast +from enum import Enum import time import threading +from azure.core import CaseInsensitiveEnumMeta from azure.core.credentials import AzureKeyCredential, TokenCredential from azure.core.tracing.decorator import distributed_trace from azure.core.exceptions import ServiceResponseTimeoutError -from ._utils import is_retryable_status_code, get_authentication_policy -from .indexes import SearchIndexClient as SearchServiceClient -from ._search_indexing_buffered_sender_base import SearchIndexingBufferedSenderBase -from ._generated import SearchIndexClient -from ._generated.models import IndexingResult, IndexBatch, IndexAction -from ._search_documents_error import RequestEntityTooLargeError -from ._index_documents_batch import IndexDocumentsBatch -from ._headers_mixin import HeadersMixin -from ._version import SDK_MONIKER - - -class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixin): + +from ._client import SearchClient as _SearchClient +from ._operations._patch import SearchItemPaged +from .models._patch import RequestEntityTooLargeError, IndexDocumentsBatch +from .models import IndexAction, IndexingResult +from .indexes import SearchIndexClient + + +def is_retryable_status_code(status_code: int) -> bool: + """Check if a status code is retryable. + + :param int status_code: The status code to check + :return: True if the status code is retryable, False otherwise + :rtype: bool + """ + return status_code in (409, 422, 503) + + +class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + V2020_06_30 = "2020-06-30" + V2023_11_01 = "2023-11-01" + V2024_07_01 = "2024-07-01" + V2025_09_01 = "2025-09-01" + V2025_11_01_PREVIEW = "2025-11-01-preview" + + +DEFAULT_VERSION = ApiVersion.V2025_11_01_PREVIEW + + +class SearchClient(_SearchClient): + """SearchClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any + ) -> None: + super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) + + +class SearchIndexingBufferedSender: """A buffered sender for document indexing actions. :param endpoint: The URL endpoint of an Azure search service @@ -30,7 +78,8 @@ class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixi :type index_name: str :param credential: A credential to authorize search client requests :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword int auto_flush_interval: how many max seconds if between 2 flushes. This only takes effect + :keyword bool auto_flush: Whether to automatically flush the batch. Default is True. + :keyword int auto_flush_interval: How many max seconds between 2 flushes. This only takes effect when auto_flush is on. Default to 60 seconds. :keyword int initial_batch_action_count: The initial number of actions to group into a batch when tuning the behavior of the sender. The default value is 512. @@ -45,50 +94,54 @@ class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixi is a IndexAction removed from the queue (succeeds or fails). This may be called from main thread or a worker thread. :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The + :keyword str audience: Sets the Audience to use for authentication with Microsoft Entra ID. The audience is not considered when using a shared key. If audience is not provided, the public cloud audience will be assumed. """ - _client: SearchIndexClient - - # pylint: disable=too-many-instance-attributes + _DEFAULT_AUTO_FLUSH_INTERVAL = 60 + _DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512 + _DEFAULT_MAX_RETRIES = 3 def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any ) -> None: - super(SearchIndexingBufferedSender, self).__init__( - endpoint=endpoint, index_name=index_name, credential=credential, **kwargs - ) + self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) + self._auto_flush = kwargs.pop("auto_flush", True) + self._batch_action_count = kwargs.pop("initial_batch_action_count", self._DEFAULT_INITIAL_BATCH_ACTION_COUNT) + self._auto_flush_interval = kwargs.pop("auto_flush_interval", self._DEFAULT_AUTO_FLUSH_INTERVAL) + if self._auto_flush_interval <= 0: + raise ValueError("auto_flush_interval must be a positive number.") + self._max_retries_per_action = kwargs.pop("max_retries_per_action", self._DEFAULT_MAX_RETRIES) + self._endpoint = endpoint + self._index_name = index_name + self._index_key: Optional[str] = None + self._credential = credential + self._on_new = kwargs.pop("on_new", None) + self._on_progress = kwargs.pop("on_progress", None) + self._on_error = kwargs.pop("on_error", None) + self._on_remove = kwargs.pop("on_remove", None) + self._retry_counter: Dict[str, int] = {} + self._index_documents_batch = IndexDocumentsBatch() - audience = kwargs.pop("audience", None) + + # Create the search client based on credential type if isinstance(credential, AzureKeyCredential): self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs + self._client = _SearchClient( + endpoint=endpoint, index_name=index_name, credential=credential, api_version=self._api_version, **kwargs ) else: self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs + self._client = _SearchClient( + endpoint=endpoint, index_name=index_name, credential=credential, api_version=self._api_version, **kwargs ) self._reset_timer() def _cleanup(self, flush: bool = True) -> None: """Clean up the client. - :param bool flush: flush the actions queue before shutdown the client - Default to True. + :param bool flush: Flush the actions queue before shutdown the client. Default to True. """ if flush: self.flush() @@ -106,7 +159,7 @@ def actions(self) -> List[IndexAction]: :rtype: list[IndexAction] """ - return self._index_documents_batch.actions + return self._index_documents_batch.actions if self._index_documents_batch.actions else [] @distributed_trace def close(self, **kwargs) -> None: # pylint: disable=unused-argument @@ -122,7 +175,7 @@ def close(self, **kwargs) -> None: # pylint: disable=unused-argument def flush(self, timeout: int = 86400, **kwargs: Any) -> bool: # pylint:disable=unused-argument """Flush the batch. - :param int timeout: time out setting. Default is 86400s (one day) + :param int timeout: Time out setting. Default is 86400s (one day) :return: True if there are errors. Else False :rtype: bool :raises ~azure.core.exceptions.ServiceResponseTimeoutError: @@ -150,7 +203,7 @@ def _process(self, timeout: int = 86400, **kwargs) -> bool: if not self._index_key: try: credential = cast(Union[AzureKeyCredential, TokenCredential], self._credential) - client = SearchServiceClient(self._endpoint, credential) + client = SearchIndexClient(self._endpoint, credential) index_result = client.get_index(self._index_name) if index_result: for field in index_result.fields: @@ -167,11 +220,7 @@ def _process(self, timeout: int = 86400, **kwargs) -> bool: for result in results: try: assert self._index_key is not None # Hint for mypy - action = next( - x - for x in actions - if x.additional_properties and x.additional_properties.get(self._index_key) == result.key - ) + action = next(x for x in actions if x and str(x.get(self._index_key)) == result.key) if result.succeeded: self._callback_succeed(action) elif is_retryable_status_code(result.status_code): @@ -192,17 +241,18 @@ def _process(self, timeout: int = 86400, **kwargs) -> bool: return has_error def _process_if_needed(self) -> bool: - """Every time when a new action is queued, this method - will be triggered. It checks the actions already queued and flushes them if: - 1. Auto_flush is on - 2. There are self._batch_action_count actions queued - :return: True if proces is needed, False otherwise + """Check if processing is needed and process if necessary. + + :return: True if process had errors, False otherwise :rtype: bool """ if not self._auto_flush: return False - if len(self._index_documents_batch.actions) < self._batch_action_count: + if ( + len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) + < self._batch_action_count + ): return False return self._process(raise_error=False) @@ -269,22 +319,19 @@ def index_documents(self, batch: IndexDocumentsBatch, **kwargs) -> List[Indexing :param batch: A batch of document operations to perform. :type batch: IndexDocumentsBatch :return: Indexing result of each action in the batch. - :rtype: list[IndexingResult] - + :rtype: list[IndexingResult] :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. """ - return self._index_documents_actions(actions=batch.actions, **kwargs) + return self._index_documents_actions(actions=batch.actions if batch.actions else [], **kwargs) def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - timeout = kwargs.pop("timeout", 86400) begin_time = int(time.time()) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) + + batch = IndexDocumentsBatch(actions=actions) try: - batch_response = self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) + batch_response = self._client.index_documents(batch=batch, **kwargs) # pylint: disable=no-member + return cast(List[IndexingResult], batch_response) except RequestEntityTooLargeError as ex: if len(actions) == 1: raise @@ -298,10 +345,8 @@ def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List batch_response_first_half = self._index_documents_actions( actions=actions[:pos], timeout=remaining, **kwargs ) - if len(batch_response_first_half) > 0: - result_first_half = batch_response_first_half - else: - result_first_half = [] + result_first_half = list(batch_response_first_half) if batch_response_first_half else [] + now = int(time.time()) remaining = timeout - (now - begin_time) if remaining < 0: @@ -309,10 +354,8 @@ def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List batch_response_second_half = self._index_documents_actions( actions=actions[pos:], timeout=remaining, **kwargs ) - if len(batch_response_second_half) > 0: - result_second_half = batch_response_second_half - else: - result_second_half = [] + result_second_half = list(batch_response_second_half) if batch_response_second_half else [] + result_first_half.extend(result_second_half) return result_first_half @@ -328,7 +371,7 @@ def _retry_action(self, action: IndexAction) -> None: if not self._index_key: self._callback_fail(action) return - key = cast(str, action.additional_properties.get(self._index_key) if action.additional_properties else "") + key = cast(str, action.get(self._index_key) if action else "") counter = self._retry_counter.get(key) if not counter: # first time that fails @@ -357,3 +400,23 @@ def _callback_new(self, actions: List[IndexAction]) -> None: if self._on_new: for action in actions: self._on_new(action) + + +__all__: list[str] = [ + "SearchClient", + "SearchItemPaged", + "SearchIndexingBufferedSender", + "ApiVersion", + "DEFAULT_VERSION", + "RequestEntityTooLargeError", + "IndexDocumentsBatch", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/_queries.py b/sdk/search/azure-search-documents/azure/search/documents/_queries.py deleted file mode 100644 index bc24fbe7db91..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_queries.py +++ /dev/null @@ -1,135 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Type, Union, List, cast -from ._generated.models import AutocompleteRequest, SearchRequest, SuggestRequest - - -class _QueryBase: - - _request_type: Union[Type[AutocompleteRequest], Type[SearchRequest], Type[SuggestRequest]] = cast( - Union[Type[AutocompleteRequest], Type[SearchRequest], Type[SuggestRequest]], - None, - ) - - def __init__(self, **kwargs) -> None: - self._request = self._request_type(**kwargs) # pylint:disable=not-callable - - def __repr__(self) -> str: - return "<{} [{}]>".format(self.__class__.__name__, self._request.search_text)[:1024] - - def filter(self, expression: str) -> None: - """Add a `filter` expression for the search results. - - :param expression: An ODate expression of for the query filter. - :type expression: str - """ - self._request.filter = expression - - @property - def request(self) -> Union[AutocompleteRequest, SearchRequest, SuggestRequest]: - """The service request for this operation. - - :return: The service request for this operation. - :rtype: AutocompleteRequest or SearchRequest or SuggestRequest - """ - return self._request - - -class AutocompleteQuery(_QueryBase): - """Represent an autocomplete query again an Azure Search index.""" - - _request_type = AutocompleteRequest - - __doc__ = AutocompleteRequest.__doc__ - - -class SearchQuery(_QueryBase): - """Represent a rich search query again an Azure Search index.""" - - _request_type = SearchRequest - - __doc__ = SearchRequest.__doc__ - - def order_by(self, *fields: Union[str, List[str]]) -> None: - """Update the `orderby` property for the search results. - - :param fields: A list of fields for the query result to be ordered by. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SearchRequest, self._request) - request.order_by = ",".join(selects) - - def select(self, *fields: Union[str, List[str]]) -> None: - """Update the `select` property for the search results. - - :param fields: A list of fields for the query result to return. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SearchRequest, self._request) - request.select = ",".join(selects) - - -class SuggestQuery(_QueryBase): - """Represent a search suggestion query again an Azure Search index.""" - - _request_type = SuggestRequest - - __doc__ = SuggestRequest.__doc__ - - def order_by(self, *fields: Union[str, List[str]]) -> None: - """Update the `orderby` property for the search results. - - :param fields: A list of fields for the query result to be ordered by. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SuggestRequest, self._request) - request.order_by = ",".join(selects) - - def select(self, *fields: Union[str, List[str]]) -> None: - """Update the `select` property for the search results. - - :param fields: A list of fields for the query result to return. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SuggestRequest, self._request) - request.select = ",".join(selects) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_client.py b/sdk/search/azure-search-documents/azure/search/documents/_search_client.py deleted file mode 100644 index d7cc1b0088aa..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_client.py +++ /dev/null @@ -1,751 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import cast, List, Any, Union, Dict, Optional, MutableMapping - -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from ._api_versions import DEFAULT_VERSION -from ._generated import SearchIndexClient -from ._generated.models import ( - AutocompleteMode, - AutocompleteRequest, - IndexAction, - IndexBatch, - IndexingResult, - QueryAnswerType, - QueryCaptionType, - QueryLanguage, - QuerySpellerType, - QueryType, - SearchMode, - ScoringStatistics, - VectorFilterMode, - VectorQuery, - SemanticErrorMode, - QueryDebugMode, - QueryRewritesType, - SuggestRequest, - HybridSearch, -) -from ._search_documents_error import RequestEntityTooLargeError -from ._index_documents_batch import IndexDocumentsBatch -from ._paging import SearchItemPaged, SearchPageIterator -from ._queries import AutocompleteQuery, SearchQuery, SuggestQuery -from ._headers_mixin import HeadersMixin -from ._utils import get_authentication_policy, get_answer_query, get_rewrites_query -from ._version import SDK_MONIKER - - -class SearchClient(HeadersMixin): - """A client to interact with an existing Azure search index. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param index_name: The name of the index to connect to - :type index_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START authenticate_search_client_with_api_key] - :end-before: [END authenticate_search_client_with_api_key] - :language: python - :dedent: 4 - :caption: Creating the SearchClient with an API key. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: SearchIndexClient - - def __init__( - self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = endpoint - self._index_name = index_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __repr__(self) -> str: - return "".format(repr(self._endpoint), repr(self._index_name))[:1024] - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - @distributed_trace - def get_document_count(self, **kwargs: Any) -> int: - """Return the number of documents in the Azure search index. - - :return: The count of documents in the index - :rtype: int - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return int(self._client.documents.count(**kwargs)) - - @distributed_trace - def get_document(self, key: str, selected_fields: Optional[List[str]] = None, **kwargs: Any) -> Dict: - """Retrieve a document from the Azure search index by its key. - - :param key: The primary key value for the document to retrieve - :type key: str - :param selected_fields: an allow-list of fields to include in the results - :type selected_fields: list[str] - :return: The document as stored in the Azure search index - :rtype: dict - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_documents_crud.py - :start-after: [START get_document] - :end-before: [END get_document] - :language: python - :dedent: 4 - :caption: Get a specific document from the search index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.documents.get(key=key, selected_fields=selected_fields, **kwargs) - return cast(dict, result) - - @distributed_trace - def search( - self, - search_text: Optional[str] = None, - *, - include_total_count: Optional[bool] = None, - facets: Optional[List[str]] = None, - filter: Optional[str] = None, - highlight_fields: Optional[str] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - query_type: Optional[Union[str, QueryType]] = None, - scoring_parameters: Optional[List[str]] = None, - scoring_profile: Optional[str] = None, - semantic_query: Optional[str] = None, - search_fields: Optional[List[str]] = None, - search_mode: Optional[Union[str, SearchMode]] = None, - query_language: Optional[Union[str, QueryLanguage]] = None, - query_speller: Optional[Union[str, QuerySpellerType]] = None, - query_answer: Optional[Union[str, QueryAnswerType]] = None, - query_answer_count: Optional[int] = None, - query_answer_threshold: Optional[float] = None, - query_caption: Optional[Union[str, QueryCaptionType]] = None, - query_caption_highlight_enabled: Optional[bool] = None, - semantic_fields: Optional[List[str]] = None, - semantic_configuration_name: Optional[str] = None, - select: Optional[List[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - scoring_statistics: Optional[Union[str, ScoringStatistics]] = None, - session_id: Optional[str] = None, - vector_queries: Optional[List[VectorQuery]] = None, - vector_filter_mode: Optional[Union[str, VectorFilterMode]] = None, - semantic_error_mode: Optional[Union[str, SemanticErrorMode]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - query_rewrites: Optional[Union[str, QueryRewritesType]] = None, - query_rewrites_count: Optional[int] = None, - debug: Optional[Union[str, QueryDebugMode]] = None, - hybrid_search: Optional[HybridSearch] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - **kwargs: Any - ) -> SearchItemPaged[Dict]: - # pylint:disable=too-many-locals, disable=redefined-builtin - """Search the Azure search index for documents. - - :param str search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. - :keyword bool include_total_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :keyword list[str] facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :keyword str filter: The OData $filter expression to apply to the search query. - :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is . - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is . - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: - 'simple', 'full', "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword list[str] scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :keyword str scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :keyword str semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :keyword list[str] search_fields: The list of field names to which to scope the full-text search. When - using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of - each fielded search expression take precedence over any field names listed in this parameter. - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Possible values include: 'any', 'all'. - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: The language of the search query. Possible values include: "none", "en-us", - "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", - "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", - "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", - "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", - "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", - "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", - "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Possible values include: "none", "lexicon". - :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword query_answer: This parameter is only valid if the query type is 'semantic'. If set, - the query returns answers extracted from key passages in the highest ranked documents. - Possible values include: "none", "extractive". - :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType - :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. Configures the number of answers returned. Default count is 1. - :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. - :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the - query returns captions extracted from key passages in the highest ranked documents. - Defaults to 'None'. Possible values include: "none", "extractive". - :paramtype query_caption: str or ~azure.search.documents.models.QueryCaptionType - :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when - query caption is set to 'extractive'. Determines whether highlighting is enabled. - Defaults to 'true'. - :keyword list[str] semantic_fields: The list of field names used for semantic search. - :keyword semantic_configuration_name: The name of the semantic configuration that will be used when - processing documents for queries of type semantic. - :paramtype semantic_configuration_name: str - :keyword list[str] select: The list of fields to retrieve. If unspecified, all fields marked as retrievable - in the schema are included. - :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use $skip due to this limitation, - consider using $orderby on a totally-ordered key and $filter with a range query instead. - :keyword int top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. - Possible values include: "local", "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword str session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :keyword semantic_error_mode: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :paramtype semantic_error_mode: str or ~azure.search.documents.models.SemanticErrorMode - :keyword int semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent - to a generate model which will produce 10 (default) rewrites to help increase the recall of the - request. The requested count can be configured by appending the pipe character ``|`` followed - by the ``count-`` option, such as ``generative|count-3``. Defaults to - ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword int query_rewrites_count: This parameter is only valid if the query rewrites type is 'generative'. - Configures the number of rewrites returned. Default count is 10. - :keyword debug: Enables a debugging tool that can be used to further explore your Semantic search - results. Known values are: "disabled", "speller", "semantic", and "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword vector_queries: The query parameters for vector and hybrid search queries. - :paramtype vector_queries: list[VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". - :paramtype vector_filter_mode: str or VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - :keyword x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype x_ms_query_source_authorization: str - :keyword x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :paramtype x_ms_enable_elevated_read: bool - :return: List of search results. - :rtype: SearchItemPaged[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_query_simple.py - :start-after: [START simple_query] - :end-before: [END simple_query] - :language: python - :dedent: 4 - :caption: Search on a simple text term. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_query_filter.py - :start-after: [START filter_query] - :end-before: [END filter_query] - :language: python - :dedent: 4 - :caption: Filter and sort search results. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_query_facets.py - :start-after: [START facet_query] - :end-before: [END facet_query] - :language: python - :dedent: 4 - :caption: Get search result facets. - """ - include_total_result_count = include_total_count - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - - answers = get_answer_query(query_answer, query_answer_count, query_answer_threshold) - - rewrites = get_rewrites_query(query_rewrites, query_rewrites_count) - - captions = ( - query_caption - if not query_caption_highlight_enabled - else "{}|highlight-{}".format(query_caption, query_caption_highlight_enabled) - ) - - semantic_configuration = semantic_configuration_name - - query = SearchQuery( - search_text=search_text, - include_total_result_count=include_total_result_count, - facets=facets, - filter=filter_arg, - highlight_fields=highlight_fields, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - query_type=query_type, - scoring_parameters=scoring_parameters, - scoring_profile=scoring_profile, - semantic_query=semantic_query, - search_fields=search_fields_str, - search_mode=search_mode, - query_language=query_language, - speller=query_speller, - answers=answers, - captions=captions, - semantic_fields=",".join(semantic_fields) if semantic_fields else None, - semantic_configuration=semantic_configuration, - select=select if isinstance(select, str) else None, - skip=skip, - top=top, - session_id=session_id, - scoring_statistics=scoring_statistics, - vector_queries=vector_queries, - vector_filter_mode=vector_filter_mode, - semantic_error_handling=semantic_error_mode, - semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, - query_rewrites=rewrites, - debug=debug, - hybrid_search=hybrid_search, - ) - if isinstance(select, list): - query.select(select) - - if isinstance(order_by, list): - query.order_by(order_by) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["x_ms_query_source_authorization"] = x_ms_query_source_authorization - kwargs["x_ms_enable_elevated_read"] = x_ms_enable_elevated_read - kwargs["api_version"] = self._api_version - return SearchItemPaged(self._client, query, kwargs, page_iterator_class=SearchPageIterator) - - @distributed_trace - def suggest( - self, - search_text: str, - suggester_name: str, - *, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, - top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search suggestion results from the Azure search index. - - :param str search_text: Required. The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. - :param str suggester_name: Required. The name of the suggester as specified in the suggesters - collection that's part of the index definition. - :keyword str filter: An OData expression that filters the documents considered for suggestions. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestions - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestions queries are slower and - consume more resources. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestions query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :keyword list[str] search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :keyword list[str] select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :keyword int top: The number of suggestions to retrieve. The value must be a number between 1 and - 100. The default is 5. - - :return: List of suggestion results. - :rtype: list[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_query_suggestions.py - :start-after: [START suggest_query] - :end-before: [END suggest_query] - :language: python - :dedent: 4 - :caption: Get search suggestions. - """ - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = SuggestQuery( - search_text=search_text, - suggester_name=suggester_name, - filter=filter_arg, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - search_fields=search_fields_str, - select=select if isinstance(select, str) else None, - top=top, - ) - if isinstance(select, list): - query.select(select) - if isinstance(order_by, list): - query.order_by(order_by) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(SuggestRequest, query.request) - response = self._client.documents.suggest_post(suggest_request=request, **kwargs) - assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - @distributed_trace - def autocomplete( - self, - search_text: str, - suggester_name: str, - *, - mode: Optional[Union[str, AutocompleteMode]] = None, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[List[str]] = None, - top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search auto-completion results from the Azure search index. - - :param str search_text: The search text on which to base autocomplete results. - :param str suggester_name: The name of the suggester as specified in the suggesters - collection that's part of the index definition. - :keyword mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Possible values include: 'oneTerm', 'twoTerms', 'oneTermWithContext'. - :paramtype mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword str filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :return: List of auto-completion results. - :rtype: list[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_query_autocomplete.py - :start-after: [START autocomplete_query] - :end-before: [END autocomplete_query] - :language: python - :dedent: 4 - :caption: Get a auto-completions. - """ - autocomplete_mode = mode - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = AutocompleteQuery( - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter_arg, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields_str, - top=top, - ) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(AutocompleteRequest, query.request) - response = self._client.documents.autocomplete_post(autocomplete_request=request, **kwargs) - assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - # pylint:disable=client-method-missing-tracing-decorator - def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Upload documents to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: A list of documents to upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_documents_crud.py - :start-after: [START upload_document] - :end-before: [END upload_document] - :language: python - :dedent: 4 - :caption: Upload new documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator, delete-operation-wrong-return-type - def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Delete documents from the Azure search index - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: A list of documents to delete. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_documents_crud.py - :start-after: [START delete_document] - :end-before: [END delete_document] - :language: python - :dedent: 4 - :caption: Delete existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_delete_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator - def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - - :param documents: A list of documents to merge. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_documents_crud.py - :start-after: [START merge_document] - :end-before: [END merge_document] - :language: python - :dedent: 4 - :caption: Merge fields into existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_merge_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator - def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index, - or upload them if they do not yet exist. - - This action behaves like `merge_documents` if a document with the given - key already exists in the index. If the document does not exist, it - behaves like `upload_documents` with a new document. - - :param documents: A list of documents to merge or upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - """ - batch = IndexDocumentsBatch() - batch.add_merge_or_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - @distributed_trace - def index_documents(self, batch: IndexDocumentsBatch, **kwargs: Any) -> List[IndexingResult]: - """Specify a document operations to perform as a batch. - - :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: List of IndexingResult - :rtype: list[IndexingResult] - - :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. - """ - return self._index_documents_actions(actions=batch.actions, **kwargs) - - def _index_documents_actions(self, actions: List[IndexAction], **kwargs: Any) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) - try: - batch_response = self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) - except RequestEntityTooLargeError: - if len(actions) == 1: - raise - pos = round(len(actions) / 2) - batch_response_first_half = self._index_documents_actions(actions=actions[:pos], **kwargs) - if batch_response_first_half: - result_first_half = batch_response_first_half - else: - result_first_half = [] - batch_response_second_half = self._index_documents_actions(actions=actions[pos:], **kwargs) - if batch_response_second_half: - result_second_half = batch_response_second_half - else: - result_second_half = [] - result_first_half.extend(result_second_half) - return result_first_half - - def __enter__(self) -> "SearchClient": - self._client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args) -> None: - self._client.__exit__(*args) - - @distributed_trace - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> HttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py b/sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py deleted file mode 100644 index fdcec1b4f7b2..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py +++ /dev/null @@ -1,10 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -from azure.core.exceptions import HttpResponseError - - -class RequestEntityTooLargeError(HttpResponseError): - """An error response with status code 413 - Request Entity Too Large""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py b/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py deleted file mode 100644 index 38fcdfbcd4a1..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py +++ /dev/null @@ -1,51 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -# pylint: disable=too-few-public-methods, too-many-instance-attributes -from typing import Any, Union, Dict, Optional - -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.credentials_async import AsyncTokenCredential -from ._api_versions import DEFAULT_VERSION -from ._headers_mixin import HeadersMixin - - -class SearchIndexingBufferedSenderBase(HeadersMixin): - """Base of search indexing buffered sender""" - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _DEFAULT_AUTO_FLUSH_INTERVAL = 60 - _DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512 - _DEFAULT_MAX_RETRIES = 3 - - def __init__( - self, - endpoint: str, - index_name: str, - credential: Union[AzureKeyCredential, TokenCredential, AsyncTokenCredential], - *, - auto_flush: bool = True, - initial_batch_action_count: int = _DEFAULT_INITIAL_BATCH_ACTION_COUNT, - auto_flush_interval: int = _DEFAULT_AUTO_FLUSH_INTERVAL, - max_retries_per_action: int = _DEFAULT_MAX_RETRIES, - **kwargs: Any - ) -> None: - - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._auto_flush = auto_flush - self._batch_action_count = initial_batch_action_count - self._auto_flush_interval = auto_flush_interval - if self._auto_flush_interval <= 0: - raise ValueError("auto_flush_interval must be a positive number.") - self._max_retries_per_action = max_retries_per_action - self._endpoint = endpoint - self._index_name = index_name - self._index_key: Optional[str] = None - self._credential = credential - self._on_new = kwargs.pop("on_new", None) - self._on_progress = kwargs.pop("on_progress", None) - self._on_error = kwargs.pop("on_error", None) - self._on_remove = kwargs.pop("on_remove", None) - self._retry_counter: Dict[str, int] = {} diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils.py b/sdk/search/azure-search-documents/azure/search/documents/_utils.py deleted file mode 100644 index 5b912120c1ed..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_utils.py +++ /dev/null @@ -1,81 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Optional, Union -from azure.core.pipeline.policies import ( - BearerTokenCredentialPolicy, - AsyncBearerTokenCredentialPolicy, -) -from ._generated.models import QueryAnswerType, QueryRewritesType - -DEFAULT_AUDIENCE = "https://search.azure.com" - - -def get_answer_query( - query_answer: Optional[Union[str, QueryAnswerType]] = None, - query_answer_count: Optional[int] = None, - query_answer_threshold: Optional[float] = None, -) -> Optional[Union[str, QueryAnswerType]]: - answers = query_answer - separator = "|" - if query_answer_count: - answers = f"{answers}{separator}count-{query_answer_count}" - separator = "," - if query_answer_threshold: - answers = f"{answers}{separator}threshold-{query_answer_threshold}" - return answers - - -def get_rewrites_query( - query_rewrites: Optional[Union[str, QueryRewritesType]] = None, query_rewrites_count: Optional[int] = None -) -> Optional[Union[str, QueryRewritesType]]: - rewrites = query_rewrites - separator = "|" - if query_rewrites_count: - rewrites = f"{rewrites}{separator}count-{query_rewrites_count}" - return rewrites - - -def is_retryable_status_code(status_code: Optional[int]) -> bool: - if not status_code: - return False - return status_code in [422, 409, 503] - - -def get_authentication_policy(credential, *, is_async: bool = False, **kwargs): - audience = kwargs.get("audience", None) - if not audience: - audience = DEFAULT_AUDIENCE - scope = audience.rstrip("/") + "/.default" - _policy = BearerTokenCredentialPolicy if not is_async else AsyncBearerTokenCredentialPolicy - authentication_policy = _policy(credential, scope) - return authentication_policy - - -def odata(statement: str, **kwargs: Any) -> str: - """Escape an OData query string. - - The statement to prepare should include fields to substitute given inside - braces, e.g. `{somevar}` and then pass the corresponding value as a keyword - argument, e.g. `somevar=10`. - - :param statement: An OData query string to prepare - :type statement: str - :return: The prepared OData query string - :rtype: str - - .. admonition:: Example: - - >>> odata("name eq {name} and age eq {age}", name="O'Neil", age=37) - "name eq 'O''Neil' and age eq 37" - - - """ - for key, value in kwargs.items(): - if isinstance(value, str): - value = value.replace("'", "''") - if f"'{{{key}}}'" not in statement: - kwargs[key] = f"'{value}'" - return statement.format(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/__init__.py similarity index 52% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_utils/__init__.py index 4473821c4ebe..8026245c2abc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/__init__.py @@ -1,4 +1,6 @@ # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py new file mode 100644 index 000000000000..c402af2afc63 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py @@ -0,0 +1,1337 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/serialization.py similarity index 98% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/serialization.py rename to sdk/search/azure-search-documents/azure/search/documents/_utils/serialization.py index 9b8154c91dc2..81ec1de5922b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/serialization.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/serialization.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -819,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1755,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1781,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py index c1a8ba78d5dd..79294ce3d7df 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py @@ -1,34 +1,29 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._search_client_async import AsyncSearchItemPaged, SearchClient -from ._search_indexing_buffered_sender_async import SearchIndexingBufferedSender +from typing import TYPE_CHECKING -__all__ = ( - "AsyncSearchItemPaged", +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ "SearchClient", - "SearchIndexingBufferedSender", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py similarity index 66% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_search_index_client.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_client.py index fbcf048dfbbd..5634eb8a97d5 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_search_index_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py @@ -1,42 +1,56 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models from .._utils.serialization import Deserializer, Serializer -from ._configuration import SearchIndexClientConfiguration -from .operations import DocumentsOperations +from ._configuration import SearchClientConfiguration +from ._operations import _SearchClientOperationsMixin +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class SearchIndexClient: - """Client that can be used to query an index and upload, merge, or delete documents. - :ivar documents: DocumentsOperations operations - :vartype documents: azure.search.documents.aio.operations.DocumentsOperations - :param endpoint: The endpoint URL of the search service. Required. +class SearchClient(_SearchClientOperationsMixin): + """SearchClient. + + :param endpoint: Service host. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential :param index_name: The name of the index. Required. :type index_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, index_name: str, **kwargs: Any + def __init__( + self, + endpoint: str, + credential: Union[AzureKeyCredential, "AsyncTokenCredential"], + index_name: str, + **kwargs: Any ) -> None: - _endpoint = "{endpoint}/indexes('{indexName}')" - self._config = SearchIndexClientConfiguration(endpoint=endpoint, index_name=index_name, **kwargs) + _endpoint = "{endpoint}" + self._config = SearchClientConfiguration( + endpoint=endpoint, credential=credential, index_name=index_name, **kwargs + ) _policies = kwargs.pop("policies", None) if _policies is None: @@ -57,13 +71,11 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.documents = DocumentsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -71,7 +83,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -86,7 +98,6 @@ def _send_request( request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py new file mode 100644 index 000000000000..34ad0564cab6 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py @@ -0,0 +1,83 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class SearchClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, + endpoint: str, + credential: Union[AzureKeyCredential, "AsyncTokenCredential"], + index_name: str, + **kwargs: Any, + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if index_name is None: + raise ValueError("Parameter 'index_name' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.index_name = index_name + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py deleted file mode 100644 index 74f8d88c8b18..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py +++ /dev/null @@ -1,139 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import List, Union, Dict, Tuple, Any, cast -import asyncio # pylint: disable=do-not-import-asyncio - -from .._generated.models import IndexAction - - -def _flatten_args(args: Tuple[Union[List[Dict[Any, Any]], List[List[Dict[Any, Any]]]], ...]) -> List[Dict]: - if len(args) == 1 and isinstance(args[0], (list, tuple)): - return cast(List[Dict], args[0]) - return cast(List[Dict], args) - - -class IndexDocumentsBatch: - """Represent a batch of update operations for documents in an Azure - Search index. - - Index operations are performed in the order in which they are added - to the batch. - - """ - - def __init__(self) -> None: - self._actions: List[IndexAction] = [] - self._lock = asyncio.Lock() - - def __repr__(self) -> str: - return "".format(len(self.actions))[:1024] - - async def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to upload to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: Documents to upload to an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "upload") - - async def add_delete_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to delete to the Azure search index. - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: Documents to delete from an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "delete") - - async def add_merge_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to merge in to existing documents in the Azure search - index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - - :param documents: Documents to merge into an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "merge") - - async def add_merge_or_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to merge in to existing documents in the Azure search - index, or upload if they do not yet exist. - - This action behaves like *merge* if a document with the given key - already exists in the index. If the document does not exist, it behaves - like *upload* with a new document. - - :param documents: Documents to merge or upload into an Azure search - index. May be a single list of documents, or documents as individual - parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "mergeOrUpload") - - @property - def actions(self) -> List[IndexAction]: - """The list of currently index actions to index. - - :rtype: list[IndexAction] - """ - return list(self._actions) - - async def dequeue_actions(self) -> List[IndexAction]: - """Get the list of currently configured index actions and clear it. - - :return: the list of currently configured index actions - :rtype: list[IndexAction] - """ - async with self._lock: - result = list(self._actions) - self._actions = [] - return result - - async def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction]]) -> None: - """Enqueue a list of index actions to index. - - :param new_actions: the list of index actions to enqueue - :type new_actions: list[IndexAction] - """ - if isinstance(new_actions, IndexAction): - async with self._lock: - self._actions.append(new_actions) - else: - async with self._lock: - self._actions.extend(new_actions) - - async def _extend_batch(self, documents: List[Dict], action_type: str) -> List[IndexAction]: - new_actions = [IndexAction(additional_properties=document, action_type=action_type) for document in documents] - async with self._lock: - self._actions.extend(new_actions) - return new_actions diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/__init__.py similarity index 65% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_operations/__init__.py index 60ca88c85f3c..3d57eee2949f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._knowledge_retrieval_operations import KnowledgeRetrievalOperations # type: ignore +from ._operations import _SearchClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "KnowledgeRetrievalOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py new file mode 100644 index 000000000000..276109af4530 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -0,0 +1,1550 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2 +from ..._operations._operations import ( + build_search_autocomplete_get_request, + build_search_autocomplete_post_request, + build_search_get_document_count_request, + build_search_get_document_request, + build_search_index_request, + build_search_search_get_request, + build_search_search_post_request, + build_search_suggest_get_request, + build_search_suggest_post_request, +) +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.utils import ClientMixinABC +from .._configuration import SearchClientConfiguration + +JSON = MutableMapping[str, Any] +_Unset: Any = object() +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class _SearchClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchClientConfiguration] +): + + @distributed_trace_async + async def get_document_count(self, **kwargs: Any) -> int: + """Queries the number of documents in the index. + + :return: int + :rtype: int + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[int] = kwargs.pop("cls", None) + + _request = build_search_get_document_count_request( + index_name=self._config.index_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(int, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _search_get( # pylint: disable=too-many-locals + self, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + search_text: Optional[str] = None, + include_total_result_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models2.QueryType]] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models2.SearchMode]] = None, + scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, + session_id: Optional[str] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models2.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + answers: Optional[Union[str, _models2.QueryAnswerType]] = None, + captions: Optional[Union[str, _models2.QueryCaptionType]] = None, + semantic_query: Optional[str] = None, + query_rewrites: Optional[Union[str, _models2.QueryRewritesType]] = None, + debug: Optional[Union[str, _models2.QueryDebugMode]] = None, + query_language: Optional[Union[str, _models2.QueryLanguage]] = None, + speller: Optional[Union[str, _models2.QuerySpellerType]] = None, + semantic_fields: Optional[list[str]] = None, + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword include_total_result_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_result_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The list of field names to use for hit highlights. Only searchable + fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: list[str] + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword search_fields: The list of field names to which to scope the full-text search. When + using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of + each fielded search expression take precedence over any field names listed in this parameter. + Default value is None. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. Known values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help to get more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as + retrievable in the schema are included. Default value is None. + :paramtype select: list[str] + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + Default value is None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration: The name of the semantic configuration that lists which fields + should be used for semantic ranking, captions, highlights, and answers. Default value is None. + :paramtype semantic_configuration: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely, or to return partial results (default). Known values are: "partial" and "fail". + Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword answers: This parameter is only valid if the query type is ``semantic``. If set, the + query returns answers extracted from key passages in the highest ranked documents. The number + of answers returned can be configured by appending the pipe character ``|`` followed by the + ``count-`` option after the answers parameter value, such as + ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by + appending the pipe character ``|`` followed by the ``threshold-`` option + after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is + 0.7. The maximum character length of answers can be configured by appending the pipe character + '|' followed by the 'count-', such as + 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". Default value is + None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: This parameter is only valid if the query type is ``semantic``. If set, the + query returns captions extracted from key passages in the highest ranked documents. When + Captions is set to ``extractive``, highlighting is enabled by default, and can be configured by + appending the pipe character ``|`` followed by the ``highlight-`` option, such as + ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of captions + can be configured by appending the pipe character '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. Known values are: "none" and + "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword query_rewrites: When QueryRewrites is set to ``generative``, the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword debug: Enables a debugging tool that can be used to further explore your search + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword query_language: The language of the query. Known values are: "none", "en-us", "en-gb", + "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", + "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", + "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", + "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", + "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", + "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". Default + value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword speller: Improve search recall by spell-correcting individual search query terms. + Known values are: "none" and "lexicon". Default value is None. + :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword semantic_fields: The list of field names used for semantic ranking. Default value is + None. + :paramtype semantic_fields: list[str] + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchDocumentsResult] = kwargs.pop("cls", None) + + _request = build_search_search_get_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + enable_elevated_read=enable_elevated_read, + search_text=search_text, + include_total_result_count=include_total_result_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + search_fields=search_fields, + search_mode=search_mode, + scoring_statistics=scoring_statistics, + session_id=session_id, + select=select, + skip=skip, + top=top, + semantic_configuration=semantic_configuration, + semantic_error_handling=semantic_error_handling, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + answers=answers, + captions=captions, + semantic_query=semantic_query, + query_rewrites=query_rewrites, + debug=debug, + query_language=query_language, + speller=speller, + semantic_fields=semantic_fields, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _search_post( # pylint: disable=too-many-locals + self, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + content_type: str = "application/json", + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models2.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models2.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models2.SearchMode]] = None, + query_language: Optional[Union[str, _models2.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models2.QuerySpellerType]] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models2.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models2.QueryAnswerType]] = None, + captions: Optional[Union[str, _models2.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models2.QueryRewritesType]] = None, + semantic_fields: Optional[list[str]] = None, + vector_queries: Optional[list[_models2.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models2.VectorFilterMode]] = None, + hybrid_search: Optional[_models2.HybridSearch] = None, + **kwargs: Any + ) -> _models2.SearchDocumentsResult: ... + @overload + async def _search_post( + self, + body: JSON, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SearchDocumentsResult: ... + @overload + async def _search_post( + self, + body: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SearchDocumentsResult: ... + + @distributed_trace_async + async def _search_post( # pylint: disable=too-many-locals + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, _models2.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models2.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, _models2.SearchMode]] = None, + query_language: Optional[Union[str, _models2.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models2.QuerySpellerType]] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models2.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models2.QueryAnswerType]] = None, + captions: Optional[Union[str, _models2.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models2.QueryRewritesType]] = None, + semantic_fields: Optional[list[str]] = None, + vector_queries: Optional[list[_models2.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models2.VectorFilterMode]] = None, + hybrid_search: Optional[_models2.HybridSearch] = None, + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :keyword include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: list[str] + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. Default value is None. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". Default value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specifies the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". Default value is None. + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields + marked as retrievable in the schema are included. Default value is None. + :paramtype select: list[str] + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. Default value is + None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration_name: The name of a semantic configuration that will be used + when processing documents for queries of type semantic. Default value is None. + :paramtype semantic_configuration_name: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword answers: A value that specifies whether answers should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + Default value is None. + :paramtype semantic_fields: list[str] + :keyword vector_queries: The query parameters for vector and hybrid search queries. Default + value is None. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". Default value is None. + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default + value is None. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchDocumentsResult] = kwargs.pop("cls", None) + + if body is _Unset: + body = { + "answers": answers, + "captions": captions, + "count": include_total_count, + "debug": debug, + "facets": facets, + "filter": filter, + "highlight": highlight_fields, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "hybridSearch": hybrid_search, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "queryLanguage": query_language, + "queryRewrites": query_rewrites, + "queryType": query_type, + "scoringParameters": scoring_parameters, + "scoringProfile": scoring_profile, + "scoringStatistics": scoring_statistics, + "search": search_text, + "searchFields": search_fields, + "searchMode": search_mode, + "select": select, + "semanticConfiguration": semantic_configuration_name, + "semanticErrorHandling": semantic_error_handling, + "semanticFields": semantic_fields, + "semanticMaxWaitInMilliseconds": semantic_max_wait_in_milliseconds, + "semanticQuery": semantic_query, + "sessionId": session_id, + "skip": skip, + "speller": query_speller, + "top": top, + "vectorFilterMode": vector_filter_mode, + "vectorQueries": vector_queries, + } + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_search_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + enable_elevated_read=enable_elevated_read, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_document( + self, + key: str, + *, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + selected_fields: Optional[list[str]] = None, + **kwargs: Any + ) -> _models2.LookupDocument: + """Retrieves a document from the index. + + :param key: The key of the document to retrieve. Required. + :type key: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool + :keyword selected_fields: List of field names to retrieve for the document; Any field not + retrieved will be missing from the returned document. Default value is None. + :paramtype selected_fields: list[str] + :return: LookupDocument. The LookupDocument is compatible with MutableMapping + :rtype: ~azure.search.documents.models.LookupDocument + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.LookupDocument] = kwargs.pop("cls", None) + + _request = build_search_get_document_request( + key=key, + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + enable_elevated_read=enable_elevated_read, + selected_fields=selected_fields, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.LookupDocument, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _suggest_get( + self, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models2._models.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestions query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestions queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestions query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword search_fields: The list of field names to search for the specified search text. Target + fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword select: The list of fields to retrieve. If unspecified, only the key field will be + included in the results. Default value is None. + :paramtype select: list[str] + :keyword top: The number of suggestions to retrieve. The value must be a number between 1 and + 100. The default is 5. Default value is None. + :paramtype top: int + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.SuggestDocumentsResult] = kwargs.pop("cls", None) + + _request = build_search_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _suggest_post( + self, + *, + search_text: str, + suggester_name: str, + content_type: str = "application/json", + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models2._models.SuggestDocumentsResult: ... + @overload + async def _suggest_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.SuggestDocumentsResult: ... + @overload + async def _suggest_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.SuggestDocumentsResult: ... + + @distributed_trace_async + async def _suggest_post( # pylint: disable=too-many-locals + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + search_text: str = _Unset, + suggester_name: str = _Unset, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models2._models.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. Default value is None. + :paramtype select: list[str] + :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. Default value is None. + :paramtype top: int + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2._models.SuggestDocumentsResult] = kwargs.pop("cls", None) + + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "search": search_text, + "searchFields": search_fields, + "select": select, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_suggest_post_request( + index_name=self._config.index_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _index( + self, batch: _models2.IndexDocumentsBatch, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.IndexDocumentsResult: ... + @overload + async def _index( + self, batch: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.IndexDocumentsResult: ... + @overload + async def _index( + self, batch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.IndexDocumentsResult: ... + + @distributed_trace_async + async def _index( + self, batch: Union[_models2.IndexDocumentsBatch, JSON, IO[bytes]], **kwargs: Any + ) -> _models2._models.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, + JSON, IO[bytes] Required. + :type batch: ~azure.search.documents.models.IndexDocumentsBatch or JSON or IO[bytes] + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2._models.IndexDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(batch, (IOBase, bytes)): + _content = batch + else: + _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_request( + index_name=self._config.index_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 207]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.IndexDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _autocomplete_get( + self, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, _models2.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models2._models.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :keyword search_text: The incomplete term which should be auto-completed. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The list of field names to consider when querying for auto-completed + terms. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.AutocompleteResult] = kwargs.pop("cls", None) + + _request = build_search_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _autocomplete_post( + self, + *, + search_text: str, + suggester_name: str, + content_type: str = "application/json", + autocomplete_mode: Optional[Union[str, _models2.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models2._models.AutocompleteResult: ... + @overload + async def _autocomplete_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.AutocompleteResult: ... + @overload + async def _autocomplete_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2._models.AutocompleteResult: ... + + @distributed_trace_async + async def _autocomplete_post( # pylint: disable=too-many-locals + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + search_text: str = _Unset, + suggester_name: str = _Unset, + autocomplete_mode: Optional[Union[str, _models2.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[list[str]] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models2._models.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text on which to base autocomplete results. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will autocomplete terms even + if there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: list[str] + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2._models.AutocompleteResult] = kwargs.pop("cls", None) + + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "autocompleteMode": autocomplete_mode, + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "search": search_text, + "searchFields": search_fields, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_autocomplete_post_request( + index_name=self._config.index_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py similarity index 54% rename from sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index e39a7f24b04f..3ac022a67b93 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -1,134 +1,237 @@ -# ------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- -from typing import cast, List, Union, Any, Optional, Dict, MutableMapping +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Dict, List, Optional, Union, cast -from azure.core.rest import HttpRequest, AsyncHttpResponse -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential +from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator, ReturnType from azure.core.tracing.decorator_async import distributed_trace_async -from ._paging import AsyncSearchItemPaged, AsyncSearchPageIterator -from .._utils import get_authentication_policy, get_answer_query, get_rewrites_query -from .._generated.aio import SearchIndexClient -from .._generated.models import ( - AutocompleteMode, - AutocompleteRequest, - IndexAction, - IndexBatch, - IndexingResult, - QueryAnswerType, - QueryCaptionType, - QueryLanguage, - QuerySpellerType, - QueryType, - SearchMode, - ScoringStatistics, - VectorFilterMode, - VectorQuery, - SemanticErrorMode, - QueryRewritesType, - QueryDebugMode, - SuggestRequest, - HybridSearch, + +from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated +from ..._operations._patch import ( + _build_search_request, + _convert_search_result, + _pack_continuation_token, + _unpack_continuation_token, ) -from .._search_documents_error import RequestEntityTooLargeError -from .._index_documents_batch import IndexDocumentsBatch -from .._queries import AutocompleteQuery, SearchQuery, SuggestQuery -from .._api_versions import DEFAULT_VERSION -from .._headers_mixin import HeadersMixin -from .._version import SDK_MONIKER - - -class SearchClient(HeadersMixin): - """A client to interact with an existing Azure search index. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param index_name: The name of the index to connect to - :type index_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_authentication_async.py - :start-after: [START authenticate_search_client_with_api_key_async] - :end-before: [END authenticate_search_client_with_api_key_async] - :language: python - :dedent: 4 - :caption: Creating the SearchClient with an API key. +from ...models._patch import RequestEntityTooLargeError +from ... import models as _models + + +def _ensure_response(f): + """Decorator to ensure response is fetched before accessing metadata. + :param f: The function to wrap. + :type f: Callable + :return: The wrapped function. + :rtype: Callable """ - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: SearchIndexClient - - def __init__( - self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._index_documents_batch = IndexDocumentsBatch() - self._endpoint: str = endpoint - self._index_name: str = index_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs + async def wrapper(self, *args, **kw): + # pylint:disable=protected-access + if self._current_page is None: + self._response = await self._get_next(self.continuation_token) + self.continuation_token, self._current_page = await self._extract_data(self._response) + return await f(self, *args, **kw) + + return wrapper + + +class AsyncSearchPageIterator(AsyncPageIterator): + """An async iterator over search result pages.""" + + def __init__(self, client, initial_request: _models.SearchRequest, kwargs, continuation_token=None) -> None: + super(AsyncSearchPageIterator, self).__init__( + get_next=self._get_next_cb, + extract_data=self._extract_data_cb, + continuation_token=continuation_token, + ) + self._client = client + self._initial_request = initial_request + self._kwargs = kwargs + self._facets: Optional[Dict[str, List[Dict[str, Any]]]] = None + self._api_version = kwargs.get("api_version", "2025-11-01-preview") + + async def _get_next_cb(self, continuation_token): + if continuation_token is None: + return await self._client._search_post( # pylint:disable=protected-access + body=self._initial_request, **self._kwargs ) - def __repr__(self) -> str: - return "".format(repr(self._endpoint), repr(self._index_name))[:1024] + _next_link, next_page_request = _unpack_continuation_token(continuation_token) + return await self._client._search_post( # pylint:disable=protected-access + body=next_page_request, **self._kwargs + ) + + async def _extract_data_cb(self, response: _models.SearchDocumentsResult): + continuation_token = _pack_continuation_token(response, api_version=self._api_version) + results = [_convert_search_result(r) for r in response.results] + return continuation_token, results + + @_ensure_response + async def get_facets(self) -> Optional[Dict[str, Any]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + if response.facets is not None and self._facets is None: + self._facets = { + k: [x.as_dict() if hasattr(x, "as_dict") else dict(x) for x in v] for k, v in response.facets.items() + } + return self._facets + + @_ensure_response + async def get_coverage(self) -> Optional[float]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.coverage + + @_ensure_response + async def get_count(self) -> Optional[int]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.count + + @_ensure_response + async def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.answers + + @_ensure_response + async def get_debug_info(self) -> Optional[_models.DebugInfo]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.debug_info + + +class AsyncSearchItemPaged(AsyncItemPaged[ReturnType]): + """An async pageable list of search results.""" + + def __init__(self, *args, **kwargs) -> None: + super(AsyncSearchItemPaged, self).__init__(*args, **kwargs) + self._first_page_iterator_instance: Optional[AsyncSearchPageIterator] = None + + def _first_iterator_instance(self) -> AsyncSearchPageIterator: + if self._first_page_iterator_instance is None: + self._first_page_iterator_instance = cast(AsyncSearchPageIterator, self.by_page()) + return self._first_page_iterator_instance + + async def __anext__(self) -> ReturnType: + if self._page_iterator is None: + self._page_iterator = self._first_iterator_instance() + return await self.__anext__() + if self._page is None: + # Let it raise StopAsyncIteration + self._page = await self._page_iterator.__anext__() + return await self.__anext__() + try: + return await self._page.__anext__() + except StopAsyncIteration: + self._page = None + return await self.__anext__() - async def close(self) -> None: - """Close the session. + async def get_facets(self) -> Optional[Dict]: + """Return any facet results if faceting was requested. - :return: None - :rtype: None + :return: facet results + :rtype: dict or None """ - return await self._client.close() + return cast(Dict, await self._first_iterator_instance().get_facets()) - @distributed_trace_async - async def get_document_count(self, **kwargs: Any) -> int: - """Return the number of documents in the Azure search index. + async def get_coverage(self) -> float: + """Return the coverage percentage, if `minimum_coverage` was + specificied for the query. + + :return: coverage percentage + :rtype: float + """ + return cast(float, await self._first_iterator_instance().get_coverage()) - :return: The count of documents in the index + async def get_count(self) -> int: + """Return the count of results if `include_total_count` was + set for the query. + + :return: count of results :rtype: int """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return int(await self._client.documents.count(**kwargs)) + return cast(int, await self._first_iterator_instance().get_count()) + + async def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + """Return semantic answers. Only included if the semantic ranker is used + and answers are requested in the search query via the query_answer parameter. + + :return: answers + :rtype: list[~azure.search.documents.models.QueryAnswerResult] or None + """ + return cast(Optional[List[_models.QueryAnswerResult]], await self._first_iterator_instance().get_answers()) + + async def get_debug_info(self) -> _models.DebugInfo: + """Return the debug information for the query. + + :return: the debug information for the query + :rtype: ~azure.search.documents.models.DebugInfo + """ + return cast(_models.DebugInfo, await self._first_iterator_instance().get_debug_info()) + + +class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): + """Async SearchClient operations mixin customizations.""" @distributed_trace_async - async def get_document(self, key: str, selected_fields: Optional[List[str]] = None, **kwargs: Any) -> Dict: - """Retrieve a document from the Azure search index by its key. + async def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + """Specify a document operations to perform as a batch. + + :param batch: A batch of document operations to perform. + :type batch: ~azure.search.documents.models.IndexDocumentsBatch + :return: List of IndexingResult + :rtype: list[IndexingResult] - :param key: The primary key value for the document to retrieve - :type key: str - :param selected_fields: an allow-list of fields to include in the results - :type selected_fields: list[str] - :return: The document that matches the specified key - :rtype: dict + :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. + """ + return await self._index_documents_actions(batch=batch, **kwargs) + + async def _index_documents_actions( + self, batch: _models.IndexDocumentsBatch, **kwargs: Any + ) -> List[_models.IndexingResult]: + error_map = {413: RequestEntityTooLargeError} + + try: + batch_response = await self._index(batch=batch, error_map=error_map, **kwargs) + typed_result = [cast(_models.IndexingResult, x) for x in batch_response.results] + return typed_result + except RequestEntityTooLargeError: + if len(batch.actions) == 1: + raise + pos = round(len(batch.actions) / 2) + batch_response_first_half = await self._index_documents_actions( + batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs + ) + if batch_response_first_half: + result_first_half = batch_response_first_half + else: + result_first_half = [] + batch_response_second_half = await self._index_documents_actions(actions=batch.actions[pos:], **kwargs) + if batch_response_second_half: + result_second_half = batch_response_second_half + else: + result_second_half = [] + result_first_half.extend(result_second_half) + return result_first_half + + async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Upload documents to the Azure search index. + + An upload action is similar to an "upsert" where the document will be + inserted if it is new and updated/replaced if it exists. All fields are + replaced in the update case. + + :param documents: A list of documents to upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] .. admonition:: Example: @@ -137,11 +240,96 @@ async def get_document(self, key: str, selected_fields: Optional[List[str]] = No :end-before: [END get_document_async] :language: python :dedent: 4 - :caption: Get a specific document from the search index. + :caption: Upload new documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_upload_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return result + + async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Delete documents from the Azure search index. + + Delete removes the specified documents from the index. Any field you + specify in a delete operation, other than the key field, will be ignored. + If you want to remove a field from a document, use merge instead and + set the field explicitly to None. + + :param documents: A list of documents to delete. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_documents_crud_async.py + :start-after: [START delete_document_async] + :end-before: [END delete_document_async] + :language: python + :dedent: 4 + :caption: Delete documents from an index """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.documents.get(key=key, selected_fields=selected_fields, **kwargs) - return cast(dict, result) + batch = _models.IndexDocumentsBatch() + batch.add_delete_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return result + + async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge documents in the Azure search index. + + Merge updates an existing document with the specified fields. If the + document doesn't exist, the merge will fail. Any field you specify in + a merge will replace the existing field in the document. This also + applies to collections of primitive and complex types. + + :param documents: A list of documents to merge. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_documents_crud_async.py + :start-after: [START merge_document_async] + :end-before: [END merge_document_async] + :language: python + :dedent: 4 + :caption: Merge documents in an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return result + + async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge or upload documents to the Azure search index. + + Merge or upload behaves like merge if a document with the given key + already exists in the index. If the document does not exist, it behaves + like upload with a new document. + + :param documents: A list of documents to merge or upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_documents_crud_async.py + :start-after: [START merge_or_upload_document_async] + :end-before: [END merge_or_upload_document_async] + :language: python + :dedent: 4 + :caption: Merge or upload documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_or_upload_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return result @distributed_trace_async async def search( @@ -156,39 +344,39 @@ async def search( highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, order_by: Optional[List[str]] = None, - query_type: Optional[Union[str, QueryType]] = None, + query_type: Optional[Union[str, _models.QueryType]] = None, scoring_parameters: Optional[List[str]] = None, scoring_profile: Optional[str] = None, semantic_query: Optional[str] = None, search_fields: Optional[List[str]] = None, - search_mode: Optional[Union[str, SearchMode]] = None, - query_language: Optional[Union[str, QueryLanguage]] = None, - query_speller: Optional[Union[str, QuerySpellerType]] = None, - query_answer: Optional[Union[str, QueryAnswerType]] = None, + search_mode: Optional[Union[str, _models.SearchMode]] = None, + query_language: Optional[Union[str, _models.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models.QuerySpellerType]] = None, + query_answer: Optional[Union[str, _models.QueryAnswerType]] = None, query_answer_count: Optional[int] = None, query_answer_threshold: Optional[float] = None, - query_caption: Optional[Union[str, QueryCaptionType]] = None, + query_caption: Optional[Union[str, _models.QueryCaptionType]] = None, query_caption_highlight_enabled: Optional[bool] = None, semantic_fields: Optional[List[str]] = None, semantic_configuration_name: Optional[str] = None, select: Optional[List[str]] = None, skip: Optional[int] = None, top: Optional[int] = None, - scoring_statistics: Optional[Union[str, ScoringStatistics]] = None, + scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, session_id: Optional[str] = None, - vector_queries: Optional[List[VectorQuery]] = None, - vector_filter_mode: Optional[Union[str, VectorFilterMode]] = None, - semantic_error_mode: Optional[Union[str, SemanticErrorMode]] = None, + vector_queries: Optional[List[_models.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models.VectorFilterMode]] = None, + semantic_error_mode: Optional[Union[str, _models.SemanticErrorMode]] = None, semantic_max_wait_in_milliseconds: Optional[int] = None, - query_rewrites: Optional[Union[str, QueryRewritesType]] = None, + query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, query_rewrites_count: Optional[int] = None, - debug: Optional[Union[str, QueryDebugMode]] = None, - hybrid_search: Optional[HybridSearch] = None, - x_ms_query_source_authorization: Optional[str] = None, - x_ms_enable_elevated_read: Optional[bool] = None, - **kwargs + debug: Optional[Union[str, _models.QueryDebugMode]] = None, + hybrid_search: Optional[_models.HybridSearch] = None, + query_source_authorization: Optional[str] = None, + enable_elevated_read: Optional[bool] = None, + **kwargs: Any, ) -> AsyncSearchItemPaged[Dict]: - # pylint:disable=too-many-locals, disable=redefined-builtin + # pylint:disable=too-many-locals """Search the Azure search index for documents. :param str search_text: A full-text search query expression; Use "*" or omit this parameter to @@ -210,12 +398,13 @@ async def search( must be covered by a search query in order for the query to be reported as a success. This parameter can be useful for ensuring search availability even for services with only one replica. The default is 100. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each expression can be either a field name or a call to either the geo.distance() or the search.score() functions. Each expression can be followed by asc to indicate ascending, and desc to indicate descending. The default is ascending order. Ties will be broken by the match scores of documents. If no OrderBy is specified, the default sort order is descending by document match score. There can be at most 32 $orderby clauses. + :paramtype order_by: list[str] :keyword query_type: A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: 'simple', 'full', "semantic". @@ -230,9 +419,11 @@ async def search( semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there is a need to use different queries between the base retrieval and ranking phase, and the L2 semantic phase. - :keyword list[str] search_fields: The list of field names to which to scope the full-text search. When - using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of - each fielded search expression take precedence over any field names listed in this parameter. + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. + :paramtype search_fields: list[str] :keyword search_mode: A value that specifies whether any or all of the search terms must be matched in order to count the document as a match. Possible values include: 'any', 'all'. :paramtype search_mode: str or ~azure.search.documents.models.SearchMode @@ -253,8 +444,7 @@ async def search( Possible values include: "none", "extractive". :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. - Configures the number of answers returned. Default count is 1. + query answer is 'extractive'. Configures the number of answers returned. Default count is 1. :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the @@ -264,12 +454,14 @@ async def search( :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when query caption is set to 'extractive'. Determines whether highlighting is enabled. Defaults to 'true'. - :keyword list[str] semantic_fields: The list of field names used for semantic search. + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + :paramtype semantic_fields: list[str] :keyword semantic_configuration_name: The name of the semantic configuration that will be used when processing documents for queries of type semantic. :paramtype semantic_configuration_name: str - :keyword list[str] select: The list of fields to retrieve. If unspecified, all fields marked as retrievable + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included. + :paramtype select: list[str] :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. If you need to scan documents in sequence, but cannot use $skip due to this limitation, consider using $orderby on a totally-ordered key and $filter with a range query instead. @@ -308,22 +500,22 @@ async def search( results. Known values are: "disabled", "speller", "semantic", and "all". :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode :keyword vector_queries: The query parameters for vector and hybrid search queries. - :paramtype vector_queries: list[VectorQuery] + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] :keyword vector_filter_mode: Determines whether or not filters are applied before or after the vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". - :paramtype vector_filter_mode: str or VectorFilterMode + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode :keyword hybrid_search: The query parameters to configure hybrid search behaviors. :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - :keyword x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype x_ms_query_source_authorization: str - :keyword x_ms_enable_elevated_read: A value that enables elevated read that bypass document level - permission checks for the query operation. Default value is None. - :paramtype x_ms_enable_elevated_read: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword enable_elevated_read: A value that enables elevated read that bypass document level + permission checks for the query operation. Default value is None. + :paramtype enable_elevated_read: bool :return: A list of documents (dicts) matching the specified search criteria. :return: List of search results. - :rtype: AsyncSearchItemPaged[dict] + :rtype: AsyncSearchItemPaged[dict] .. admonition:: Example: @@ -352,114 +544,105 @@ async def search( :dedent: 4 :caption: Get search result facets. """ - include_total_result_count = include_total_count - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - answers = get_answer_query(query_answer, query_answer_count, query_answer_threshold) - rewrites = get_rewrites_query(query_rewrites, query_rewrites_count) - captions = ( - query_caption - if not query_caption_highlight_enabled - else "{}|highlight-{}".format(query_caption, query_caption_highlight_enabled) - ) - semantic_configuration = semantic_configuration_name - - query = SearchQuery( + # Build the search request using shared helper + search_request = _build_search_request( search_text=search_text, - include_total_result_count=include_total_result_count, + include_total_count=include_total_count, facets=facets, - filter=filter_arg, + filter=filter, highlight_fields=highlight_fields, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, + order_by=order_by, query_type=query_type, scoring_parameters=scoring_parameters, scoring_profile=scoring_profile, semantic_query=semantic_query, - search_fields=search_fields_str, + search_fields=search_fields, search_mode=search_mode, query_language=query_language, - speller=query_speller, - answers=answers, - captions=captions, - semantic_fields=",".join(semantic_fields) if semantic_fields else None, - semantic_configuration=semantic_configuration, - select=select if isinstance(select, str) else None, + query_speller=query_speller, + query_answer=query_answer, + query_answer_count=query_answer_count, + query_answer_threshold=query_answer_threshold, + query_caption=query_caption, + query_caption_highlight_enabled=query_caption_highlight_enabled, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, skip=skip, top=top, - session_id=session_id, scoring_statistics=scoring_statistics, + session_id=session_id, vector_queries=vector_queries, vector_filter_mode=vector_filter_mode, - semantic_error_handling=semantic_error_mode, + semantic_error_mode=semantic_error_mode, semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, - query_rewrites=rewrites, + query_rewrites=query_rewrites, + query_rewrites_count=query_rewrites_count, debug=debug, hybrid_search=hybrid_search, ) - if isinstance(select, list): - query.select(select) - if isinstance(order_by, list): - query.order_by(order_by) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["x_ms_query_source_authorization"] = x_ms_query_source_authorization - kwargs["x_ms_enable_elevated_read"] = x_ms_enable_elevated_read - kwargs["api_version"] = self._api_version - return AsyncSearchItemPaged(self._client, query, kwargs, page_iterator_class=AsyncSearchPageIterator) + + # Create kwargs for the search_post call + search_kwargs = dict(kwargs) + if query_source_authorization is not None: + search_kwargs["query_source_authorization"] = query_source_authorization + if enable_elevated_read is not None: + search_kwargs["enable_elevated_read"] = enable_elevated_read + + return AsyncSearchItemPaged(self, search_request, search_kwargs, page_iterator_class=AsyncSearchPageIterator) @distributed_trace_async - async def suggest( + async def autocomplete( self, search_text: str, suggester_name: str, *, + mode: Optional[Union[str, _models.AutocompleteMode]] = None, filter: Optional[str] = None, use_fuzzy_matching: Optional[bool] = None, highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search suggestion results from the Azure search index. + **kwargs: Any, + ) -> List[_models.AutocompleteItem]: + """Autocomplete incomplete search terms based on input text and matching terms in the index. - :param str search_text: Required. The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. - :param str suggester_name: Required. The name of the suggester as specified in the suggesters + :param str search_text: The search text on which to base autocomplete results. + :param str suggester_name: The name of the suggester as specified in the suggesters collection that's part of the index definition. - :keyword str filter: An OData expression that filters the documents considered for suggestions. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestions - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestions queries are slower and - consume more resources. + :keyword mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. + Use 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while + producing auto-completed terms. Known values are: "oneTerm", "twoTerms", and + "oneTermWithContext". + :paramtype mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword str filter: An OData expression that filters the documents used to produce completed + terms for the Autocomplete result. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + highlightPreTag. If omitted, hit highlighting is disabled. :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestions query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :keyword list[str] search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :keyword list[str] select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :keyword int top: The number of suggestions to retrieve. The value must be a number between 1 and - 100. The default is 5. - :return: List of suggestion results. - :rtype: list[dict] + highlightPostTag. If omitted, hit highlighting is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: list[str] + :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. + :return: List of autocomplete results. + :rtype: list[dict[str, Any]] .. admonition:: Example: @@ -468,80 +651,77 @@ async def suggest( :end-before: [END suggest_query_async] :language: python :dedent: 4 - :caption: Get search suggestions. + :caption: Get autocomplete suggestions. """ - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = SuggestQuery( + # Call the generated _autocomplete_post method + response = await self._autocomplete_post( search_text=search_text, suggester_name=suggester_name, - filter=filter_arg, + autocomplete_mode=mode, + filter=filter, use_fuzzy_matching=use_fuzzy_matching, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - search_fields=search_fields_str, - select=select if isinstance(select, str) else None, + search_fields=search_fields, top=top, + **kwargs, ) - if isinstance(select, list): - query.select(select) - if isinstance(order_by, list): - query.order_by(order_by) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(SuggestRequest, query.request) - response = await self._client.documents.suggest_post(suggest_request=request, **kwargs) + assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results + return response.results @distributed_trace_async - async def autocomplete( + async def suggest( self, search_text: str, suggester_name: str, *, - mode: Optional[Union[str, AutocompleteMode]] = None, filter: Optional[str] = None, use_fuzzy_matching: Optional[bool] = None, highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, search_fields: Optional[List[str]] = None, + select: Optional[List[str]] = None, top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search auto-completion results from the Azure search index. + **kwargs: Any, + ) -> List[_models.SuggestResult]: + """Get search suggestions for documents in the Azure search index. - :param str search_text: The search text on which to base autocomplete results. + :param str search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. :param str suggester_name: The name of the suggester as specified in the suggesters collection that's part of the index definition. - :keyword mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Possible values include: 'oneTerm', 'twoTerms', 'oneTermWithContext'. - :paramtype mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword str filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. + :keyword str filter: An OData expression that filters the documents considered for suggestions. :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will find terms even if + suggestion query. Default is false. When set to true, the query will find suggestions even if there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are slower and consume more resources. :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. This parameter can be useful for ensuring search availability even for services with only one replica. The default is 80. - :keyword list[str] search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :return: List of auto-completion results. - :rtype: list[Dict] + :keyword list[str] order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :keyword list[str] search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. + :keyword list[str] select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. + :keyword int top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. + :return: List of suggestion results. + :rtype: list[dict[str, Any]] .. admonition:: Example: @@ -550,199 +730,38 @@ async def autocomplete( :end-before: [END autocomplete_query_async] :language: python :dedent: 4 - :caption: Get a auto-completions. + :caption: Get search suggestions. """ - autocomplete_mode = mode - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = AutocompleteQuery( + # Call the generated _suggest_post method + response = await self._suggest_post( search_text=search_text, suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter_arg, + filter=filter, use_fuzzy_matching=use_fuzzy_matching, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, minimum_coverage=minimum_coverage, - search_fields=search_fields_str, + order_by=order_by, + search_fields=search_fields, + select=select, top=top, + **kwargs, ) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(AutocompleteRequest, query.request) - response = await self._client.documents.autocomplete_post(autocomplete_request=request, **kwargs) assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - # pylint:disable=client-method-missing-tracing-decorator-async - async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Upload documents to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: A list of documents to upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_documents_crud_async.py - :start-after: [START upload_document_async] - :end-before: [END upload_document_async] - :language: python - :dedent: 4 - :caption: Upload new documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator-async, delete-operation-wrong-return-type - async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Delete documents from the Azure search index - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: A list of documents to delete. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: + return response.results - .. literalinclude:: ../samples/async_samples/sample_documents_crud_async.py - :start-after: [START delete_document_async] - :end-before: [END delete_document_async] - :language: python - :dedent: 4 - :caption: Delete existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_delete_actions(documents) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) +__all__: list[str] = [ + "_SearchClientOperationsMixin", + "AsyncSearchItemPaged", +] # Add all objects you want publicly available to users at this package level - # pylint:disable=client-method-missing-tracing-decorator-async - async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - :param documents: A list of documents to merge. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_documents_crud_async.py - :start-after: [START merge_document_async] - :end-before: [END merge_document_async] - :language: python - :dedent: 4 - :caption: Merge fields into existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_merge_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator-async - async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index, - or upload them if they do not yet exist. - - This action behaves like `merge_documents` if a document with the given - key already exists in the index. If the document does not exist, it - behaves like `upload_documents` with a new document. - - :param documents: A list of documents to merge or upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - """ - batch = IndexDocumentsBatch() - batch.add_merge_or_upload_actions(documents) +def patch_sdk(): + """Do not remove from this file. - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - @distributed_trace_async - async def index_documents(self, batch: IndexDocumentsBatch, **kwargs: Any) -> List[IndexingResult]: - """Specify a document operations to perform as a batch. - - :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: List of IndexingResult - :rtype: list[IndexingResult] - - :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. - """ - return await self._index_documents_actions(actions=batch.actions, **kwargs) - - async def _index_documents_actions(self, actions: List[IndexAction], **kwargs: Any) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) - try: - batch_response = await self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) - except RequestEntityTooLargeError: - if len(actions) == 1: - raise - pos = round(len(actions) / 2) - batch_response_first_half = await self._index_documents_actions(actions=actions[:pos], **kwargs) - if batch_response_first_half: - result_first_half = batch_response_first_half - else: - result_first_half = [] - batch_response_second_half = await self._index_documents_actions(actions=actions[pos:], **kwargs) - if batch_response_second_half: - result_second_half = batch_response_second_half - else: - result_second_half = [] - result_first_half.extend(result_second_half) - return result_first_half - - async def __aenter__(self) -> "SearchClient": - await self._client.__aenter__() # pylint: disable=no-member - return self - - async def __aexit__(self, *args) -> None: - await self._client.__aexit__(*args) - - @distributed_trace_async - async def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> AsyncHttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return await self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py deleted file mode 100644 index 51003804f4c1..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py +++ /dev/null @@ -1,164 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import List, Dict, Optional, cast, MutableMapping, Any - -from azure.core.paging import ReturnType -from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator -from .._generated.models import QueryAnswerResult, SearchDocumentsResult, DebugInfo -from .._paging import ( - convert_search_result, - pack_continuation_token, - unpack_continuation_token, -) -from .._api_versions import DEFAULT_VERSION - - -class AsyncSearchItemPaged(AsyncItemPaged[ReturnType]): - """A pageable list of search results.""" - - def __init__(self, *args, **kwargs) -> None: - super(AsyncSearchItemPaged, self).__init__(*args, **kwargs) - self._first_page_iterator_instance: Optional[AsyncSearchPageIterator] = None - - async def __anext__(self) -> ReturnType: - if self._page_iterator is None: - self._page_iterator = self.by_page() - self._first_page_iterator_instance = cast(AsyncSearchPageIterator, self._page_iterator) - return await self.__anext__() - if self._page is None: - # Let it raise StopAsyncIteration - self._page = await self._page_iterator.__anext__() - return await self.__anext__() - try: - return await self._page.__anext__() - except StopAsyncIteration: - self._page = None - return await self.__anext__() - - def _first_iterator_instance(self) -> "AsyncSearchPageIterator": - if self._first_page_iterator_instance is None: - self._page_iterator = cast(AsyncSearchPageIterator, self.by_page()) - self._first_page_iterator_instance = self._page_iterator - return self._first_page_iterator_instance - - async def get_facets(self) -> Optional[Dict]: - """Return any facet results if faceting was requested. - - :return: Facet results. - :rtype: dict - """ - return cast(Dict, await self._first_iterator_instance().get_facets()) - - async def get_coverage(self) -> float: - """Return the coverage percentage, if `minimum_coverage` was - specificied for the query. - - :return: Coverage percentage. - :rtype: float - """ - return cast(float, await self._first_iterator_instance().get_coverage()) - - async def get_count(self) -> int: - """Return the count of results if `include_total_count` was - set for the query. - - :return: Count of results. - :rtype: int - """ - return cast(int, await self._first_iterator_instance().get_count()) - - async def get_answers(self) -> Optional[List[QueryAnswerResult]]: - """Return semantic answers. Only included if the semantic ranker is used - and answers are requested in the search query via the query_answer parameter. - - :return: Answers. - :rtype: list[~azure.search.documents.models.QueryAnswerResult] - """ - return cast(List[QueryAnswerResult], await self._first_iterator_instance().get_answers()) - - async def get_debug_info(self) -> DebugInfo: - """Return the debug information for the query. - - :return: the debug information for the query. - :rtype: ~azure.search.documents.models.DebugInfo - """ - return cast(DebugInfo, await self._first_iterator_instance().get_debug_info()) - - -# The pylint error silenced below seems spurious, as the inner wrapper does, in -# fact, become a method of the class when it is applied. -def _ensure_response(f): - # pylint:disable=protected-access - async def wrapper(self, *args, **kw): - if self._current_page is None: - self._response = await self._get_next(self.continuation_token) - self.continuation_token, self._current_page = await self._extract_data(self._response) - return await f(self, *args, **kw) - - return wrapper - - -class AsyncSearchPageIterator(AsyncPageIterator[ReturnType]): - """An iterator of search results.""" - - def __init__(self, client, initial_query, kwargs, continuation_token=None) -> None: - super(AsyncSearchPageIterator, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token, - ) - self._client = client - self._initial_query = initial_query - self._kwargs = kwargs - self._facets: Optional[MutableMapping[str, List[MutableMapping[str, Any]]]] = None - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - - async def _get_next_cb(self, continuation_token): - if continuation_token is None: - return await self._client.documents.search_post(search_request=self._initial_query.request, **self._kwargs) - - _next_link, next_page_request = unpack_continuation_token(continuation_token) - - return await self._client.documents.search_post(search_request=next_page_request, **self._kwargs) - - async def _extract_data_cb(self, response): - continuation_token = pack_continuation_token(response, api_version=self._api_version) - results = [convert_search_result(r) for r in response.results] - return continuation_token, results - - @_ensure_response - async def get_facets(self) -> Optional[MutableMapping[str, Any]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - facets = response.facets - if facets is not None and self._facets is None: - assert facets.items() is not None # Hint for mypy - self._facets = {k: [x.as_dict() for x in v] for k, v in facets.items()} - return self._facets - - @_ensure_response - async def get_coverage(self) -> float: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(float, response.coverage) - - @_ensure_response - async def get_count(self) -> int: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(int, response.count) - - @_ensure_response - async def get_answers(self) -> Optional[List[QueryAnswerResult]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return response.answers - - @_ensure_response - async def get_debug_info(self) -> DebugInfo: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(DebugInfo, response.debug_info) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py similarity index 50% rename from sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index 9990a7dca659..3eed18136470 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -1,28 +1,54 @@ -# ------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- -from typing import cast, List, Union, Any, Dict -import time +# pylint: disable=too-many-instance-attributes +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Union, List, Dict, Optional, cast +import asyncio # pylint: disable=do-not-import-asyncio from azure.core.credentials import AzureKeyCredential from azure.core.credentials_async import AsyncTokenCredential from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.exceptions import ServiceResponseTimeoutError -from ._timer import Timer -from .._utils import is_retryable_status_code, get_authentication_policy -from .._search_indexing_buffered_sender_base import SearchIndexingBufferedSenderBase -from .._generated.aio import SearchIndexClient -from .._generated.models import IndexingResult, IndexBatch, IndexAction -from .._search_documents_error import RequestEntityTooLargeError -from ._index_documents_batch_async import IndexDocumentsBatch -from .._headers_mixin import HeadersMixin -from .._version import SDK_MONIKER + +from ._client import SearchClient as _SearchClient +from ._operations._patch import AsyncSearchItemPaged +from ..models._patch import RequestEntityTooLargeError, IndexDocumentsBatch +from ..models import IndexAction, IndexingResult +from ..indexes.aio import SearchIndexClient +from .._patch import DEFAULT_VERSION, is_retryable_status_code + + +class SearchClient(_SearchClient): + """SearchClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any + ) -> None: + super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) -class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixin): - """A buffered sender for document indexing actions. +class SearchIndexingBufferedSender: + """A buffered sender for document indexing actions (async version). :param endpoint: The URL endpoint of an Azure search service :type endpoint: str @@ -30,7 +56,8 @@ class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixi :type index_name: str :param credential: A credential to authorize search client requests :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword int auto_flush_interval: how many max seconds if between 2 flushes. This only takes effect + :keyword bool auto_flush: Whether to automatically flush the batch. Default is True. + :keyword int auto_flush_interval: How many max seconds between 2 flushes. This only takes effect when auto_flush is on. Default to 60 seconds. :keyword int initial_batch_action_count: The initial number of actions to group into a batch when tuning the behavior of the sender. The default value is 512. @@ -44,55 +71,68 @@ class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixi :keyword callable on_remove: If it is set, the client will call corresponding methods when there is a IndexAction removed from the queue (succeeds or fails). :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. + :keyword str audience: Sets the Audience to use for authentication with Microsoft Entra ID. """ - _client: SearchIndexClient - - # pylint: disable=too-many-instance-attributes + _DEFAULT_AUTO_FLUSH_INTERVAL = 60 + _DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512 + _DEFAULT_MAX_RETRIES = 3 def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any ) -> None: - super(SearchIndexingBufferedSender, self).__init__( - endpoint=endpoint, index_name=index_name, credential=credential, **kwargs - ) + self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) + self._auto_flush = kwargs.pop("auto_flush", True) + self._batch_action_count = kwargs.pop("initial_batch_action_count", self._DEFAULT_INITIAL_BATCH_ACTION_COUNT) + self._auto_flush_interval = kwargs.pop("auto_flush_interval", self._DEFAULT_AUTO_FLUSH_INTERVAL) + if self._auto_flush_interval <= 0: + raise ValueError("auto_flush_interval must be a positive number.") + self._max_retries_per_action = kwargs.pop("max_retries_per_action", self._DEFAULT_MAX_RETRIES) + self._endpoint = endpoint + self._index_name = index_name + self._index_key: Optional[str] = None + self._credential = credential + self._on_new = kwargs.pop("on_new", None) + self._on_progress = kwargs.pop("on_progress", None) + self._on_error = kwargs.pop("on_error", None) + self._on_remove = kwargs.pop("on_remove", None) + self._retry_counter: Dict[str, int] = {} + self._index_documents_batch = IndexDocumentsBatch() - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self._reset_timer() + + # Create the search client + self._client = _SearchClient( + endpoint=endpoint, index_name=index_name, credential=credential, api_version=self._api_version, **kwargs + ) + self._auto_flush_task: Optional[asyncio.Task] = None + if self._auto_flush: + self._schedule_auto_flush() + + def _schedule_auto_flush(self) -> None: + """Schedule the auto flush task.""" + if self._auto_flush_task and not self._auto_flush_task.done(): + self._auto_flush_task.cancel() + + async def auto_flush_worker(): + await asyncio.sleep(self._auto_flush_interval) + await self._process() + + try: + loop = asyncio.get_event_loop() + self._auto_flush_task = loop.create_task(auto_flush_worker()) + except RuntimeError: + # If no event loop is running, we'll schedule when processing happens + self._auto_flush_task = None async def _cleanup(self, flush: bool = True) -> None: """Clean up the client. - :param bool flush: flush the actions queue before shutdown the client - Default to True. + :param bool flush: Flush the actions queue before shutdown the client. Default to True. """ if flush: await self.flush() - if self._auto_flush: - self._timer.cancel() + if self._auto_flush_task and not self._auto_flush_task.done(): + self._auto_flush_task.cancel() def __repr__(self) -> str: return "".format( @@ -103,260 +143,272 @@ def __repr__(self) -> str: def actions(self) -> List[IndexAction]: """The list of currently index actions in queue to index. - :return: The list of currently index actions in queue to index. :rtype: list[IndexAction] """ - return self._index_documents_batch.actions + return self._index_documents_batch.actions if self._index_documents_batch.actions else [] @distributed_trace_async - async def close(self, **kwargs: Any) -> None: # pylint: disable=unused-argument + async def close(self, **kwargs) -> None: # pylint: disable=unused-argument """Close the session. :return: None :rtype: None """ await self._cleanup(flush=True) - return await self._client.close() + await self._client.close() @distributed_trace_async - async def flush(self, timeout: int = 86400, **kwargs) -> bool: # pylint:disable=unused-argument + async def flush(self, timeout: int = 86400, **kwargs: Any) -> bool: # pylint:disable=unused-argument """Flush the batch. - :param int timeout: time out setting. Default is 86400s (one day) + :param int timeout: Time out setting. Default is 86400s (one day) :return: True if there are errors. Else False :rtype: bool - :raises ~azure.core.exceptions.ServiceResponseTimeoutError: if there is a timeout + :raises ~azure.core.exceptions.ServiceResponseTimeoutError: """ has_error = False - begin_time = int(time.time()) + begin_time = asyncio.get_event_loop().time() while len(self.actions) > 0: - now = int(time.time()) + now = asyncio.get_event_loop().time() remaining = timeout - (now - begin_time) if remaining < 0: if self._on_error: - actions = await self._index_documents_batch.dequeue_actions() + actions = self._index_documents_batch.dequeue_actions() for action in actions: - await self._on_error(action) + if asyncio.iscoroutinefunction(self._on_error): + await self._on_error(action) + else: + self._on_error(action) raise ServiceResponseTimeoutError("Service response time out") - result = await self._process(timeout=remaining, raise_error=False) + result = await self._process(timeout=int(remaining), raise_error=False) if result: has_error = True return has_error async def _process(self, timeout: int = 86400, **kwargs) -> bool: - from ..indexes.aio import SearchIndexClient as SearchServiceClient - raise_error = kwargs.pop("raise_error", True) - actions = await self._index_documents_batch.dequeue_actions() + actions = self._index_documents_batch.dequeue_actions() has_error = False + if not self._index_key: try: credential = cast(Union[AzureKeyCredential, AsyncTokenCredential], self._credential) - client = SearchServiceClient(self._endpoint, credential) + client = SearchIndexClient(self._endpoint, credential) index_result = await client.get_index(self._index_name) if index_result: for field in index_result.fields: if field.key: self._index_key = field.name break + await client.close() except Exception: # pylint: disable=broad-except pass - self._reset_timer() + self._schedule_auto_flush() try: results = await self._index_documents_actions(actions=actions, timeout=timeout) for result in results: try: assert self._index_key is not None # Hint for mypy - action = next( - x - for x in actions - if x.additional_properties and x.additional_properties.get(self._index_key) == result.key - ) + action = next(x for x in actions if x and str(x.get(self._index_key)) == result.key) if result.succeeded: await self._callback_succeed(action) elif is_retryable_status_code(result.status_code): - await self._retry_action(action) + self._retry_action(action) has_error = True else: await self._callback_fail(action) has_error = True except StopIteration: pass - return has_error - except Exception: # pylint: disable=broad-except for action in actions: - await self._retry_action(action) + self._retry_action(action) if raise_error: raise return True return has_error async def _process_if_needed(self) -> bool: - """Every time when a new action is queued, this method - will be triggered. It checks the actions already queued and flushes them if: - 1. Auto_flush is on - 2. There are self._batch_action_count actions queued + """Check if processing is needed and process if necessary. - :return: True if proces is needed, False otherwise + :return: True if process had errors, False otherwise :rtype: bool """ if not self._auto_flush: return False - if len(self._index_documents_batch.actions) < self._batch_action_count: + if ( + len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) + < self._batch_action_count + ): return False return await self._process(raise_error=False) - def _reset_timer(self): - # pylint: disable=access-member-before-definition - try: - self._timer.cancel() - except AttributeError: - pass - if self._auto_flush: - self._timer = Timer(self._auto_flush_interval, self._process) - @distributed_trace_async - async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> None: # pylint: disable=unused-argument + async def upload_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument """Queue upload documents actions. :param documents: A list of documents to upload. :type documents: list[dict] """ - actions = await self._index_documents_batch.add_upload_actions(documents) + actions = self._index_documents_batch.add_upload_actions(documents) await self._callback_new(actions) await self._process_if_needed() @distributed_trace_async - async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> None: # pylint: disable=unused-argument + async def delete_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument """Queue delete documents actions :param documents: A list of documents to delete. - :type documents: list[Dict] + :type documents: list[dict] """ - actions = await self._index_documents_batch.add_delete_actions(documents) + actions = self._index_documents_batch.add_delete_actions(documents) await self._callback_new(actions) await self._process_if_needed() @distributed_trace_async - async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> None: # pylint: disable=unused-argument + async def merge_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument """Queue merge documents actions :param documents: A list of documents to merge. :type documents: list[dict] """ - actions = await self._index_documents_batch.add_merge_actions(documents) + actions = self._index_documents_batch.add_merge_actions(documents) await self._callback_new(actions) await self._process_if_needed() @distributed_trace_async - async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> None: + async def merge_or_upload_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument """Queue merge documents or upload documents actions :param documents: A list of documents to merge or upload. :type documents: list[dict] """ - actions = await self._index_documents_batch.add_merge_or_upload_actions(documents) + actions = self._index_documents_batch.add_merge_or_upload_actions(documents) await self._callback_new(actions) await self._process_if_needed() @distributed_trace_async - async def index_documents(self, batch: IndexDocumentsBatch, **kwargs: Any) -> List[IndexingResult]: + async def index_documents(self, batch: IndexDocumentsBatch, **kwargs) -> List[IndexingResult]: """Specify a document operations to perform as a batch. :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: Indexing result for each action in the batch. - :rtype: list[IndexingResult] + :type batch: ~azure.search.documents.models.IndexDocumentsBatch + :return: Indexing result of each action in the batch. + :rtype: list[IndexingResult] :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. """ - return await self._index_documents_actions(actions=batch.actions, **kwargs) - - async def _index_documents_actions(self, actions: List[IndexAction], **kwargs: Any) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} + return await self._index_documents_actions(actions=batch.actions if batch.actions else [], **kwargs) + async def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List[IndexingResult]: timeout = kwargs.pop("timeout", 86400) - begin_time = int(time.time()) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) + begin_time = asyncio.get_event_loop().time() + + batch = IndexDocumentsBatch(actions=actions) try: - batch_response = await self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) + batch_response = await self._client.index_documents(batch=batch, **kwargs) # pylint: disable=no-member + return cast(List[IndexingResult], batch_response) except RequestEntityTooLargeError as ex: if len(actions) == 1: raise pos = round(len(actions) / 2) if pos < self._batch_action_count: - await self._index_documents_batch.enqueue_actions(actions) - now = int(time.time()) + self._index_documents_batch.enqueue_actions(actions) + now = asyncio.get_event_loop().time() remaining = timeout - (now - begin_time) if remaining < 0: raise ServiceResponseTimeoutError("Service response time out") from ex batch_response_first_half = await self._index_documents_actions( actions=actions[:pos], timeout=remaining, **kwargs ) - if len(batch_response_first_half) > 0: - result_first_half = batch_response_first_half - else: - result_first_half = [] - now = int(time.time()) + result_first_half = list(batch_response_first_half) if batch_response_first_half else [] + + now = asyncio.get_event_loop().time() remaining = timeout - (now - begin_time) if remaining < 0: raise ServiceResponseTimeoutError("Service response time out") from ex batch_response_second_half = await self._index_documents_actions( actions=actions[pos:], timeout=remaining, **kwargs ) - if len(batch_response_second_half) > 0: - result_second_half = batch_response_second_half - else: - result_second_half = [] + result_second_half = list(batch_response_second_half) if batch_response_second_half else [] + result_first_half.extend(result_second_half) return result_first_half async def __aenter__(self) -> "SearchIndexingBufferedSender": - await self._client.__aenter__() # pylint: disable=no-member + await self._client.__aenter__() return self async def __aexit__(self, *args) -> None: await self.close() await self._client.__aexit__(*args) - async def _retry_action(self, action: IndexAction) -> None: + def _retry_action(self, action: IndexAction) -> None: if not self._index_key: - await self._callback_fail(action) + asyncio.create_task(self._callback_fail(action)) return - key = cast(str, action.additional_properties.get(self._index_key) if action.additional_properties else "") + key = cast(str, action.get(self._index_key) if action else "") counter = self._retry_counter.get(key) if not counter: # first time that fails self._retry_counter[key] = 1 - await self._index_documents_batch.enqueue_actions(action) + self._index_documents_batch.enqueue_actions(action) elif counter < self._max_retries_per_action - 1: # not reach retry limit yet self._retry_counter[key] = counter + 1 - await self._index_documents_batch.enqueue_actions(action) + self._index_documents_batch.enqueue_actions(action) else: - await self._callback_fail(action) + asyncio.create_task(self._callback_fail(action)) async def _callback_succeed(self, action: IndexAction) -> None: if self._on_remove: - await self._on_remove(action) + if asyncio.iscoroutinefunction(self._on_remove): + await self._on_remove(action) + else: + self._on_remove(action) if self._on_progress: - await self._on_progress(action) + if asyncio.iscoroutinefunction(self._on_progress): + await self._on_progress(action) + else: + self._on_progress(action) async def _callback_fail(self, action: IndexAction) -> None: if self._on_remove: - await self._on_remove(action) + if asyncio.iscoroutinefunction(self._on_remove): + await self._on_remove(action) + else: + self._on_remove(action) if self._on_error: - await self._on_error(action) + if asyncio.iscoroutinefunction(self._on_error): + await self._on_error(action) + else: + self._on_error(action) async def _callback_new(self, actions: List[IndexAction]) -> None: if self._on_new: for action in actions: - await self._on_new(action) + if asyncio.iscoroutinefunction(self._on_new): + await self._on_new(action) + else: + self._on_new(action) + + +__all__: list[str] = [ + "SearchClient", + "AsyncSearchItemPaged", + "SearchIndexingBufferedSender", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py deleted file mode 100644 index 2bf58159a25c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import asyncio # pylint: disable=do-not-import-asyncio - - -class Timer: - def __init__(self, timeout, callback) -> None: - self._timeout = timeout - self._callback = callback - self._task = asyncio.ensure_future(self._job()) - - async def _job(self): - await asyncio.sleep(self._timeout) - await self._callback() - - def cancel(self) -> None: - self._task.cancel() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py index 03792b2fcb89..064fb13712b1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py @@ -1,33 +1,34 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._search_index_client import SearchIndexClient -from ._search_indexer_client import SearchIndexerClient +from typing import TYPE_CHECKING -__all__ = ( - "SearchIndexerClient", +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchIndexClient # type: ignore +from ._client import SearchIndexerClient # type: ignore +from .._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ "SearchIndexClient", -) + "SearchIndexerClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py new file mode 100644 index 000000000000..54c2e85631d1 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py @@ -0,0 +1,181 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING, Union +from typing_extensions import Self + +from azure.core import PipelineClient +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse + +from .._utils.serialization import Deserializer, Serializer +from ._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration +from ._operations import _SearchIndexClientOperationsMixin, _SearchIndexerClientOperationsMixin + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class SearchIndexClient(_SearchIndexClientOperationsMixin): + """SearchIndexClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = SearchIndexClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) + + +class SearchIndexerClient(_SearchIndexerClientOperationsMixin): + """SearchIndexerClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = SearchIndexerClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py new file mode 100644 index 000000000000..a1c66e4d109e --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py @@ -0,0 +1,127 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) + + +class SearchIndexerClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexerClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py deleted file mode 100644 index 202320be3a96..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_service_client import SearchServiceClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchServiceClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py deleted file mode 100644 index c4deaa4cc736..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchServiceClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-11-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - - self.endpoint = endpoint - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchserviceclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py deleted file mode 100644 index 148199307d85..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any -from typing_extensions import Self - -from azure.core import PipelineClient -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse - -from . import models as _models -from ._configuration import SearchServiceClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import ( - AliasesOperations, - DataSourcesOperations, - IndexersOperations, - IndexesOperations, - KnowledgeBasesOperations, - KnowledgeSourcesOperations, - SkillsetsOperations, - SynonymMapsOperations, - _SearchServiceClientOperationsMixin, -) - - -class SearchServiceClient(_SearchServiceClientOperationsMixin): # pylint: disable=too-many-instance-attributes - """Client that can be used to manage and query indexes and documents, as well as manage other - resources, on a search service. - - :ivar knowledge_bases: KnowledgeBasesOperations operations - :vartype knowledge_bases: azure.search.documents.indexes.operations.KnowledgeBasesOperations - :ivar knowledge_sources: KnowledgeSourcesOperations operations - :vartype knowledge_sources: - azure.search.documents.indexes.operations.KnowledgeSourcesOperations - :ivar data_sources: DataSourcesOperations operations - :vartype data_sources: azure.search.documents.indexes.operations.DataSourcesOperations - :ivar indexers: IndexersOperations operations - :vartype indexers: azure.search.documents.indexes.operations.IndexersOperations - :ivar skillsets: SkillsetsOperations operations - :vartype skillsets: azure.search.documents.indexes.operations.SkillsetsOperations - :ivar synonym_maps: SynonymMapsOperations operations - :vartype synonym_maps: azure.search.documents.indexes.operations.SynonymMapsOperations - :ivar indexes: IndexesOperations operations - :vartype indexes: azure.search.documents.indexes.operations.IndexesOperations - :ivar aliases: AliasesOperations operations - :vartype aliases: azure.search.documents.indexes.operations.AliasesOperations - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = SearchServiceClientConfiguration(endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.knowledge_bases = KnowledgeBasesOperations(self._client, self._config, self._serialize, self._deserialize) - self.knowledge_sources = KnowledgeSourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.data_sources = DataSourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexers = IndexersOperations(self._client, self._config, self._serialize, self._deserialize) - self.skillsets = SkillsetsOperations(self._client, self._config, self._serialize, self._deserialize) - self.synonym_maps = SynonymMapsOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) - self.aliases = AliasesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py deleted file mode 100644 index a9d001691686..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py +++ /dev/null @@ -1,23 +0,0 @@ -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Generic, TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .serialization import Deserializer, Serializer - - -TClient = TypeVar("TClient") -TConfig = TypeVar("TConfig") - - -class ClientMixinABC(ABC, Generic[TClient, TConfig]): - """DO NOT use this class. It is for internal typing use only.""" - - _client: TClient - _config: TConfig - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py deleted file mode 100644 index 202320be3a96..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_service_client import SearchServiceClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchServiceClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py deleted file mode 100644 index 3d51f5a4964f..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchServiceClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-11-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - - self.endpoint = endpoint - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchserviceclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py deleted file mode 100644 index a02642ae0fa0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable -from typing_extensions import Self - -from azure.core import AsyncPipelineClient -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import SearchServiceClientConfiguration -from .operations import ( - AliasesOperations, - DataSourcesOperations, - IndexersOperations, - IndexesOperations, - KnowledgeBasesOperations, - KnowledgeSourcesOperations, - SkillsetsOperations, - SynonymMapsOperations, - _SearchServiceClientOperationsMixin, -) - - -class SearchServiceClient(_SearchServiceClientOperationsMixin): # pylint: disable=too-many-instance-attributes - """Client that can be used to manage and query indexes and documents, as well as manage other - resources, on a search service. - - :ivar knowledge_bases: KnowledgeBasesOperations operations - :vartype knowledge_bases: - azure.search.documents.indexes.aio.operations.KnowledgeBasesOperations - :ivar knowledge_sources: KnowledgeSourcesOperations operations - :vartype knowledge_sources: - azure.search.documents.indexes.aio.operations.KnowledgeSourcesOperations - :ivar data_sources: DataSourcesOperations operations - :vartype data_sources: azure.search.documents.indexes.aio.operations.DataSourcesOperations - :ivar indexers: IndexersOperations operations - :vartype indexers: azure.search.documents.indexes.aio.operations.IndexersOperations - :ivar skillsets: SkillsetsOperations operations - :vartype skillsets: azure.search.documents.indexes.aio.operations.SkillsetsOperations - :ivar synonym_maps: SynonymMapsOperations operations - :vartype synonym_maps: azure.search.documents.indexes.aio.operations.SynonymMapsOperations - :ivar indexes: IndexesOperations operations - :vartype indexes: azure.search.documents.indexes.aio.operations.IndexesOperations - :ivar aliases: AliasesOperations operations - :vartype aliases: azure.search.documents.indexes.aio.operations.AliasesOperations - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = SearchServiceClientConfiguration(endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.knowledge_bases = KnowledgeBasesOperations(self._client, self._config, self._serialize, self._deserialize) - self.knowledge_sources = KnowledgeSourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.data_sources = DataSourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexers = IndexersOperations(self._client, self._config, self._serialize, self._deserialize) - self.skillsets = SkillsetsOperations(self._client, self._config, self._serialize, self._deserialize) - self.synonym_maps = SynonymMapsOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) - self.aliases = AliasesOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py deleted file mode 100644 index 83f75c712c54..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_bases_operations import KnowledgeBasesOperations # type: ignore -from ._knowledge_sources_operations import KnowledgeSourcesOperations # type: ignore -from ._data_sources_operations import DataSourcesOperations # type: ignore -from ._indexers_operations import IndexersOperations # type: ignore -from ._skillsets_operations import SkillsetsOperations # type: ignore -from ._synonym_maps_operations import SynonymMapsOperations # type: ignore -from ._indexes_operations import IndexesOperations # type: ignore -from ._aliases_operations import AliasesOperations # type: ignore -from ._search_service_client_operations import _SearchServiceClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBasesOperations", - "KnowledgeSourcesOperations", - "DataSourcesOperations", - "IndexersOperations", - "SkillsetsOperations", - "SynonymMapsOperations", - "IndexesOperations", - "AliasesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py deleted file mode 100644 index 626f0452b62d..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py +++ /dev/null @@ -1,626 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._aliases_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class AliasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`aliases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create( - self, - alias: _models.SearchAlias, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - alias: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - alias: Union[_models.SearchAlias, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Is either a SearchAlias type or a - IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.SearchAlias"]: - """Lists all aliases available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Aliases - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchAlias or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListAliasesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListAliasesResult", pipeline_response) - list_of_elem = deserialized.aliases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: _models.SearchAlias, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: Union[_models.SearchAlias, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Is either a SearchAlias type or - a IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_or_update_request( - alias_name=alias_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - alias_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Alias - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, alias_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchAlias: - """Retrieves an alias definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Alias - - :param alias_name: The name of the alias to retrieve. Required. - :type alias_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py deleted file mode 100644 index a8b3c2cfaeb6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py +++ /dev/null @@ -1,607 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._data_sources_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class DataSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`data_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: _models.SearchIndexerDataSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_or_update_request( - data_source_name=data_source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - data_source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Data-Source - - :param data_source_name: The name of the datasource to delete. Required. - :type data_source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, data_source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Retrieves a datasource definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Data-Source - - :param data_source_name: The name of the datasource to retrieve. Required. - :type data_source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListDataSourcesResult: - """Lists all datasources available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Data-Sources - - :param select: Selects which top-level properties of the data sources to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListDataSourcesResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListDataSourcesResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListDataSourcesResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - data_source: _models.SearchIndexerDataSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - data_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py deleted file mode 100644 index 0a3823b7d167..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py +++ /dev/null @@ -1,1123 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._indexers_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_get_status_request, - build_list_request, - build_reset_docs_request, - build_reset_request, - build_resync_request, - build_run_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class IndexersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`indexers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def reset( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Resets the change tracking state associated with an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Reset-Indexer - - :param indexer_name: The name of the indexer to reset. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_reset_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[_models.DocumentKeysOrIds] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[Union[_models.DocumentKeysOrIds, IO[bytes]]] = None, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Is either a DocumentKeysOrIds type or a IO[bytes] type. Default value is - None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if keys_or_ids else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" if keys_or_ids else None - _json = None - _content = None - if isinstance(keys_or_ids, (IOBase, bytes)): - _content = keys_or_ids - else: - if keys_or_ids is not None: - _json = self._serialize.body(keys_or_ids, "DocumentKeysOrIds") - else: - _json = None - - _request = build_reset_docs_request( - indexer_name=indexer_name, - overwrite=overwrite, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def resync( - self, - indexer_name: str, - indexer_resync: _models.IndexerResyncBody, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def resync( - self, - indexer_name: str, - indexer_resync: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def resync( - self, - indexer_name: str, - indexer_resync: Union[_models.IndexerResyncBody, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Is either a IndexerResyncBody type or a IO[bytes] type. Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer_resync, (IOBase, bytes)): - _content = indexer_resync - else: - _json = self._serialize.body(indexer_resync, "IndexerResyncBody") - - _request = build_resync_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def run( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Runs an indexer on-demand. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Run-Indexer - - :param indexer_name: The name of the indexer to run. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_run_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: _models.SearchIndexer, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: Union[_models.SearchIndexer, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Is either a SearchIndexer - type or a IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_or_update_request( - indexer_name=indexer_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - indexer_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Indexer - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexer: - """Retrieves an indexer definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer - - :param indexer_name: The name of the indexer to retrieve. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListIndexersResult: - """Lists all indexers available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexers - - :param select: Selects which top-level properties of the indexers to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListIndexersResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexersResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListIndexersResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - indexer: _models.SearchIndexer, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - indexer: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - indexer: Union[_models.SearchIndexer, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Is either a SearchIndexer type or a - IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_status( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerStatus: - """Returns the current status and execution history of an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer-Status - - :param indexer_name: The name of the indexer for which to retrieve status. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerStatus or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerStatus] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_status_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py deleted file mode 100644 index 7ca6a1309afc..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py +++ /dev/null @@ -1,870 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._indexes_operations import ( - build_analyze_request, - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_get_statistics_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`indexes` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create( - self, - index: _models.SearchIndex, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - index: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - index: Union[_models.SearchIndex, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Is either a SearchIndex type or a - IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.SearchIndex"]: - """Lists all indexes available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexes - - :param select: Selects which top-level properties of the index definitions to retrieve. - Specified as a comma-separated list of JSON property names, or '*' for all properties. The - default is all properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchIndex or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexesResult", pipeline_response) - list_of_elem = deserialized.indexes - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: _models.SearchIndex, - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: IO[bytes], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: Union[_models.SearchIndex, IO[bytes]], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Is either a SearchIndex type or - a IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_or_update_request( - index_name=index_name, - prefer=prefer, - allow_index_downtime=allow_index_downtime, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - index_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. This operation is permanent, with no - recovery option. Make sure you have a master copy of your index definition, data ingestion - code, and a backup of the primary data source in case you need to re-build the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Index - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndex: - """Retrieves an index definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index - - :param index_name: The name of the index to retrieve. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_statistics( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.GetIndexStatisticsResult: - """Returns statistics for the given index, including a document count and storage usage. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index-Statistics - - :param index_name: The name of the index for which to retrieve statistics. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: GetIndexStatisticsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GetIndexStatisticsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_statistics_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("GetIndexStatisticsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def analyze( - self, - index_name: str, - request: _models.AnalyzeRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def analyze( - self, - index_name: str, - request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def analyze( - self, - index_name: str, - request: Union[_models.AnalyzeRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Is either a - AnalyzeRequest type or a IO[bytes] type. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AnalyzeResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(request, (IOBase, bytes)): - _content = request - else: - _json = self._serialize.body(request, "AnalyzeRequest") - - _request = build_analyze_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AnalyzeResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_bases_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_bases_operations.py deleted file mode 100644 index a03399e532e5..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_bases_operations.py +++ /dev/null @@ -1,598 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._knowledge_bases_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class KnowledgeBasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`knowledge_bases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - knowledge_base_name: str, - prefer: Union[str, _models.Enum0], - knowledge_base: _models.KnowledgeBase, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base or updates an knowledge base if it already exists. - - :param knowledge_base_name: The name of the knowledge base to create or update. Required. - :type knowledge_base_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_base: The definition of the knowledge base to create or update. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - knowledge_base_name: str, - prefer: Union[str, _models.Enum0], - knowledge_base: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base or updates an knowledge base if it already exists. - - :param knowledge_base_name: The name of the knowledge base to create or update. Required. - :type knowledge_base_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_base: The definition of the knowledge base to create or update. Required. - :type knowledge_base: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - knowledge_base_name: str, - prefer: Union[str, _models.Enum0], - knowledge_base: Union[_models.KnowledgeBase, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base or updates an knowledge base if it already exists. - - :param knowledge_base_name: The name of the knowledge base to create or update. Required. - :type knowledge_base_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_base: The definition of the knowledge base to create or update. Is either a - KnowledgeBase type or a IO[bytes] type. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_base, (IOBase, bytes)): - _content = knowledge_base - else: - _json = self._serialize.body(knowledge_base, "KnowledgeBase") - - _request = build_create_or_update_request( - knowledge_base_name=knowledge_base_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBase", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - knowledge_base_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge base. - - :param knowledge_base_name: The name of the knowledge base to delete. Required. - :type knowledge_base_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - knowledge_base_name=knowledge_base_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, knowledge_base_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeBase: - """Retrieves an knowledge base definition. - - :param knowledge_base_name: The name of the knowledge base to retrieve. Required. - :type knowledge_base_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - knowledge_base_name=knowledge_base_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBase", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.KnowledgeBase"]: - """Lists all knowledge bases available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeBase or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeBasesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeBasesResult", pipeline_response) - list_of_elem = deserialized.knowledge_bases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create( - self, - knowledge_base: _models.KnowledgeBase, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The definition of the knowledge base to create. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - knowledge_base: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The definition of the knowledge base to create. Required. - :type knowledge_base: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - knowledge_base: Union[_models.KnowledgeBase, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The definition of the knowledge base to create. Is either a - KnowledgeBase type or a IO[bytes] type. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_base, (IOBase, bytes)): - _content = knowledge_base - else: - _json = self._serialize.body(knowledge_base, "KnowledgeBase") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBase", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py deleted file mode 100644 index c99490808ea2..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py +++ /dev/null @@ -1,665 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._knowledge_sources_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_get_status_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class KnowledgeSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`knowledge_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: _models.KnowledgeSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Is either - a KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_or_update_request( - source_name=source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeSource: - """Retrieves a knowledge source definition. - - :param source_name: The name of the knowledge source to retrieve. Required. - :type source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.KnowledgeSource"]: - """Lists all knowledge sources available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeSource or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeSourcesResult", pipeline_response) - list_of_elem = deserialized.knowledge_sources - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create( - self, - knowledge_source: _models.KnowledgeSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - knowledge_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Is either a - KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_status( - self, source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeSourceStatus: - """Returns the current status and synchronization history of a knowledge source. - - :param source_name: The name of the knowledge source for which to retrieve status. Required. - :type source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSourceStatus or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSourceStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeSourceStatus] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_status_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSourceStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py deleted file mode 100644 index 864c9d7d7cce..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py +++ /dev/null @@ -1,202 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.utils import ClientMixinABC -from ...operations._search_service_client_operations import ( - build_get_index_stats_summary_request, - build_get_service_statistics_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class _SearchServiceClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchServiceClientConfiguration] -): - - @distributed_trace_async - async def get_service_statistics( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchServiceStatistics: - """Gets service level statistics for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchServiceStatistics or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchServiceStatistics] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_service_statistics_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchServiceStatistics", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_index_stats_summary( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.IndexStatisticsSummary"]: - """Retrieves a summary of statistics for all indexes in the search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either IndexStatisticsSummary or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexStatsSummary] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_index_stats_summary_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexStatsSummary", pipeline_response) - list_of_elem = deserialized.indexes_statistics - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py deleted file mode 100644 index c644d5b710be..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py +++ /dev/null @@ -1,766 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._skillsets_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, - build_reset_skills_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class SkillsetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`skillsets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: _models.SearchIndexerSkillset, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Is either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_or_update_request( - skillset_name=skillset_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - skillset_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/delete-skillset - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, skillset_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Retrieves a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/get-skillset - - :param skillset_name: The name of the skillset to retrieve. Required. - :type skillset_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSkillsetsResult: - """List all skillsets in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/list-skillset - - :param select: Selects which top-level properties of the skillsets to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSkillsetsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSkillsetsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSkillsetsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - skillset: _models.SearchIndexerSkillset, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - skillset: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. Is - either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def reset_skills( - self, - skillset_name: str, - skill_names: _models.SkillNames, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def reset_skills( - self, - skillset_name: str, - skill_names: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def reset_skills( - self, - skillset_name: str, - skill_names: Union[_models.SkillNames, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Is either a SkillNames type or a IO[bytes] - type. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skill_names, (IOBase, bytes)): - _content = skill_names - else: - _json = self._serialize.body(skill_names, "SkillNames") - - _request = build_reset_skills_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py deleted file mode 100644 index 6d7b65b1a5b5..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py +++ /dev/null @@ -1,594 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._synonym_maps_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class SynonymMapsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`synonym_maps` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: _models.SynonymMap, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: Union[_models.SynonymMap, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Is either a - SynonymMap type or a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_or_update_request( - synonym_map_name=synonym_map_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - synonym_map_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Synonym-Map - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, synonym_map_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SynonymMap: - """Retrieves a synonym map definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Synonym-Map - - :param synonym_map_name: The name of the synonym map to retrieve. Required. - :type synonym_map_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSynonymMapsResult: - """Lists all synonym maps available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Synonym-Maps - - :param select: Selects which top-level properties of the synonym maps to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSynonymMapsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSynonymMapsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSynonymMapsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - synonym_map: _models.SynonymMap, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - synonym_map: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - synonym_map: Union[_models.SynonymMap, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Is either a SynonymMap type or - a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py deleted file mode 100644 index fd05db95b410..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py +++ /dev/null @@ -1,650 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AIServices, - AIServicesAccountIdentity, - AIServicesAccountKey, - AIServicesVisionParameters, - AIServicesVisionVectorizer, - AnalyzeRequest, - AnalyzeResult, - AnalyzedTokenInfo, - AsciiFoldingTokenFilter, - AzureActiveDirectoryApplicationCredentials, - AzureBlobKnowledgeSource, - AzureBlobKnowledgeSourceParameters, - AzureMachineLearningParameters, - AzureMachineLearningSkill, - AzureMachineLearningVectorizer, - AzureOpenAIEmbeddingSkill, - AzureOpenAITokenizerParameters, - AzureOpenAIVectorizer, - AzureOpenAIVectorizerParameters, - BM25SimilarityAlgorithm, - BinaryQuantizationCompression, - CharFilter, - ChatCompletionResponseFormat, - ChatCompletionResponseFormatJsonSchemaProperties, - ChatCompletionSchema, - ChatCompletionSkill, - CjkBigramTokenFilter, - ClassicSimilarityAlgorithm, - ClassicTokenizer, - CognitiveServicesAccount, - CognitiveServicesAccountKey, - CommonGramTokenFilter, - CommonModelParameters, - CompletedSynchronizationState, - ConditionalSkill, - ContentUnderstandingSkill, - ContentUnderstandingSkillChunkingProperties, - CorsOptions, - CustomAnalyzer, - CustomEntity, - CustomEntityAlias, - CustomEntityLookupSkill, - CustomNormalizer, - DataChangeDetectionPolicy, - DataDeletionDetectionPolicy, - DataSourceCredentials, - DefaultCognitiveServicesAccount, - DictionaryDecompounderTokenFilter, - DistanceScoringFunction, - DistanceScoringParameters, - DocumentExtractionSkill, - DocumentIntelligenceLayoutSkill, - DocumentIntelligenceLayoutSkillChunkingProperties, - DocumentKeysOrIds, - EdgeNGramTokenFilter, - EdgeNGramTokenFilterV2, - EdgeNGramTokenizer, - ElisionTokenFilter, - EntityLinkingSkill, - EntityRecognitionSkill, - EntityRecognitionSkillV3, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - ExhaustiveKnnAlgorithmConfiguration, - ExhaustiveKnnParameters, - FieldMapping, - FieldMappingFunction, - FreshnessScoringFunction, - FreshnessScoringParameters, - GetIndexStatisticsResult, - HighWaterMarkChangeDetectionPolicy, - HnswAlgorithmConfiguration, - HnswParameters, - ImageAnalysisSkill, - IndexStatisticsSummary, - IndexedOneLakeKnowledgeSource, - IndexedOneLakeKnowledgeSourceParameters, - IndexedSharePointKnowledgeSource, - IndexedSharePointKnowledgeSourceParameters, - IndexerCurrentState, - IndexerExecutionResult, - IndexerResyncBody, - IndexerRuntime, - IndexingParameters, - IndexingParametersConfiguration, - IndexingSchedule, - InputFieldMappingEntry, - KeepTokenFilter, - KeyPhraseExtractionSkill, - KeywordMarkerTokenFilter, - KeywordTokenizer, - KeywordTokenizerV2, - KnowledgeBase, - KnowledgeBaseAzureOpenAIModel, - KnowledgeBaseModel, - KnowledgeRetrievalLowReasoningEffort, - KnowledgeRetrievalMediumReasoningEffort, - KnowledgeRetrievalMinimalReasoningEffort, - KnowledgeRetrievalReasoningEffort, - KnowledgeSource, - KnowledgeSourceAzureOpenAIVectorizer, - KnowledgeSourceIngestionParameters, - KnowledgeSourceReference, - KnowledgeSourceStatistics, - KnowledgeSourceStatus, - KnowledgeSourceVectorizer, - LanguageDetectionSkill, - LengthTokenFilter, - LexicalAnalyzer, - LexicalNormalizer, - LexicalTokenizer, - LimitTokenFilter, - ListAliasesResult, - ListDataSourcesResult, - ListIndexStatsSummary, - ListIndexersResult, - ListIndexesResult, - ListKnowledgeBasesResult, - ListKnowledgeSourcesResult, - ListSkillsetsResult, - ListSynonymMapsResult, - LuceneStandardAnalyzer, - LuceneStandardTokenizer, - LuceneStandardTokenizerV2, - MagnitudeScoringFunction, - MagnitudeScoringParameters, - MappingCharFilter, - MergeSkill, - MicrosoftLanguageStemmingTokenizer, - MicrosoftLanguageTokenizer, - NGramTokenFilter, - NGramTokenFilterV2, - NGramTokenizer, - NativeBlobSoftDeleteDeletionDetectionPolicy, - OcrSkill, - OutputFieldMappingEntry, - PIIDetectionSkill, - PathHierarchyTokenizerV2, - PatternAnalyzer, - PatternCaptureTokenFilter, - PatternReplaceCharFilter, - PatternReplaceTokenFilter, - PatternTokenizer, - PhoneticTokenFilter, - RemoteSharePointKnowledgeSource, - RemoteSharePointKnowledgeSourceParameters, - RequestOptions, - RescoringOptions, - ResourceCounter, - ScalarQuantizationCompression, - ScalarQuantizationParameters, - ScoringFunction, - ScoringProfile, - SearchAlias, - SearchField, - SearchIndex, - SearchIndexFieldReference, - SearchIndexKnowledgeSource, - SearchIndexKnowledgeSourceParameters, - SearchIndexer, - SearchIndexerCache, - SearchIndexerDataContainer, - SearchIndexerDataIdentity, - SearchIndexerDataNoneIdentity, - SearchIndexerDataSource, - SearchIndexerDataUserAssignedIdentity, - SearchIndexerError, - SearchIndexerIndexProjection, - SearchIndexerIndexProjectionSelector, - SearchIndexerIndexProjectionsParameters, - SearchIndexerKnowledgeStore, - SearchIndexerKnowledgeStoreBlobProjectionSelector, - SearchIndexerKnowledgeStoreFileProjectionSelector, - SearchIndexerKnowledgeStoreObjectProjectionSelector, - SearchIndexerKnowledgeStoreParameters, - SearchIndexerKnowledgeStoreProjection, - SearchIndexerKnowledgeStoreProjectionSelector, - SearchIndexerKnowledgeStoreTableProjectionSelector, - SearchIndexerLimits, - SearchIndexerSkill, - SearchIndexerSkillset, - SearchIndexerStatus, - SearchIndexerWarning, - SearchResourceEncryptionKey, - SearchServiceCounters, - SearchServiceLimits, - SearchServiceStatistics, - SearchSuggester, - SemanticConfiguration, - SemanticField, - SemanticPrioritizedFields, - SemanticSearch, - SentimentSkill, - SentimentSkillV3, - ServiceIndexersRuntime, - ShaperSkill, - ShingleTokenFilter, - SimilarityAlgorithm, - SkillNames, - SnowballTokenFilter, - SoftDeleteColumnDeletionDetectionPolicy, - SplitSkill, - SqlIntegratedChangeTrackingPolicy, - StemmerOverrideTokenFilter, - StemmerTokenFilter, - StopAnalyzer, - StopwordsTokenFilter, - SynchronizationState, - SynonymMap, - SynonymTokenFilter, - TagScoringFunction, - TagScoringParameters, - TextTranslationSkill, - TextWeights, - TokenFilter, - TruncateTokenFilter, - UaxUrlEmailTokenizer, - UniqueTokenFilter, - VectorSearch, - VectorSearchAlgorithmConfiguration, - VectorSearchCompression, - VectorSearchProfile, - VectorSearchVectorizer, - VisionVectorizeSkill, - WebApiSkill, - WebApiVectorizer, - WebApiVectorizerParameters, - WebKnowledgeSource, - WebKnowledgeSourceDomain, - WebKnowledgeSourceDomains, - WebKnowledgeSourceParameters, - WordDelimiterTokenFilter, -) - -from ._search_service_client_enums import ( # type: ignore - AIFoundryModelCatalogName, - AzureOpenAIModelName, - BlobIndexerDataToExtract, - BlobIndexerImageAction, - BlobIndexerPDFTextRotationAlgorithm, - BlobIndexerParsingMode, - CharFilterName, - ChatCompletionExtraParametersBehavior, - ChatCompletionResponseFormatType, - CjkBigramTokenFilterScripts, - ContentUnderstandingSkillChunkingUnit, - ContentUnderstandingSkillExtractionOptions, - CustomEntityLookupSkillLanguage, - DocumentIntelligenceLayoutSkillChunkingUnit, - DocumentIntelligenceLayoutSkillExtractionOptions, - DocumentIntelligenceLayoutSkillMarkdownHeaderDepth, - DocumentIntelligenceLayoutSkillOutputFormat, - DocumentIntelligenceLayoutSkillOutputMode, - EdgeNGramTokenFilterSide, - EntityCategory, - EntityRecognitionSkillLanguage, - Enum0, - ImageAnalysisSkillLanguage, - ImageDetail, - IndexProjectionMode, - IndexedSharePointContainerName, - IndexerExecutionEnvironment, - IndexerExecutionStatus, - IndexerExecutionStatusDetail, - IndexerPermissionOption, - IndexerResyncOption, - IndexerStatus, - IndexingMode, - KeyPhraseExtractionSkillLanguage, - KnowledgeBaseModelKind, - KnowledgeRetrievalOutputMode, - KnowledgeRetrievalReasoningEffortKind, - KnowledgeSourceContentExtractionMode, - KnowledgeSourceIngestionPermissionOption, - KnowledgeSourceKind, - KnowledgeSourceSynchronizationStatus, - LexicalAnalyzerName, - LexicalNormalizerName, - LexicalTokenizerName, - MarkdownHeaderDepth, - MarkdownParsingSubmode, - MicrosoftStemmingTokenizerLanguage, - MicrosoftTokenizerLanguage, - OcrLineEnding, - OcrSkillLanguage, - PIIDetectionSkillMaskingMode, - PermissionFilter, - PhoneticEncoder, - RankingOrder, - RegexFlags, - ScoringFunctionAggregation, - ScoringFunctionInterpolation, - SearchFieldDataType, - SearchIndexPermissionFilterOption, - SearchIndexerDataSourceType, - SentimentSkillLanguage, - SnowballTokenFilterLanguage, - SplitSkillEncoderModelName, - SplitSkillLanguage, - SplitSkillUnit, - StemmerTokenFilterLanguage, - StopwordsList, - TextSplitMode, - TextTranslationSkillLanguage, - TokenCharacterKind, - TokenFilterName, - VectorEncodingFormat, - VectorSearchAlgorithmKind, - VectorSearchAlgorithmMetric, - VectorSearchCompressionKind, - VectorSearchCompressionRescoreStorageMethod, - VectorSearchCompressionTarget, - VectorSearchVectorizerKind, - VisualFeature, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AIServices", - "AIServicesAccountIdentity", - "AIServicesAccountKey", - "AIServicesVisionParameters", - "AIServicesVisionVectorizer", - "AnalyzeRequest", - "AnalyzeResult", - "AnalyzedTokenInfo", - "AsciiFoldingTokenFilter", - "AzureActiveDirectoryApplicationCredentials", - "AzureBlobKnowledgeSource", - "AzureBlobKnowledgeSourceParameters", - "AzureMachineLearningParameters", - "AzureMachineLearningSkill", - "AzureMachineLearningVectorizer", - "AzureOpenAIEmbeddingSkill", - "AzureOpenAITokenizerParameters", - "AzureOpenAIVectorizer", - "AzureOpenAIVectorizerParameters", - "BM25SimilarityAlgorithm", - "BinaryQuantizationCompression", - "CharFilter", - "ChatCompletionResponseFormat", - "ChatCompletionResponseFormatJsonSchemaProperties", - "ChatCompletionSchema", - "ChatCompletionSkill", - "CjkBigramTokenFilter", - "ClassicSimilarityAlgorithm", - "ClassicTokenizer", - "CognitiveServicesAccount", - "CognitiveServicesAccountKey", - "CommonGramTokenFilter", - "CommonModelParameters", - "CompletedSynchronizationState", - "ConditionalSkill", - "ContentUnderstandingSkill", - "ContentUnderstandingSkillChunkingProperties", - "CorsOptions", - "CustomAnalyzer", - "CustomEntity", - "CustomEntityAlias", - "CustomEntityLookupSkill", - "CustomNormalizer", - "DataChangeDetectionPolicy", - "DataDeletionDetectionPolicy", - "DataSourceCredentials", - "DefaultCognitiveServicesAccount", - "DictionaryDecompounderTokenFilter", - "DistanceScoringFunction", - "DistanceScoringParameters", - "DocumentExtractionSkill", - "DocumentIntelligenceLayoutSkill", - "DocumentIntelligenceLayoutSkillChunkingProperties", - "DocumentKeysOrIds", - "EdgeNGramTokenFilter", - "EdgeNGramTokenFilterV2", - "EdgeNGramTokenizer", - "ElisionTokenFilter", - "EntityLinkingSkill", - "EntityRecognitionSkill", - "EntityRecognitionSkillV3", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "ExhaustiveKnnAlgorithmConfiguration", - "ExhaustiveKnnParameters", - "FieldMapping", - "FieldMappingFunction", - "FreshnessScoringFunction", - "FreshnessScoringParameters", - "GetIndexStatisticsResult", - "HighWaterMarkChangeDetectionPolicy", - "HnswAlgorithmConfiguration", - "HnswParameters", - "ImageAnalysisSkill", - "IndexStatisticsSummary", - "IndexedOneLakeKnowledgeSource", - "IndexedOneLakeKnowledgeSourceParameters", - "IndexedSharePointKnowledgeSource", - "IndexedSharePointKnowledgeSourceParameters", - "IndexerCurrentState", - "IndexerExecutionResult", - "IndexerResyncBody", - "IndexerRuntime", - "IndexingParameters", - "IndexingParametersConfiguration", - "IndexingSchedule", - "InputFieldMappingEntry", - "KeepTokenFilter", - "KeyPhraseExtractionSkill", - "KeywordMarkerTokenFilter", - "KeywordTokenizer", - "KeywordTokenizerV2", - "KnowledgeBase", - "KnowledgeBaseAzureOpenAIModel", - "KnowledgeBaseModel", - "KnowledgeRetrievalLowReasoningEffort", - "KnowledgeRetrievalMediumReasoningEffort", - "KnowledgeRetrievalMinimalReasoningEffort", - "KnowledgeRetrievalReasoningEffort", - "KnowledgeSource", - "KnowledgeSourceAzureOpenAIVectorizer", - "KnowledgeSourceIngestionParameters", - "KnowledgeSourceReference", - "KnowledgeSourceStatistics", - "KnowledgeSourceStatus", - "KnowledgeSourceVectorizer", - "LanguageDetectionSkill", - "LengthTokenFilter", - "LexicalAnalyzer", - "LexicalNormalizer", - "LexicalTokenizer", - "LimitTokenFilter", - "ListAliasesResult", - "ListDataSourcesResult", - "ListIndexStatsSummary", - "ListIndexersResult", - "ListIndexesResult", - "ListKnowledgeBasesResult", - "ListKnowledgeSourcesResult", - "ListSkillsetsResult", - "ListSynonymMapsResult", - "LuceneStandardAnalyzer", - "LuceneStandardTokenizer", - "LuceneStandardTokenizerV2", - "MagnitudeScoringFunction", - "MagnitudeScoringParameters", - "MappingCharFilter", - "MergeSkill", - "MicrosoftLanguageStemmingTokenizer", - "MicrosoftLanguageTokenizer", - "NGramTokenFilter", - "NGramTokenFilterV2", - "NGramTokenizer", - "NativeBlobSoftDeleteDeletionDetectionPolicy", - "OcrSkill", - "OutputFieldMappingEntry", - "PIIDetectionSkill", - "PathHierarchyTokenizerV2", - "PatternAnalyzer", - "PatternCaptureTokenFilter", - "PatternReplaceCharFilter", - "PatternReplaceTokenFilter", - "PatternTokenizer", - "PhoneticTokenFilter", - "RemoteSharePointKnowledgeSource", - "RemoteSharePointKnowledgeSourceParameters", - "RequestOptions", - "RescoringOptions", - "ResourceCounter", - "ScalarQuantizationCompression", - "ScalarQuantizationParameters", - "ScoringFunction", - "ScoringProfile", - "SearchAlias", - "SearchField", - "SearchIndex", - "SearchIndexFieldReference", - "SearchIndexKnowledgeSource", - "SearchIndexKnowledgeSourceParameters", - "SearchIndexer", - "SearchIndexerCache", - "SearchIndexerDataContainer", - "SearchIndexerDataIdentity", - "SearchIndexerDataNoneIdentity", - "SearchIndexerDataSource", - "SearchIndexerDataUserAssignedIdentity", - "SearchIndexerError", - "SearchIndexerIndexProjection", - "SearchIndexerIndexProjectionSelector", - "SearchIndexerIndexProjectionsParameters", - "SearchIndexerKnowledgeStore", - "SearchIndexerKnowledgeStoreBlobProjectionSelector", - "SearchIndexerKnowledgeStoreFileProjectionSelector", - "SearchIndexerKnowledgeStoreObjectProjectionSelector", - "SearchIndexerKnowledgeStoreParameters", - "SearchIndexerKnowledgeStoreProjection", - "SearchIndexerKnowledgeStoreProjectionSelector", - "SearchIndexerKnowledgeStoreTableProjectionSelector", - "SearchIndexerLimits", - "SearchIndexerSkill", - "SearchIndexerSkillset", - "SearchIndexerStatus", - "SearchIndexerWarning", - "SearchResourceEncryptionKey", - "SearchServiceCounters", - "SearchServiceLimits", - "SearchServiceStatistics", - "SearchSuggester", - "SemanticConfiguration", - "SemanticField", - "SemanticPrioritizedFields", - "SemanticSearch", - "SentimentSkill", - "SentimentSkillV3", - "ServiceIndexersRuntime", - "ShaperSkill", - "ShingleTokenFilter", - "SimilarityAlgorithm", - "SkillNames", - "SnowballTokenFilter", - "SoftDeleteColumnDeletionDetectionPolicy", - "SplitSkill", - "SqlIntegratedChangeTrackingPolicy", - "StemmerOverrideTokenFilter", - "StemmerTokenFilter", - "StopAnalyzer", - "StopwordsTokenFilter", - "SynchronizationState", - "SynonymMap", - "SynonymTokenFilter", - "TagScoringFunction", - "TagScoringParameters", - "TextTranslationSkill", - "TextWeights", - "TokenFilter", - "TruncateTokenFilter", - "UaxUrlEmailTokenizer", - "UniqueTokenFilter", - "VectorSearch", - "VectorSearchAlgorithmConfiguration", - "VectorSearchCompression", - "VectorSearchProfile", - "VectorSearchVectorizer", - "VisionVectorizeSkill", - "WebApiSkill", - "WebApiVectorizer", - "WebApiVectorizerParameters", - "WebKnowledgeSource", - "WebKnowledgeSourceDomain", - "WebKnowledgeSourceDomains", - "WebKnowledgeSourceParameters", - "WordDelimiterTokenFilter", - "AIFoundryModelCatalogName", - "AzureOpenAIModelName", - "BlobIndexerDataToExtract", - "BlobIndexerImageAction", - "BlobIndexerPDFTextRotationAlgorithm", - "BlobIndexerParsingMode", - "CharFilterName", - "ChatCompletionExtraParametersBehavior", - "ChatCompletionResponseFormatType", - "CjkBigramTokenFilterScripts", - "ContentUnderstandingSkillChunkingUnit", - "ContentUnderstandingSkillExtractionOptions", - "CustomEntityLookupSkillLanguage", - "DocumentIntelligenceLayoutSkillChunkingUnit", - "DocumentIntelligenceLayoutSkillExtractionOptions", - "DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", - "DocumentIntelligenceLayoutSkillOutputFormat", - "DocumentIntelligenceLayoutSkillOutputMode", - "EdgeNGramTokenFilterSide", - "EntityCategory", - "EntityRecognitionSkillLanguage", - "Enum0", - "ImageAnalysisSkillLanguage", - "ImageDetail", - "IndexProjectionMode", - "IndexedSharePointContainerName", - "IndexerExecutionEnvironment", - "IndexerExecutionStatus", - "IndexerExecutionStatusDetail", - "IndexerPermissionOption", - "IndexerResyncOption", - "IndexerStatus", - "IndexingMode", - "KeyPhraseExtractionSkillLanguage", - "KnowledgeBaseModelKind", - "KnowledgeRetrievalOutputMode", - "KnowledgeRetrievalReasoningEffortKind", - "KnowledgeSourceContentExtractionMode", - "KnowledgeSourceIngestionPermissionOption", - "KnowledgeSourceKind", - "KnowledgeSourceSynchronizationStatus", - "LexicalAnalyzerName", - "LexicalNormalizerName", - "LexicalTokenizerName", - "MarkdownHeaderDepth", - "MarkdownParsingSubmode", - "MicrosoftStemmingTokenizerLanguage", - "MicrosoftTokenizerLanguage", - "OcrLineEnding", - "OcrSkillLanguage", - "PIIDetectionSkillMaskingMode", - "PermissionFilter", - "PhoneticEncoder", - "RankingOrder", - "RegexFlags", - "ScoringFunctionAggregation", - "ScoringFunctionInterpolation", - "SearchFieldDataType", - "SearchIndexPermissionFilterOption", - "SearchIndexerDataSourceType", - "SentimentSkillLanguage", - "SnowballTokenFilterLanguage", - "SplitSkillEncoderModelName", - "SplitSkillLanguage", - "SplitSkillUnit", - "StemmerTokenFilterLanguage", - "StopwordsList", - "TextSplitMode", - "TextTranslationSkillLanguage", - "TokenCharacterKind", - "TokenFilterName", - "VectorEncodingFormat", - "VectorSearchAlgorithmKind", - "VectorSearchAlgorithmMetric", - "VectorSearchCompressionKind", - "VectorSearchCompressionRescoreStorageMethod", - "VectorSearchCompressionTarget", - "VectorSearchVectorizerKind", - "VisualFeature", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py deleted file mode 100644 index 3e3e973cc671..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py +++ /dev/null @@ -1,14467 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class AIServices(_serialization.Model): - """Parameters for Azure Blob Storage knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar uri: The URI of the AI Services endpoint. Required. - :vartype uri: str - :ivar api_key: The API key for accessing AI Services. - :vartype api_key: str - """ - - _validation = { - "uri": {"required": True}, - } - - _attribute_map = { - "uri": {"key": "uri", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - } - - def __init__(self, *, uri: str, api_key: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword uri: The URI of the AI Services endpoint. Required. - :paramtype uri: str - :keyword api_key: The API key for accessing AI Services. - :paramtype api_key: str - """ - super().__init__(**kwargs) - self.uri = uri - self.api_key = api_key - - -class CognitiveServicesAccount(_serialization.Model): - """Base type for describing any Azure AI service resource attached to a skillset. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AIServicesAccountIdentity, AIServicesAccountKey, CognitiveServicesAccountKey, - DefaultCognitiveServicesAccount - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.AIServicesByIdentity": "AIServicesAccountIdentity", - "#Microsoft.Azure.Search.AIServicesByKey": "AIServicesAccountKey", - "#Microsoft.Azure.Search.CognitiveServicesByKey": "CognitiveServicesAccountKey", - "#Microsoft.Azure.Search.DefaultCognitiveServices": "DefaultCognitiveServicesAccount", - } - } - - def __init__(self, *, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.description = description - - -class AIServicesAccountIdentity(CognitiveServicesAccount): - """The multi-region account of an Azure AI service resource that's attached to a skillset. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - :ivar identity: The user-assigned managed identity used for connections to AI Service. If not - specified, the system-assigned managed identity is used. On updates to the skillset, if the - identity is unspecified, the value remains unchanged. If set to "none", the value of this - property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. - :vartype subdomain_url: str - """ - - _validation = { - "odata_type": {"required": True}, - "subdomain_url": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "subdomain_url": {"key": "subdomainUrl", "type": "str"}, - } - - def __init__( - self, - *, - subdomain_url: str, - description: Optional[str] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - :keyword identity: The user-assigned managed identity used for connections to AI Service. If - not specified, the system-assigned managed identity is used. On updates to the skillset, if the - identity is unspecified, the value remains unchanged. If set to "none", the value of this - property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword subdomain_url: The subdomain url for the corresponding AI Service. Required. - :paramtype subdomain_url: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.AIServicesByIdentity" - self.identity = identity - self.subdomain_url = subdomain_url - - -class AIServicesAccountKey(CognitiveServicesAccount): - """The account key of an Azure AI service resource that's attached to a skillset, to be used with - the resource's subdomain. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - :ivar key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :vartype key: str - :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. - :vartype subdomain_url: str - """ - - _validation = { - "odata_type": {"required": True}, - "key": {"required": True}, - "subdomain_url": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "key": {"key": "key", "type": "str"}, - "subdomain_url": {"key": "subdomainUrl", "type": "str"}, - } - - def __init__(self, *, key: str, subdomain_url: str, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - :keyword key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :paramtype key: str - :keyword subdomain_url: The subdomain url for the corresponding AI Service. Required. - :paramtype subdomain_url: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.AIServicesByKey" - self.key = key - self.subdomain_url = subdomain_url - - -class AIServicesVisionParameters(_serialization.Model): - """Specifies the AI Services Vision parameters for vectorizing a query image or text. - - All required parameters must be populated in order to send to server. - - :ivar model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :vartype model_version: str - :ivar resource_uri: The resource URI of the AI Services resource. Required. - :vartype resource_uri: str - :ivar api_key: API key of the designated AI Services resource. - :vartype api_key: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the index, if the identity is unspecified, the value remains unchanged. If - set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _validation = { - "model_version": {"required": True}, - "resource_uri": {"required": True}, - } - - _attribute_map = { - "model_version": {"key": "modelVersion", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - model_version: str, - resource_uri: str, - api_key: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :paramtype model_version: str - :keyword resource_uri: The resource URI of the AI Services resource. Required. - :paramtype resource_uri: str - :keyword api_key: API key of the designated AI Services resource. - :paramtype api_key: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the index, if the identity is unspecified, the value remains unchanged. If - set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.model_version = model_version - self.resource_uri = resource_uri - self.api_key = api_key - self.auth_identity = auth_identity - - -class VectorSearchVectorizer(_serialization.Model): - """Specifies the vectorization method to be used during query time. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AIServicesVisionVectorizer, AzureMachineLearningVectorizer, AzureOpenAIVectorizer, - WebApiVectorizer - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": { - "aiServicesVision": "AIServicesVisionVectorizer", - "aml": "AzureMachineLearningVectorizer", - "azureOpenAI": "AzureOpenAIVectorizer", - "customWebApi": "WebApiVectorizer", - } - } - - def __init__(self, *, vectorizer_name: str, **kwargs: Any) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - """ - super().__init__(**kwargs) - self.vectorizer_name = vectorizer_name - self.kind: Optional[str] = None - - -class AIServicesVisionVectorizer(VectorSearchVectorizer): - """Specifies the AI Services Vision parameters for vectorizing a query image or text. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar ai_services_vision_parameters: Contains the parameters specific to AI Services Vision - embedding vectorization. - :vartype ai_services_vision_parameters: - ~azure.search.documents.indexes.models.AIServicesVisionParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "ai_services_vision_parameters": {"key": "aiServicesVisionParameters", "type": "AIServicesVisionParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - ai_services_vision_parameters: Optional["_models.AIServicesVisionParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword ai_services_vision_parameters: Contains the parameters specific to AI Services Vision - embedding vectorization. - :paramtype ai_services_vision_parameters: - ~azure.search.documents.indexes.models.AIServicesVisionParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "aiServicesVision" - self.ai_services_vision_parameters = ai_services_vision_parameters - - -class AnalyzedTokenInfo(_serialization.Model): - """Information about a token returned by an analyzer. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar token: The token returned by the analyzer. Required. - :vartype token: str - :ivar start_offset: The index of the first character of the token in the input text. Required. - :vartype start_offset: int - :ivar end_offset: The index of the last character of the token in the input text. Required. - :vartype end_offset: int - :ivar position: The position of the token in the input text relative to other tokens. The first - token in the input text has position 0, the next has position 1, and so on. Depending on the - analyzer used, some tokens might have the same position, for example if they are synonyms of - each other. Required. - :vartype position: int - """ - - _validation = { - "token": {"required": True, "readonly": True}, - "start_offset": {"required": True, "readonly": True}, - "end_offset": {"required": True, "readonly": True}, - "position": {"required": True, "readonly": True}, - } - - _attribute_map = { - "token": {"key": "token", "type": "str"}, - "start_offset": {"key": "startOffset", "type": "int"}, - "end_offset": {"key": "endOffset", "type": "int"}, - "position": {"key": "position", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.token: Optional[str] = None - self.start_offset: Optional[int] = None - self.end_offset: Optional[int] = None - self.position: Optional[int] = None - - -class AnalyzeRequest(_serialization.Model): - """Specifies some text and analysis components used to break that text into tokens. - - All required parameters must be populated in order to send to server. - - :ivar text: The text to break into tokens. Required. - :vartype text: str - :ivar analyzer: The name of the analyzer to use to break the given text. If this parameter is - not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are - mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar tokenizer: The name of the tokenizer to use to break the given text. If this parameter is - not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters are - mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", "letter", - "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", - "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". - :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar normalizer: The name of the normalizer to use to normalize the given text. Known values - are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :ivar token_filters: An optional list of token filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: An optional list of character filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - - _validation = { - "text": {"required": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "str"}, - "analyzer": {"key": "analyzer", "type": "str"}, - "tokenizer": {"key": "tokenizer", "type": "str"}, - "normalizer": {"key": "normalizer", "type": "str"}, - "token_filters": {"key": "tokenFilters", "type": "[str]"}, - "char_filters": {"key": "charFilters", "type": "[str]"}, - } - - def __init__( - self, - *, - text: str, - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - tokenizer: Optional[Union[str, "_models.LexicalTokenizerName"]] = None, - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, - token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, - char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword text: The text to break into tokens. Required. - :paramtype text: str - :keyword analyzer: The name of the analyzer to use to break the given text. If this parameter - is not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters - are mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", - "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", - "zh-Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", - "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", - "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", - "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", - "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", - "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", - "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", - "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", - "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", - "pt-PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", - "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", - "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", - "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", - "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", - "simple", "stop", and "whitespace". - :paramtype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword tokenizer: The name of the tokenizer to use to break the given text. If this parameter - is not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters - are mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", "letter", - "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", - "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". - :paramtype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :keyword normalizer: The name of the normalizer to use to normalize the given text. Known - values are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :paramtype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :keyword token_filters: An optional list of token filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :paramtype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: An optional list of character filters to use when breaking the given - text. This parameter can only be set when using the tokenizer parameter. - :paramtype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - super().__init__(**kwargs) - self.text = text - self.analyzer = analyzer - self.tokenizer = tokenizer - self.normalizer = normalizer - self.token_filters = token_filters - self.char_filters = char_filters - - -class AnalyzeResult(_serialization.Model): - """The result of testing an analyzer on text. - - All required parameters must be populated in order to send to server. - - :ivar tokens: The list of tokens returned by the analyzer specified in the request. Required. - :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] - """ - - _validation = { - "tokens": {"required": True}, - } - - _attribute_map = { - "tokens": {"key": "tokens", "type": "[AnalyzedTokenInfo]"}, - } - - def __init__(self, *, tokens: list["_models.AnalyzedTokenInfo"], **kwargs: Any) -> None: - """ - :keyword tokens: The list of tokens returned by the analyzer specified in the request. - Required. - :paramtype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] - """ - super().__init__(**kwargs) - self.tokens = tokens - - -class TokenFilter(_serialization.Model): - """Base type for token filters. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AsciiFoldingTokenFilter, CjkBigramTokenFilter, CommonGramTokenFilter, - DictionaryDecompounderTokenFilter, EdgeNGramTokenFilter, EdgeNGramTokenFilterV2, - ElisionTokenFilter, KeepTokenFilter, KeywordMarkerTokenFilter, LengthTokenFilter, - LimitTokenFilter, NGramTokenFilter, NGramTokenFilterV2, PatternCaptureTokenFilter, - PatternReplaceTokenFilter, PhoneticTokenFilter, ShingleTokenFilter, SnowballTokenFilter, - StemmerOverrideTokenFilter, StemmerTokenFilter, StopwordsTokenFilter, SynonymTokenFilter, - TruncateTokenFilter, UniqueTokenFilter, WordDelimiterTokenFilter - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.AsciiFoldingTokenFilter": "AsciiFoldingTokenFilter", - "#Microsoft.Azure.Search.CjkBigramTokenFilter": "CjkBigramTokenFilter", - "#Microsoft.Azure.Search.CommonGramTokenFilter": "CommonGramTokenFilter", - "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter": "DictionaryDecompounderTokenFilter", - "#Microsoft.Azure.Search.EdgeNGramTokenFilter": "EdgeNGramTokenFilter", - "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2": "EdgeNGramTokenFilterV2", - "#Microsoft.Azure.Search.ElisionTokenFilter": "ElisionTokenFilter", - "#Microsoft.Azure.Search.KeepTokenFilter": "KeepTokenFilter", - "#Microsoft.Azure.Search.KeywordMarkerTokenFilter": "KeywordMarkerTokenFilter", - "#Microsoft.Azure.Search.LengthTokenFilter": "LengthTokenFilter", - "#Microsoft.Azure.Search.LimitTokenFilter": "LimitTokenFilter", - "#Microsoft.Azure.Search.NGramTokenFilter": "NGramTokenFilter", - "#Microsoft.Azure.Search.NGramTokenFilterV2": "NGramTokenFilterV2", - "#Microsoft.Azure.Search.PatternCaptureTokenFilter": "PatternCaptureTokenFilter", - "#Microsoft.Azure.Search.PatternReplaceTokenFilter": "PatternReplaceTokenFilter", - "#Microsoft.Azure.Search.PhoneticTokenFilter": "PhoneticTokenFilter", - "#Microsoft.Azure.Search.ShingleTokenFilter": "ShingleTokenFilter", - "#Microsoft.Azure.Search.SnowballTokenFilter": "SnowballTokenFilter", - "#Microsoft.Azure.Search.StemmerOverrideTokenFilter": "StemmerOverrideTokenFilter", - "#Microsoft.Azure.Search.StemmerTokenFilter": "StemmerTokenFilter", - "#Microsoft.Azure.Search.StopwordsTokenFilter": "StopwordsTokenFilter", - "#Microsoft.Azure.Search.SynonymTokenFilter": "SynonymTokenFilter", - "#Microsoft.Azure.Search.TruncateTokenFilter": "TruncateTokenFilter", - "#Microsoft.Azure.Search.UniqueTokenFilter": "UniqueTokenFilter", - "#Microsoft.Azure.Search.WordDelimiterTokenFilter": "WordDelimiterTokenFilter", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class AsciiFoldingTokenFilter(TokenFilter): - """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 - ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such - equivalents exist. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar preserve_original: A value indicating whether the original token will be kept. Default is - false. - :vartype preserve_original: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "preserve_original": {"key": "preserveOriginal", "type": "bool"}, - } - - def __init__(self, *, name: str, preserve_original: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword preserve_original: A value indicating whether the original token will be kept. Default - is false. - :paramtype preserve_original: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.AsciiFoldingTokenFilter" - self.preserve_original = preserve_original - - -class AzureActiveDirectoryApplicationCredentials(_serialization.Model): # pylint: disable=name-too-long - """Credentials of a registered application created for your search service, used for authenticated - access to the encryption keys stored in Azure Key Vault. - - All required parameters must be populated in order to send to server. - - :ivar application_id: An AAD Application ID that was granted the required access permissions to - the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID - should not be confused with the Object ID for your AAD Application. Required. - :vartype application_id: str - :ivar application_secret: The authentication key of the specified AAD application. - :vartype application_secret: str - """ - - _validation = { - "application_id": {"required": True}, - } - - _attribute_map = { - "application_id": {"key": "applicationId", "type": "str"}, - "application_secret": {"key": "applicationSecret", "type": "str"}, - } - - def __init__(self, *, application_id: str, application_secret: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword application_id: An AAD Application ID that was granted the required access permissions - to the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID - should not be confused with the Object ID for your AAD Application. Required. - :paramtype application_id: str - :keyword application_secret: The authentication key of the specified AAD application. - :paramtype application_secret: str - """ - super().__init__(**kwargs) - self.application_id = application_id - self.application_secret = application_secret - - -class KnowledgeSource(_serialization.Model): - """Represents a knowledge source definition. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureBlobKnowledgeSource, IndexedOneLakeKnowledgeSource, IndexedSharePointKnowledgeSource, - RemoteSharePointKnowledgeSource, SearchIndexKnowledgeSource, WebKnowledgeSource - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - } - - _subtype_map = { - "kind": { - "azureBlob": "AzureBlobKnowledgeSource", - "indexedOneLake": "IndexedOneLakeKnowledgeSource", - "indexedSharePoint": "IndexedSharePointKnowledgeSource", - "remoteSharePoint": "RemoteSharePointKnowledgeSource", - "searchIndex": "SearchIndexKnowledgeSource", - "web": "WebKnowledgeSource", - } - } - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.kind: Optional[str] = None - self.e_tag = e_tag - self.encryption_key = encryption_key - - -class AzureBlobKnowledgeSource(KnowledgeSource): - """Configuration for Azure Blob Storage knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar azure_blob_parameters: The type of the knowledge source. Required. - :vartype azure_blob_parameters: - ~azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - "azure_blob_parameters": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "azure_blob_parameters": {"key": "azureBlobParameters", "type": "AzureBlobKnowledgeSourceParameters"}, - } - - def __init__( - self, - *, - name: str, - azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters", - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword azure_blob_parameters: The type of the knowledge source. Required. - :paramtype azure_blob_parameters: - ~azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "azureBlob" - self.azure_blob_parameters = azure_blob_parameters - - -class AzureBlobKnowledgeSourceParameters(_serialization.Model): - """Parameters for Azure Blob Storage knowledge source. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar connection_string: Key-based connection string or the ResourceId format if using a - managed identity. Required. - :vartype connection_string: str - :ivar container_name: The name of the blob storage container. Required. - :vartype container_name: str - :ivar folder_path: Optional folder path within the container. - :vartype folder_path: str - :ivar is_adls_gen2: Set to true if connecting to an ADLS Gen2 storage account. Default is - false. - :vartype is_adls_gen2: bool - :ivar ingestion_parameters: Consolidates all general ingestion settings. - :vartype ingestion_parameters: - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionParameters - :ivar created_resources: Resources created by the knowledge source. - :vartype created_resources: dict[str, str] - """ - - _validation = { - "connection_string": {"required": True}, - "container_name": {"required": True}, - "created_resources": {"readonly": True}, - } - - _attribute_map = { - "connection_string": {"key": "connectionString", "type": "str"}, - "container_name": {"key": "containerName", "type": "str"}, - "folder_path": {"key": "folderPath", "type": "str"}, - "is_adls_gen2": {"key": "isADLSGen2", "type": "bool"}, - "ingestion_parameters": {"key": "ingestionParameters", "type": "KnowledgeSourceIngestionParameters"}, - "created_resources": {"key": "createdResources", "type": "{str}"}, - } - - def __init__( - self, - *, - connection_string: str, - container_name: str, - folder_path: Optional[str] = None, - is_adls_gen2: bool = False, - ingestion_parameters: Optional["_models.KnowledgeSourceIngestionParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword connection_string: Key-based connection string or the ResourceId format if using a - managed identity. Required. - :paramtype connection_string: str - :keyword container_name: The name of the blob storage container. Required. - :paramtype container_name: str - :keyword folder_path: Optional folder path within the container. - :paramtype folder_path: str - :keyword is_adls_gen2: Set to true if connecting to an ADLS Gen2 storage account. Default is - false. - :paramtype is_adls_gen2: bool - :keyword ingestion_parameters: Consolidates all general ingestion settings. - :paramtype ingestion_parameters: - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionParameters - """ - super().__init__(**kwargs) - self.connection_string = connection_string - self.container_name = container_name - self.folder_path = folder_path - self.is_adls_gen2 = is_adls_gen2 - self.ingestion_parameters = ingestion_parameters - self.created_resources: Optional[dict[str, str]] = None - - -class AzureMachineLearningParameters(_serialization.Model): - """Specifies the properties for connecting to an AML vectorizer. - - All required parameters must be populated in order to send to server. - - :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - Required. - :vartype scoring_uri: str - :ivar authentication_key: (Required for key authentication) The key for the AML service. - :vartype authentication_key: str - :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID - of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :vartype resource_id: str - :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the - API call. - :vartype timeout: ~datetime.timedelta - :ivar region: (Optional for token authentication). The region the AML service is deployed in. - :vartype region: str - :ivar model_name: The name of the embedding model from the Azure AI Foundry Catalog that is - deployed at the provided endpoint. Known values are: - "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", - "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", - "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", - "Cohere-embed-v3-english", "Cohere-embed-v3-multilingual", and "Cohere-embed-v4". - :vartype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName - """ - - _validation = { - "scoring_uri": {"required": True}, - } - - _attribute_map = { - "scoring_uri": {"key": "uri", "type": "str"}, - "authentication_key": {"key": "key", "type": "str"}, - "resource_id": {"key": "resourceId", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "region": {"key": "region", "type": "str"}, - "model_name": {"key": "modelName", "type": "str"}, - } - - def __init__( - self, - *, - scoring_uri: str, - authentication_key: Optional[str] = None, - resource_id: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - region: Optional[str] = None, - model_name: Optional[Union[str, "_models.AIFoundryModelCatalogName"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - Required. - :paramtype scoring_uri: str - :keyword authentication_key: (Required for key authentication) The key for the AML service. - :paramtype authentication_key: str - :keyword resource_id: (Required for token authentication). The Azure Resource Manager resource - ID of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :paramtype resource_id: str - :keyword timeout: (Optional) When specified, indicates the timeout for the http client making - the API call. - :paramtype timeout: ~datetime.timedelta - :keyword region: (Optional for token authentication). The region the AML service is deployed - in. - :paramtype region: str - :keyword model_name: The name of the embedding model from the Azure AI Foundry Catalog that is - deployed at the provided endpoint. Known values are: - "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", - "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", - "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", - "Cohere-embed-v3-english", "Cohere-embed-v3-multilingual", and "Cohere-embed-v4". - :paramtype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName - """ - super().__init__(**kwargs) - self.scoring_uri = scoring_uri - self.authentication_key = authentication_key - self.resource_id = resource_id - self.timeout = timeout - self.region = region - self.model_name = model_name - - -class SearchIndexerSkill(_serialization.Model): - """Base type for skills. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureMachineLearningSkill, WebApiSkill, AzureOpenAIEmbeddingSkill, CustomEntityLookupSkill, - EntityRecognitionSkill, KeyPhraseExtractionSkill, LanguageDetectionSkill, MergeSkill, - PIIDetectionSkill, SentimentSkill, SplitSkill, TextTranslationSkill, EntityLinkingSkill, - EntityRecognitionSkillV3, SentimentSkillV3, ConditionalSkill, ContentUnderstandingSkill, - DocumentExtractionSkill, DocumentIntelligenceLayoutSkill, ShaperSkill, ImageAnalysisSkill, - OcrSkill, VisionVectorizeSkill - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Skills.Custom.AmlSkill": "AzureMachineLearningSkill", - "#Microsoft.Skills.Custom.WebApiSkill": "WebApiSkill", - "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill": "AzureOpenAIEmbeddingSkill", - "#Microsoft.Skills.Text.CustomEntityLookupSkill": "CustomEntityLookupSkill", - "#Microsoft.Skills.Text.EntityRecognitionSkill": "EntityRecognitionSkill", - "#Microsoft.Skills.Text.KeyPhraseExtractionSkill": "KeyPhraseExtractionSkill", - "#Microsoft.Skills.Text.LanguageDetectionSkill": "LanguageDetectionSkill", - "#Microsoft.Skills.Text.MergeSkill": "MergeSkill", - "#Microsoft.Skills.Text.PIIDetectionSkill": "PIIDetectionSkill", - "#Microsoft.Skills.Text.SentimentSkill": "SentimentSkill", - "#Microsoft.Skills.Text.SplitSkill": "SplitSkill", - "#Microsoft.Skills.Text.TranslationSkill": "TextTranslationSkill", - "#Microsoft.Skills.Text.V3.EntityLinkingSkill": "EntityLinkingSkill", - "#Microsoft.Skills.Text.V3.EntityRecognitionSkill": "EntityRecognitionSkillV3", - "#Microsoft.Skills.Text.V3.SentimentSkill": "SentimentSkillV3", - "#Microsoft.Skills.Util.ConditionalSkill": "ConditionalSkill", - "#Microsoft.Skills.Util.ContentUnderstandingSkill": "ContentUnderstandingSkill", - "#Microsoft.Skills.Util.DocumentExtractionSkill": "DocumentExtractionSkill", - "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill": "DocumentIntelligenceLayoutSkill", - "#Microsoft.Skills.Util.ShaperSkill": "ShaperSkill", - "#Microsoft.Skills.Vision.ImageAnalysisSkill": "ImageAnalysisSkill", - "#Microsoft.Skills.Vision.OcrSkill": "OcrSkill", - "#Microsoft.Skills.Vision.VectorizeSkill": "VisionVectorizeSkill", - } - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - self.description = description - self.context = context - self.inputs = inputs - self.outputs = outputs - - -class AzureMachineLearningSkill(SearchIndexerSkill): - """The AML skill allows you to extend AI enrichment with a custom Azure Machine Learning (AML) - model. Once an AML model is trained and deployed, an AML skill integrates it into AI - enrichment. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - :vartype scoring_uri: str - :ivar authentication_key: (Required for key authentication) The key for the AML service. - :vartype authentication_key: str - :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID - of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :vartype resource_id: str - :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the - API call. - :vartype timeout: ~datetime.timedelta - :ivar region: (Optional for token authentication). The region the AML service is deployed in. - :vartype region: str - :ivar degree_of_parallelism: (Optional) When specified, indicates the number of calls the - indexer will make in parallel to the endpoint you have provided. You can decrease this value if - your endpoint is failing under too high of a request load, or raise it if your endpoint is able - to accept more requests and you would like an increase in the performance of the indexer. If - not set, a default value of 5 is used. The degreeOfParallelism can be set to a maximum of 10 - and a minimum of 1. - :vartype degree_of_parallelism: int - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "scoring_uri": {"key": "uri", "type": "str"}, - "authentication_key": {"key": "key", "type": "str"}, - "resource_id": {"key": "resourceId", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "region": {"key": "region", "type": "str"}, - "degree_of_parallelism": {"key": "degreeOfParallelism", "type": "int"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - scoring_uri: Optional[str] = None, - authentication_key: Optional[str] = None, - resource_id: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - region: Optional[str] = None, - degree_of_parallelism: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - :paramtype scoring_uri: str - :keyword authentication_key: (Required for key authentication) The key for the AML service. - :paramtype authentication_key: str - :keyword resource_id: (Required for token authentication). The Azure Resource Manager resource - ID of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :paramtype resource_id: str - :keyword timeout: (Optional) When specified, indicates the timeout for the http client making - the API call. - :paramtype timeout: ~datetime.timedelta - :keyword region: (Optional for token authentication). The region the AML service is deployed - in. - :paramtype region: str - :keyword degree_of_parallelism: (Optional) When specified, indicates the number of calls the - indexer will make in parallel to the endpoint you have provided. You can decrease this value if - your endpoint is failing under too high of a request load, or raise it if your endpoint is able - to accept more requests and you would like an increase in the performance of the indexer. If - not set, a default value of 5 is used. The degreeOfParallelism can be set to a maximum of 10 - and a minimum of 1. - :paramtype degree_of_parallelism: int - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Custom.AmlSkill" - self.scoring_uri = scoring_uri - self.authentication_key = authentication_key - self.resource_id = resource_id - self.timeout = timeout - self.region = region - self.degree_of_parallelism = degree_of_parallelism - - -class AzureMachineLearningVectorizer(VectorSearchVectorizer): - """Specifies an Azure Machine Learning endpoint deployed via the Azure AI Foundry Model Catalog - for generating the vector embedding of a query string. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar aml_parameters: Specifies the properties of the AML vectorizer. - :vartype aml_parameters: ~azure.search.documents.indexes.models.AzureMachineLearningParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "aml_parameters": {"key": "amlParameters", "type": "AzureMachineLearningParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - aml_parameters: Optional["_models.AzureMachineLearningParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword aml_parameters: Specifies the properties of the AML vectorizer. - :paramtype aml_parameters: - ~azure.search.documents.indexes.models.AzureMachineLearningParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "aml" - self.aml_parameters = aml_parameters - - -class AzureOpenAIVectorizerParameters(_serialization.Model): - """Specifies the parameters for connecting to the Azure OpenAI resource. - - :ivar resource_url: The resource URI of the Azure OpenAI resource. - :vartype resource_url: str - :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :vartype deployment_name: str - :ivar api_key: API key of the designated Azure OpenAI resource. - :vartype api_key: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", - "gpt-5", "gpt-5-mini", and "gpt-5-nano". - :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - """ - - _attribute_map = { - "resource_url": {"key": "resourceUri", "type": "str"}, - "deployment_name": {"key": "deploymentId", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - "model_name": {"key": "modelName", "type": "str"}, - } - - def __init__( - self, - *, - resource_url: Optional[str] = None, - deployment_name: Optional[str] = None, - api_key: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_url: The resource URI of the Azure OpenAI resource. - :paramtype resource_url: str - :keyword deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :paramtype deployment_name: str - :keyword api_key: API key of the designated Azure OpenAI resource. - :paramtype api_key: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword model_name: The name of the embedding model that is deployed at the provided - deploymentId path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", - "gpt-5", "gpt-5-mini", and "gpt-5-nano". - :paramtype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - """ - super().__init__(**kwargs) - self.resource_url = resource_url - self.deployment_name = deployment_name - self.api_key = api_key - self.auth_identity = auth_identity - self.model_name = model_name - - -class AzureOpenAIEmbeddingSkill(SearchIndexerSkill, AzureOpenAIVectorizerParameters): - """Allows you to generate a vector embedding for a given text input using the Azure OpenAI - resource. - - All required parameters must be populated in order to send to server. - - :ivar resource_url: The resource URI of the Azure OpenAI resource. - :vartype resource_url: str - :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :vartype deployment_name: str - :ivar api_key: API key of the designated Azure OpenAI resource. - :vartype api_key: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", - "gpt-5", "gpt-5-mini", and "gpt-5-nano". - :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar dimensions: The number of dimensions the resulting output embeddings should have. Only - supported in text-embedding-3 and later models. - :vartype dimensions: int - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "resource_url": {"key": "resourceUri", "type": "str"}, - "deployment_name": {"key": "deploymentId", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - "model_name": {"key": "modelName", "type": "str"}, - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "dimensions": {"key": "dimensions", "type": "int"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - resource_url: Optional[str] = None, - deployment_name: Optional[str] = None, - api_key: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - dimensions: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_url: The resource URI of the Azure OpenAI resource. - :paramtype resource_url: str - :keyword deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :paramtype deployment_name: str - :keyword api_key: API key of the designated Azure OpenAI resource. - :paramtype api_key: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword model_name: The name of the embedding model that is deployed at the provided - deploymentId path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", - "gpt-5", "gpt-5-mini", and "gpt-5-nano". - :paramtype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword dimensions: The number of dimensions the resulting output embeddings should have. Only - supported in text-embedding-3 and later models. - :paramtype dimensions: int - """ - super().__init__( - name=name, - description=description, - context=context, - inputs=inputs, - outputs=outputs, - resource_url=resource_url, - deployment_name=deployment_name, - api_key=api_key, - auth_identity=auth_identity, - model_name=model_name, - **kwargs - ) - self.resource_url = resource_url - self.deployment_name = deployment_name - self.api_key = api_key - self.auth_identity = auth_identity - self.model_name = model_name - self.odata_type: str = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill" - self.dimensions = dimensions - self.name = name - self.description = description - self.context = context - self.inputs = inputs - self.outputs = outputs - - -class AzureOpenAITokenizerParameters(_serialization.Model): - """AzureOpenAITokenizerParameters. - - :ivar encoder_model_name: Only applies if the unit is set to azureOpenAITokens. Options include - 'R50k_base', 'P50k_base', 'P50k_edit' and 'CL100k_base'. The default value is 'CL100k_base'. - Known values are: "r50k_base", "p50k_base", "p50k_edit", and "cl100k_base". - :vartype encoder_model_name: str or - ~azure.search.documents.indexes.models.SplitSkillEncoderModelName - :ivar allowed_special_tokens: (Optional) Only applies if the unit is set to azureOpenAITokens. - This parameter defines a collection of special tokens that are permitted within the - tokenization process. - :vartype allowed_special_tokens: list[str] - """ - - _attribute_map = { - "encoder_model_name": {"key": "encoderModelName", "type": "str"}, - "allowed_special_tokens": {"key": "allowedSpecialTokens", "type": "[str]"}, - } - - def __init__( - self, - *, - encoder_model_name: Optional[Union[str, "_models.SplitSkillEncoderModelName"]] = None, - allowed_special_tokens: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword encoder_model_name: Only applies if the unit is set to azureOpenAITokens. Options - include 'R50k_base', 'P50k_base', 'P50k_edit' and 'CL100k_base'. The default value is - 'CL100k_base'. Known values are: "r50k_base", "p50k_base", "p50k_edit", and "cl100k_base". - :paramtype encoder_model_name: str or - ~azure.search.documents.indexes.models.SplitSkillEncoderModelName - :keyword allowed_special_tokens: (Optional) Only applies if the unit is set to - azureOpenAITokens. This parameter defines a collection of special tokens that are permitted - within the tokenization process. - :paramtype allowed_special_tokens: list[str] - """ - super().__init__(**kwargs) - self.encoder_model_name = encoder_model_name - self.allowed_special_tokens = allowed_special_tokens - - -class AzureOpenAIVectorizer(VectorSearchVectorizer): - """Specifies the Azure OpenAI resource used to vectorize a query string. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar parameters: Contains the parameters specific to Azure OpenAI embedding vectorization. - :vartype parameters: ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "parameters": {"key": "azureOpenAIParameters", "type": "AzureOpenAIVectorizerParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword parameters: Contains the parameters specific to Azure OpenAI embedding vectorization. - :paramtype parameters: ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "azureOpenAI" - self.parameters = parameters - - -class VectorSearchCompression(_serialization.Model): - """Contains configuration options specific to the compression method used during indexing or - querying. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - BinaryQuantizationCompression, ScalarQuantizationCompression - - All required parameters must be populated in order to send to server. - - :ivar compression_name: The name to associate with this particular configuration. Required. - :vartype compression_name: str - :ivar kind: The name of the kind of compression method being configured for use with vector - search. Required. Known values are: "scalarQuantization" and "binaryQuantization". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind - :ivar rescoring_options: Contains the options for rescoring. - :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the - vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :vartype truncation_dimension: int - """ - - _validation = { - "compression_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "compression_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "rescoring_options": {"key": "rescoringOptions", "type": "RescoringOptions"}, - "truncation_dimension": {"key": "truncationDimension", "type": "int"}, - } - - _subtype_map = { - "kind": { - "binaryQuantization": "BinaryQuantizationCompression", - "scalarQuantization": "ScalarQuantizationCompression", - } - } - - def __init__( - self, - *, - compression_name: str, - rescoring_options: Optional["_models.RescoringOptions"] = None, - truncation_dimension: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword compression_name: The name to associate with this particular configuration. Required. - :paramtype compression_name: str - :keyword rescoring_options: Contains the options for rescoring. - :paramtype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :keyword truncation_dimension: The number of dimensions to truncate the vectors to. Truncating - the vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :paramtype truncation_dimension: int - """ - super().__init__(**kwargs) - self.compression_name = compression_name - self.kind: Optional[str] = None - self.rescoring_options = rescoring_options - self.truncation_dimension = truncation_dimension - - -class BinaryQuantizationCompression(VectorSearchCompression): - """Contains configuration options specific to the binary quantization compression method used - during indexing and querying. - - All required parameters must be populated in order to send to server. - - :ivar compression_name: The name to associate with this particular configuration. Required. - :vartype compression_name: str - :ivar kind: The name of the kind of compression method being configured for use with vector - search. Required. Known values are: "scalarQuantization" and "binaryQuantization". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind - :ivar rescoring_options: Contains the options for rescoring. - :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the - vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :vartype truncation_dimension: int - """ - - _validation = { - "compression_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "compression_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "rescoring_options": {"key": "rescoringOptions", "type": "RescoringOptions"}, - "truncation_dimension": {"key": "truncationDimension", "type": "int"}, - } - - def __init__( - self, - *, - compression_name: str, - rescoring_options: Optional["_models.RescoringOptions"] = None, - truncation_dimension: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword compression_name: The name to associate with this particular configuration. Required. - :paramtype compression_name: str - :keyword rescoring_options: Contains the options for rescoring. - :paramtype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :keyword truncation_dimension: The number of dimensions to truncate the vectors to. Truncating - the vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :paramtype truncation_dimension: int - """ - super().__init__( - compression_name=compression_name, - rescoring_options=rescoring_options, - truncation_dimension=truncation_dimension, - **kwargs - ) - self.kind: str = "binaryQuantization" - - -class SimilarityAlgorithm(_serialization.Model): - """Base type for similarity algorithms. Similarity algorithms are used to calculate scores that - tie queries to documents. The higher the score, the more relevant the document is to that - specific query. Those scores are used to rank the search results. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - BM25SimilarityAlgorithm, ClassicSimilarityAlgorithm - - All required parameters must be populated in order to send to server. - - :ivar odata_type: Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.BM25Similarity": "BM25SimilarityAlgorithm", - "#Microsoft.Azure.Search.ClassicSimilarity": "ClassicSimilarityAlgorithm", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class BM25SimilarityAlgorithm(SimilarityAlgorithm): - """Ranking function based on the Okapi BM25 similarity algorithm. BM25 is a TF-IDF-like algorithm - that includes length normalization (controlled by the 'b' parameter) as well as term frequency - saturation (controlled by the 'k1' parameter). - - All required parameters must be populated in order to send to server. - - :ivar odata_type: Required. - :vartype odata_type: str - :ivar k1: This property controls the scaling function between the term frequency of each - matching terms and the final relevance score of a document-query pair. By default, a value of - 1.2 is used. A value of 0.0 means the score does not scale with an increase in term frequency. - :vartype k1: float - :ivar b: This property controls how the length of a document affects the relevance score. By - default, a value of 0.75 is used. A value of 0.0 means no length normalization is applied, - while a value of 1.0 means the score is fully normalized by the length of the document. - :vartype b: float - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "k1": {"key": "k1", "type": "float"}, - "b": {"key": "b", "type": "float"}, - } - - def __init__(self, *, k1: Optional[float] = None, b: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword k1: This property controls the scaling function between the term frequency of each - matching terms and the final relevance score of a document-query pair. By default, a value of - 1.2 is used. A value of 0.0 means the score does not scale with an increase in term frequency. - :paramtype k1: float - :keyword b: This property controls how the length of a document affects the relevance score. By - default, a value of 0.75 is used. A value of 0.0 means no length normalization is applied, - while a value of 1.0 means the score is fully normalized by the length of the document. - :paramtype b: float - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.BM25Similarity" - self.k1 = k1 - self.b = b - - -class CharFilter(_serialization.Model): - """Base type for character filters. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MappingCharFilter, PatternReplaceCharFilter - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of char filter. Required. - :vartype odata_type: str - :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.MappingCharFilter": "MappingCharFilter", - "#Microsoft.Azure.Search.PatternReplaceCharFilter": "PatternReplaceCharFilter", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the char filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class ChatCompletionResponseFormat(_serialization.Model): - """Determines how the language model's response should be serialized. Defaults to 'text'. - - :ivar type: Specifies how the LLM should format the response. Possible values: 'text' (plain - string), 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). Known - values are: "text", "jsonObject", and "jsonSchema". - :vartype type: str or ~azure.search.documents.indexes.models.ChatCompletionResponseFormatType - :ivar chat_completion_schema_properties: An open dictionary for extended properties. Required - if 'type' == 'json_schema'. - :vartype chat_completion_schema_properties: - ~azure.search.documents.indexes.models.ChatCompletionResponseFormatJsonSchemaProperties - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "chat_completion_schema_properties": { - "key": "jsonSchemaProperties", - "type": "ChatCompletionResponseFormatJsonSchemaProperties", - }, - } - - def __init__( - self, - *, - type: Union[str, "_models.ChatCompletionResponseFormatType"] = "text", - chat_completion_schema_properties: Optional["_models.ChatCompletionResponseFormatJsonSchemaProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: Specifies how the LLM should format the response. Possible values: 'text' (plain - string), 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). Known - values are: "text", "jsonObject", and "jsonSchema". - :paramtype type: str or ~azure.search.documents.indexes.models.ChatCompletionResponseFormatType - :keyword chat_completion_schema_properties: An open dictionary for extended properties. - Required if 'type' == 'json_schema'. - :paramtype chat_completion_schema_properties: - ~azure.search.documents.indexes.models.ChatCompletionResponseFormatJsonSchemaProperties - """ - super().__init__(**kwargs) - self.type = type - self.chat_completion_schema_properties = chat_completion_schema_properties - - -class ChatCompletionResponseFormatJsonSchemaProperties(_serialization.Model): # pylint: disable=name-too-long - """An open dictionary for extended properties. Required if 'type' == 'json_schema'. - - :ivar name: Name of the json schema the model will adhere to. - :vartype name: str - :ivar description: Description of the json schema the model will adhere to. - :vartype description: str - :ivar strict: Whether or not the model's response should use structured outputs. Default is - true. - :vartype strict: bool - :ivar schema: Object defining the custom schema the model will use to structure its output. - :vartype schema: ~azure.search.documents.indexes.models.ChatCompletionSchema - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "strict": {"key": "strict", "type": "bool"}, - "schema": {"key": "schema", "type": "ChatCompletionSchema"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - strict: bool = True, - schema: Optional["_models.ChatCompletionSchema"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Name of the json schema the model will adhere to. - :paramtype name: str - :keyword description: Description of the json schema the model will adhere to. - :paramtype description: str - :keyword strict: Whether or not the model's response should use structured outputs. Default is - true. - :paramtype strict: bool - :keyword schema: Object defining the custom schema the model will use to structure its output. - :paramtype schema: ~azure.search.documents.indexes.models.ChatCompletionSchema - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.strict = strict - self.schema = schema - - -class ChatCompletionSchema(_serialization.Model): - """Object defining the custom schema the model will use to structure its output. - - :ivar type: Type of schema representation. Usually 'object'. Default is 'object'. - :vartype type: str - :ivar properties: A JSON-formatted string that defines the output schema's properties and - constraints for the model. - :vartype properties: str - :ivar required: An array of the property names that are required to be part of the model's - response. All properties must be included for structured outputs. - :vartype required: list[str] - :ivar additional_properties: Controls whether it is allowable for an object to contain - additional keys / values that were not defined in the JSON Schema. Default is false. - :vartype additional_properties: bool - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "str"}, - "required": {"key": "required", "type": "[str]"}, - "additional_properties": {"key": "additionalProperties", "type": "bool"}, - } - - def __init__( - self, - *, - type: str = "object", - properties: Optional[str] = None, - required: Optional[list[str]] = None, - additional_properties: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword type: Type of schema representation. Usually 'object'. Default is 'object'. - :paramtype type: str - :keyword properties: A JSON-formatted string that defines the output schema's properties and - constraints for the model. - :paramtype properties: str - :keyword required: An array of the property names that are required to be part of the model's - response. All properties must be included for structured outputs. - :paramtype required: list[str] - :keyword additional_properties: Controls whether it is allowable for an object to contain - additional keys / values that were not defined in the JSON Schema. Default is false. - :paramtype additional_properties: bool - """ - super().__init__(**kwargs) - self.type = type - self.properties = properties - self.required = required - self.additional_properties = additional_properties # type: ignore[assignment] - - -class WebApiSkill(SearchIndexerSkill): - """A skill that can call a Web API endpoint, allowing you to extend a skillset by having it call - your custom code. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ChatCompletionSkill - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar uri: The url for the Web API. Required. - :vartype uri: str - :ivar http_headers: The headers required to make the http request. - :vartype http_headers: dict[str, str] - :ivar http_method: The method for the http request. - :vartype http_method: str - :ivar timeout: The desired timeout for the request. Default is 30 seconds. - :vartype timeout: ~datetime.timedelta - :ivar batch_size: The desired batch size which indicates number of documents. - :vartype batch_size: int - :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web - API. - :vartype degree_of_parallelism: int - :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "uri": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "uri": {"key": "uri", "type": "str"}, - "http_headers": {"key": "httpHeaders", "type": "{str}"}, - "http_method": {"key": "httpMethod", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "batch_size": {"key": "batchSize", "type": "int"}, - "degree_of_parallelism": {"key": "degreeOfParallelism", "type": "int"}, - "auth_resource_id": {"key": "authResourceId", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - } - - _subtype_map = {"odata_type": {"#Microsoft.Skills.Custom.ChatCompletionSkill": "ChatCompletionSkill"}} - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - uri: str, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, - http_method: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - batch_size: Optional[int] = None, - degree_of_parallelism: Optional[int] = None, - auth_resource_id: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword uri: The url for the Web API. Required. - :paramtype uri: str - :keyword http_headers: The headers required to make the http request. - :paramtype http_headers: dict[str, str] - :keyword http_method: The method for the http request. - :paramtype http_method: str - :keyword timeout: The desired timeout for the request. Default is 30 seconds. - :paramtype timeout: ~datetime.timedelta - :keyword batch_size: The desired batch size which indicates number of documents. - :paramtype batch_size: int - :keyword degree_of_parallelism: If set, the number of parallel calls that can be made to the - Web API. - :paramtype degree_of_parallelism: int - :keyword auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :paramtype auth_resource_id: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Custom.WebApiSkill" - self.uri = uri - self.http_headers = http_headers - self.http_method = http_method - self.timeout = timeout - self.batch_size = batch_size - self.degree_of_parallelism = degree_of_parallelism - self.auth_resource_id = auth_resource_id - self.auth_identity = auth_identity - - -class ChatCompletionSkill(WebApiSkill): - """A skill that calls a language model via Azure AI Foundry's Chat Completions endpoint. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar uri: The url for the Web API. Required. - :vartype uri: str - :ivar http_headers: The headers required to make the http request. - :vartype http_headers: dict[str, str] - :ivar http_method: The method for the http request. - :vartype http_method: str - :ivar timeout: The desired timeout for the request. Default is 30 seconds. - :vartype timeout: ~datetime.timedelta - :ivar batch_size: The desired batch size which indicates number of documents. - :vartype batch_size: int - :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web - API. - :vartype degree_of_parallelism: int - :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot be - specified at the same time. - :vartype api_key: str - :ivar common_model_parameters: Common language model parameters that customers can tweak. If - omitted, reasonable defaults will be applied. - :vartype common_model_parameters: ~azure.search.documents.indexes.models.CommonModelParameters - :ivar extra_parameters: Open-type dictionary for model-specific parameters that should be - appended to the chat completions call. Follows Azure AI Foundry’s extensibility pattern. - :vartype extra_parameters: dict[str, any] - :ivar extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. Default - is 'error'. Known values are: "passThrough", "drop", and "error". - :vartype extra_parameters_behavior: str or - ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior - :ivar response_format: Determines how the LLM should format its response. Defaults to 'text' - response type. - :vartype response_format: ~azure.search.documents.indexes.models.ChatCompletionResponseFormat - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "uri": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "uri": {"key": "uri", "type": "str"}, - "http_headers": {"key": "httpHeaders", "type": "{str}"}, - "http_method": {"key": "httpMethod", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "batch_size": {"key": "batchSize", "type": "int"}, - "degree_of_parallelism": {"key": "degreeOfParallelism", "type": "int"}, - "auth_resource_id": {"key": "authResourceId", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - "api_key": {"key": "apiKey", "type": "str"}, - "common_model_parameters": {"key": "commonModelParameters", "type": "CommonModelParameters"}, - "extra_parameters": {"key": "extraParameters", "type": "{object}"}, - "extra_parameters_behavior": {"key": "extraParametersBehavior", "type": "str"}, - "response_format": {"key": "responseFormat", "type": "ChatCompletionResponseFormat"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - uri: str, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, - http_method: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - batch_size: Optional[int] = None, - degree_of_parallelism: Optional[int] = None, - auth_resource_id: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - api_key: Optional[str] = None, - common_model_parameters: Optional["_models.CommonModelParameters"] = None, - extra_parameters: Optional[dict[str, Any]] = None, - extra_parameters_behavior: Union[str, "_models.ChatCompletionExtraParametersBehavior"] = "error", - response_format: Optional["_models.ChatCompletionResponseFormat"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword uri: The url for the Web API. Required. - :paramtype uri: str - :keyword http_headers: The headers required to make the http request. - :paramtype http_headers: dict[str, str] - :keyword http_method: The method for the http request. - :paramtype http_method: str - :keyword timeout: The desired timeout for the request. Default is 30 seconds. - :paramtype timeout: ~datetime.timedelta - :keyword batch_size: The desired batch size which indicates number of documents. - :paramtype batch_size: int - :keyword degree_of_parallelism: If set, the number of parallel calls that can be made to the - Web API. - :paramtype degree_of_parallelism: int - :keyword auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :paramtype auth_resource_id: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot - be specified at the same time. - :paramtype api_key: str - :keyword common_model_parameters: Common language model parameters that customers can tweak. If - omitted, reasonable defaults will be applied. - :paramtype common_model_parameters: - ~azure.search.documents.indexes.models.CommonModelParameters - :keyword extra_parameters: Open-type dictionary for model-specific parameters that should be - appended to the chat completions call. Follows Azure AI Foundry’s extensibility pattern. - :paramtype extra_parameters: dict[str, any] - :keyword extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. - Default is 'error'. Known values are: "passThrough", "drop", and "error". - :paramtype extra_parameters_behavior: str or - ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior - :keyword response_format: Determines how the LLM should format its response. Defaults to 'text' - response type. - :paramtype response_format: ~azure.search.documents.indexes.models.ChatCompletionResponseFormat - """ - super().__init__( - name=name, - description=description, - context=context, - inputs=inputs, - outputs=outputs, - uri=uri, - http_headers=http_headers, - http_method=http_method, - timeout=timeout, - batch_size=batch_size, - degree_of_parallelism=degree_of_parallelism, - auth_resource_id=auth_resource_id, - auth_identity=auth_identity, - **kwargs - ) - self.odata_type: str = "#Microsoft.Skills.Custom.ChatCompletionSkill" - self.api_key = api_key - self.common_model_parameters = common_model_parameters - self.extra_parameters = extra_parameters - self.extra_parameters_behavior = extra_parameters_behavior - self.response_format = response_format - - -class CjkBigramTokenFilter(TokenFilter): - """Forms bigrams of CJK terms that are generated from the standard tokenizer. This token filter is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar ignore_scripts: The scripts to ignore. - :vartype ignore_scripts: list[str or - ~azure.search.documents.indexes.models.CjkBigramTokenFilterScripts] - :ivar output_unigrams: A value indicating whether to output both unigrams and bigrams (if - true), or just bigrams (if false). Default is false. - :vartype output_unigrams: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "ignore_scripts": {"key": "ignoreScripts", "type": "[str]"}, - "output_unigrams": {"key": "outputUnigrams", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - ignore_scripts: Optional[list[Union[str, "_models.CjkBigramTokenFilterScripts"]]] = None, - output_unigrams: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword ignore_scripts: The scripts to ignore. - :paramtype ignore_scripts: list[str or - ~azure.search.documents.indexes.models.CjkBigramTokenFilterScripts] - :keyword output_unigrams: A value indicating whether to output both unigrams and bigrams (if - true), or just bigrams (if false). Default is false. - :paramtype output_unigrams: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CjkBigramTokenFilter" - self.ignore_scripts = ignore_scripts - self.output_unigrams = output_unigrams - - -class ClassicSimilarityAlgorithm(SimilarityAlgorithm): - """Legacy similarity algorithm which uses the Lucene TFIDFSimilarity implementation of TF-IDF. - This variation of TF-IDF introduces static document length normalization as well as - coordinating factors that penalize documents that only partially match the searched queries. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ClassicSimilarity" - - -class LexicalTokenizer(_serialization.Model): - """Base type for tokenizers. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ClassicTokenizer, EdgeNGramTokenizer, KeywordTokenizer, KeywordTokenizerV2, - MicrosoftLanguageStemmingTokenizer, MicrosoftLanguageTokenizer, NGramTokenizer, - PathHierarchyTokenizerV2, PatternTokenizer, LuceneStandardTokenizer, LuceneStandardTokenizerV2, - UaxUrlEmailTokenizer - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.ClassicTokenizer": "ClassicTokenizer", - "#Microsoft.Azure.Search.EdgeNGramTokenizer": "EdgeNGramTokenizer", - "#Microsoft.Azure.Search.KeywordTokenizer": "KeywordTokenizer", - "#Microsoft.Azure.Search.KeywordTokenizerV2": "KeywordTokenizerV2", - "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer": "MicrosoftLanguageStemmingTokenizer", - "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer": "MicrosoftLanguageTokenizer", - "#Microsoft.Azure.Search.NGramTokenizer": "NGramTokenizer", - "#Microsoft.Azure.Search.PathHierarchyTokenizerV2": "PathHierarchyTokenizerV2", - "#Microsoft.Azure.Search.PatternTokenizer": "PatternTokenizer", - "#Microsoft.Azure.Search.StandardTokenizer": "LuceneStandardTokenizer", - "#Microsoft.Azure.Search.StandardTokenizerV2": "LuceneStandardTokenizerV2", - "#Microsoft.Azure.Search.UaxUrlEmailTokenizer": "UaxUrlEmailTokenizer", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class ClassicTokenizer(LexicalTokenizer): - """Grammar-based tokenizer that is suitable for processing most European-language documents. This - tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ClassicTokenizer" - self.max_token_length = max_token_length - - -class CognitiveServicesAccountKey(CognitiveServicesAccount): - """The multi-region account key of an Azure AI service resource that's attached to a skillset. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - :ivar key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :vartype key: str - """ - - _validation = { - "odata_type": {"required": True}, - "key": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "key": {"key": "key", "type": "str"}, - } - - def __init__(self, *, key: str, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - :keyword key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :paramtype key: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CognitiveServicesByKey" - self.key = key - - -class CommonGramTokenFilter(TokenFilter): - """Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed - too, with bigrams overlaid. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar common_words: The set of common words. Required. - :vartype common_words: list[str] - :ivar ignore_case: A value indicating whether common words matching will be case insensitive. - Default is false. - :vartype ignore_case: bool - :ivar use_query_mode: A value that indicates whether the token filter is in query mode. When in - query mode, the token filter generates bigrams and then removes common words and single terms - followed by a common word. Default is false. - :vartype use_query_mode: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "common_words": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "common_words": {"key": "commonWords", "type": "[str]"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - "use_query_mode": {"key": "queryMode", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - common_words: list[str], - ignore_case: bool = False, - use_query_mode: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword common_words: The set of common words. Required. - :paramtype common_words: list[str] - :keyword ignore_case: A value indicating whether common words matching will be case - insensitive. Default is false. - :paramtype ignore_case: bool - :keyword use_query_mode: A value that indicates whether the token filter is in query mode. When - in query mode, the token filter generates bigrams and then removes common words and single - terms followed by a common word. Default is false. - :paramtype use_query_mode: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CommonGramTokenFilter" - self.common_words = common_words - self.ignore_case = ignore_case - self.use_query_mode = use_query_mode - - -class CommonModelParameters(_serialization.Model): - """Common language model parameters for Chat Completions. If omitted, default values are used. - - :ivar model: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not - specified. - :vartype model: str - :ivar frequency_penalty: A float in the range [-2,2] that reduces or increases likelihood of - repeated tokens. Default is 0. - :vartype frequency_penalty: float - :ivar presence_penalty: A float in the range [-2,2] that penalizes new tokens based on their - existing presence. Default is 0. - :vartype presence_penalty: float - :ivar max_tokens: Maximum number of tokens to generate. - :vartype max_tokens: int - :ivar temperature: Sampling temperature. Default is 0.7. - :vartype temperature: float - :ivar seed: Random seed for controlling deterministic outputs. If omitted, randomization is - used. - :vartype seed: int - :ivar stop: List of stop sequences that will cut off text generation. Default is none. - :vartype stop: list[str] - """ - - _attribute_map = { - "model": {"key": "model", "type": "str"}, - "frequency_penalty": {"key": "frequencyPenalty", "type": "float"}, - "presence_penalty": {"key": "presencePenalty", "type": "float"}, - "max_tokens": {"key": "maxTokens", "type": "int"}, - "temperature": {"key": "temperature", "type": "float"}, - "seed": {"key": "seed", "type": "int"}, - "stop": {"key": "stop", "type": "[str]"}, - } - - def __init__( - self, - *, - model: Optional[str] = None, - frequency_penalty: float = 0, - presence_penalty: float = 0, - max_tokens: Optional[int] = None, - temperature: float = 0.7, - seed: Optional[int] = None, - stop: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword model: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not - specified. - :paramtype model: str - :keyword frequency_penalty: A float in the range [-2,2] that reduces or increases likelihood of - repeated tokens. Default is 0. - :paramtype frequency_penalty: float - :keyword presence_penalty: A float in the range [-2,2] that penalizes new tokens based on their - existing presence. Default is 0. - :paramtype presence_penalty: float - :keyword max_tokens: Maximum number of tokens to generate. - :paramtype max_tokens: int - :keyword temperature: Sampling temperature. Default is 0.7. - :paramtype temperature: float - :keyword seed: Random seed for controlling deterministic outputs. If omitted, randomization is - used. - :paramtype seed: int - :keyword stop: List of stop sequences that will cut off text generation. Default is none. - :paramtype stop: list[str] - """ - super().__init__(**kwargs) - self.model = model - self.frequency_penalty = frequency_penalty - self.presence_penalty = presence_penalty - self.max_tokens = max_tokens - self.temperature = temperature - self.seed = seed - self.stop = stop - - -class CompletedSynchronizationState(_serialization.Model): - """Represents the completed state of the last synchronization. - - All required parameters must be populated in order to send to server. - - :ivar start_time: The start time of the last completed synchronization. Required. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of the last completed synchronization. Required. - :vartype end_time: ~datetime.datetime - :ivar items_updates_processed: The number of item updates successfully processed in the last - synchronization. Required. - :vartype items_updates_processed: int - :ivar items_updates_failed: The number of item updates that failed in the last synchronization. - Required. - :vartype items_updates_failed: int - :ivar items_skipped: The number of items skipped in the last synchronization. Required. - :vartype items_skipped: int - """ - - _validation = { - "start_time": {"required": True}, - "end_time": {"required": True}, - "items_updates_processed": {"required": True}, - "items_updates_failed": {"required": True}, - "items_skipped": {"required": True}, - } - - _attribute_map = { - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "items_updates_processed": {"key": "itemsUpdatesProcessed", "type": "int"}, - "items_updates_failed": {"key": "itemsUpdatesFailed", "type": "int"}, - "items_skipped": {"key": "itemsSkipped", "type": "int"}, - } - - def __init__( - self, - *, - start_time: datetime.datetime, - end_time: datetime.datetime, - items_updates_processed: int, - items_updates_failed: int, - items_skipped: int, - **kwargs: Any - ) -> None: - """ - :keyword start_time: The start time of the last completed synchronization. Required. - :paramtype start_time: ~datetime.datetime - :keyword end_time: The end time of the last completed synchronization. Required. - :paramtype end_time: ~datetime.datetime - :keyword items_updates_processed: The number of item updates successfully processed in the last - synchronization. Required. - :paramtype items_updates_processed: int - :keyword items_updates_failed: The number of item updates that failed in the last - synchronization. Required. - :paramtype items_updates_failed: int - :keyword items_skipped: The number of items skipped in the last synchronization. Required. - :paramtype items_skipped: int - """ - super().__init__(**kwargs) - self.start_time = start_time - self.end_time = end_time - self.items_updates_processed = items_updates_processed - self.items_updates_failed = items_updates_failed - self.items_skipped = items_skipped - - -class ConditionalSkill(SearchIndexerSkill): - """A skill that enables scenarios that require a Boolean operation to determine the data to assign - to an output. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.ConditionalSkill" - - -class ContentUnderstandingSkill(SearchIndexerSkill): - """A skill that leverages Azure AI Content Understanding to process and extract structured - insights from documents, enabling enriched, searchable content for enhanced document indexing - and retrieval. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar extraction_options: Controls the cardinality of the content extracted from the document - by the skill. - :vartype extraction_options: list[str or - ~azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions] - :ivar chunking_properties: Controls the cardinality for chunking the content. - :vartype chunking_properties: - ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "extraction_options": {"key": "extractionOptions", "type": "[str]"}, - "chunking_properties": {"key": "chunkingProperties", "type": "ContentUnderstandingSkillChunkingProperties"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - extraction_options: Optional[list[Union[str, "_models.ContentUnderstandingSkillExtractionOptions"]]] = None, - chunking_properties: Optional["_models.ContentUnderstandingSkillChunkingProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword extraction_options: Controls the cardinality of the content extracted from the - document by the skill. - :paramtype extraction_options: list[str or - ~azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions] - :keyword chunking_properties: Controls the cardinality for chunking the content. - :paramtype chunking_properties: - ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.ContentUnderstandingSkill" - self.extraction_options = extraction_options - self.chunking_properties = chunking_properties - - -class ContentUnderstandingSkillChunkingProperties(_serialization.Model): # pylint: disable=name-too-long - """Controls the cardinality for chunking the content. - - :ivar unit: The unit of the chunk. "characters" - :vartype unit: str or - ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit - :ivar maximum_length: The maximum chunk length in characters. Default is 500. - :vartype maximum_length: int - :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. - :vartype overlap_length: int - """ - - _attribute_map = { - "unit": {"key": "unit", "type": "str"}, - "maximum_length": {"key": "maximumLength", "type": "int"}, - "overlap_length": {"key": "overlapLength", "type": "int"}, - } - - def __init__( - self, - *, - unit: Union[str, "_models.ContentUnderstandingSkillChunkingUnit"] = "characters", - maximum_length: Optional[int] = None, - overlap_length: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword unit: The unit of the chunk. "characters" - :paramtype unit: str or - ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit - :keyword maximum_length: The maximum chunk length in characters. Default is 500. - :paramtype maximum_length: int - :keyword overlap_length: The length of overlap provided between two text chunks. Default is 0. - :paramtype overlap_length: int - """ - super().__init__(**kwargs) - self.unit = unit - self.maximum_length = maximum_length - self.overlap_length = overlap_length - - -class CorsOptions(_serialization.Model): - """Defines options to control Cross-Origin Resource Sharing (CORS) for an index. - - All required parameters must be populated in order to send to server. - - :ivar allowed_origins: The list of origins from which JavaScript code will be granted access to - your index. Can contain a list of hosts of the form - {protocol}://{fully-qualified-domain-name}[:{port#}], or a single '*' to allow all origins (not - recommended). Required. - :vartype allowed_origins: list[str] - :ivar max_age_in_seconds: The duration for which browsers should cache CORS preflight - responses. Defaults to 5 minutes. - :vartype max_age_in_seconds: int - """ - - _validation = { - "allowed_origins": {"required": True}, - } - - _attribute_map = { - "allowed_origins": {"key": "allowedOrigins", "type": "[str]"}, - "max_age_in_seconds": {"key": "maxAgeInSeconds", "type": "int"}, - } - - def __init__(self, *, allowed_origins: list[str], max_age_in_seconds: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword allowed_origins: The list of origins from which JavaScript code will be granted access - to your index. Can contain a list of hosts of the form - {protocol}://{fully-qualified-domain-name}[:{port#}], or a single '*' to allow all origins (not - recommended). Required. - :paramtype allowed_origins: list[str] - :keyword max_age_in_seconds: The duration for which browsers should cache CORS preflight - responses. Defaults to 5 minutes. - :paramtype max_age_in_seconds: int - """ - super().__init__(**kwargs) - self.allowed_origins = allowed_origins - self.max_age_in_seconds = max_age_in_seconds - - -class LexicalAnalyzer(_serialization.Model): - """Base type for analyzers. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CustomAnalyzer, PatternAnalyzer, LuceneStandardAnalyzer, StopAnalyzer - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.CustomAnalyzer": "CustomAnalyzer", - "#Microsoft.Azure.Search.PatternAnalyzer": "PatternAnalyzer", - "#Microsoft.Azure.Search.StandardAnalyzer": "LuceneStandardAnalyzer", - "#Microsoft.Azure.Search.StopAnalyzer": "StopAnalyzer", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class CustomAnalyzer(LexicalAnalyzer): - """Allows you to take control over the process of converting text into indexable/searchable - tokens. It's a user-defined configuration consisting of a single predefined tokenizer and one - or more filters. The tokenizer is responsible for breaking text into tokens, and the filters - for modifying tokens emitted by the tokenizer. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar tokenizer: The name of the tokenizer to use to divide continuous text into a sequence of - tokens, such as breaking a sentence into words. Required. Known values are: "classic", - "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", - "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", - "standard_v2", "uax_url_email", and "whitespace". - :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar token_filters: A list of token filters used to filter out or modify the tokens generated - by a tokenizer. For example, you can specify a lowercase filter that converts all characters to - lowercase. The filters are run in the order in which they are listed. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: A list of character filters used to prepare input text before it is - processed by the tokenizer. For instance, they can replace certain characters or symbols. The - filters are run in the order in which they are listed. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "tokenizer": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "tokenizer": {"key": "tokenizer", "type": "str"}, - "token_filters": {"key": "tokenFilters", "type": "[str]"}, - "char_filters": {"key": "charFilters", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - tokenizer: Union[str, "_models.LexicalTokenizerName"], - token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, - char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword tokenizer: The name of the tokenizer to use to divide continuous text into a sequence - of tokens, such as breaking a sentence into words. Required. Known values are: "classic", - "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", - "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", - "standard_v2", "uax_url_email", and "whitespace". - :paramtype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :keyword token_filters: A list of token filters used to filter out or modify the tokens - generated by a tokenizer. For example, you can specify a lowercase filter that converts all - characters to lowercase. The filters are run in the order in which they are listed. - :paramtype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: A list of character filters used to prepare input text before it is - processed by the tokenizer. For instance, they can replace certain characters or symbols. The - filters are run in the order in which they are listed. - :paramtype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CustomAnalyzer" - self.tokenizer = tokenizer - self.token_filters = token_filters - self.char_filters = char_filters - - -class CustomEntity(_serialization.Model): - """An object that contains information about the matches that were found, and related metadata. - - All required parameters must be populated in order to send to server. - - :ivar name: The top-level entity descriptor. Matches in the skill output will be grouped by - this name, and it should represent the "normalized" form of the text being found. Required. - :vartype name: str - :ivar description: This field can be used as a passthrough for custom metadata about the - matched text(s). The value of this field will appear with every match of its entity in the - skill output. - :vartype description: str - :ivar type: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :vartype type: str - :ivar subtype: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :vartype subtype: str - :ivar id: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :vartype id: str - :ivar case_sensitive: Defaults to false. Boolean value denoting whether comparisons with the - entity name should be sensitive to character casing. Sample case insensitive matches of - "Microsoft" could be: microsoft, microSoft, MICROSOFT. - :vartype case_sensitive: bool - :ivar accent_sensitive: Defaults to false. Boolean value denoting whether comparisons with the - entity name should be sensitive to accent. - :vartype accent_sensitive: bool - :ivar fuzzy_edit_distance: Defaults to 0. Maximum value of 5. Denotes the acceptable number of - divergent characters that would still constitute a match with the entity name. The smallest - possible fuzziness for any given match is returned. For instance, if the edit distance is set - to 3, "Windows10" would still match "Windows", "Windows10" and "Windows 7". When case - sensitivity is set to false, case differences do NOT count towards fuzziness tolerance, but - otherwise do. - :vartype fuzzy_edit_distance: int - :ivar default_case_sensitive: Changes the default case sensitivity value for this entity. It be - used to change the default value of all aliases caseSensitive values. - :vartype default_case_sensitive: bool - :ivar default_accent_sensitive: Changes the default accent sensitivity value for this entity. - It be used to change the default value of all aliases accentSensitive values. - :vartype default_accent_sensitive: bool - :ivar default_fuzzy_edit_distance: Changes the default fuzzy edit distance value for this - entity. It can be used to change the default value of all aliases fuzzyEditDistance values. - :vartype default_fuzzy_edit_distance: int - :ivar aliases: An array of complex objects that can be used to specify alternative spellings or - synonyms to the root entity name. - :vartype aliases: list[~azure.search.documents.indexes.models.CustomEntityAlias] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "subtype": {"key": "subtype", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "case_sensitive": {"key": "caseSensitive", "type": "bool"}, - "accent_sensitive": {"key": "accentSensitive", "type": "bool"}, - "fuzzy_edit_distance": {"key": "fuzzyEditDistance", "type": "int"}, - "default_case_sensitive": {"key": "defaultCaseSensitive", "type": "bool"}, - "default_accent_sensitive": {"key": "defaultAccentSensitive", "type": "bool"}, - "default_fuzzy_edit_distance": {"key": "defaultFuzzyEditDistance", "type": "int"}, - "aliases": {"key": "aliases", "type": "[CustomEntityAlias]"}, - } - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - type: Optional[str] = None, - subtype: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - case_sensitive: Optional[bool] = None, - accent_sensitive: Optional[bool] = None, - fuzzy_edit_distance: Optional[int] = None, - default_case_sensitive: Optional[bool] = None, - default_accent_sensitive: Optional[bool] = None, - default_fuzzy_edit_distance: Optional[int] = None, - aliases: Optional[list["_models.CustomEntityAlias"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The top-level entity descriptor. Matches in the skill output will be grouped by - this name, and it should represent the "normalized" form of the text being found. Required. - :paramtype name: str - :keyword description: This field can be used as a passthrough for custom metadata about the - matched text(s). The value of this field will appear with every match of its entity in the - skill output. - :paramtype description: str - :keyword type: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :paramtype type: str - :keyword subtype: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :paramtype subtype: str - :keyword id: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :paramtype id: str - :keyword case_sensitive: Defaults to false. Boolean value denoting whether comparisons with the - entity name should be sensitive to character casing. Sample case insensitive matches of - "Microsoft" could be: microsoft, microSoft, MICROSOFT. - :paramtype case_sensitive: bool - :keyword accent_sensitive: Defaults to false. Boolean value denoting whether comparisons with - the entity name should be sensitive to accent. - :paramtype accent_sensitive: bool - :keyword fuzzy_edit_distance: Defaults to 0. Maximum value of 5. Denotes the acceptable number - of divergent characters that would still constitute a match with the entity name. The smallest - possible fuzziness for any given match is returned. For instance, if the edit distance is set - to 3, "Windows10" would still match "Windows", "Windows10" and "Windows 7". When case - sensitivity is set to false, case differences do NOT count towards fuzziness tolerance, but - otherwise do. - :paramtype fuzzy_edit_distance: int - :keyword default_case_sensitive: Changes the default case sensitivity value for this entity. It - be used to change the default value of all aliases caseSensitive values. - :paramtype default_case_sensitive: bool - :keyword default_accent_sensitive: Changes the default accent sensitivity value for this - entity. It be used to change the default value of all aliases accentSensitive values. - :paramtype default_accent_sensitive: bool - :keyword default_fuzzy_edit_distance: Changes the default fuzzy edit distance value for this - entity. It can be used to change the default value of all aliases fuzzyEditDistance values. - :paramtype default_fuzzy_edit_distance: int - :keyword aliases: An array of complex objects that can be used to specify alternative spellings - or synonyms to the root entity name. - :paramtype aliases: list[~azure.search.documents.indexes.models.CustomEntityAlias] - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.type = type - self.subtype = subtype - self.id = id - self.case_sensitive = case_sensitive - self.accent_sensitive = accent_sensitive - self.fuzzy_edit_distance = fuzzy_edit_distance - self.default_case_sensitive = default_case_sensitive - self.default_accent_sensitive = default_accent_sensitive - self.default_fuzzy_edit_distance = default_fuzzy_edit_distance - self.aliases = aliases - - -class CustomEntityAlias(_serialization.Model): - """A complex object that can be used to specify alternative spellings or synonyms to the root - entity name. - - All required parameters must be populated in order to send to server. - - :ivar text: The text of the alias. Required. - :vartype text: str - :ivar case_sensitive: Determine if the alias is case sensitive. - :vartype case_sensitive: bool - :ivar accent_sensitive: Determine if the alias is accent sensitive. - :vartype accent_sensitive: bool - :ivar fuzzy_edit_distance: Determine the fuzzy edit distance of the alias. - :vartype fuzzy_edit_distance: int - """ - - _validation = { - "text": {"required": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "str"}, - "case_sensitive": {"key": "caseSensitive", "type": "bool"}, - "accent_sensitive": {"key": "accentSensitive", "type": "bool"}, - "fuzzy_edit_distance": {"key": "fuzzyEditDistance", "type": "int"}, - } - - def __init__( - self, - *, - text: str, - case_sensitive: Optional[bool] = None, - accent_sensitive: Optional[bool] = None, - fuzzy_edit_distance: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword text: The text of the alias. Required. - :paramtype text: str - :keyword case_sensitive: Determine if the alias is case sensitive. - :paramtype case_sensitive: bool - :keyword accent_sensitive: Determine if the alias is accent sensitive. - :paramtype accent_sensitive: bool - :keyword fuzzy_edit_distance: Determine the fuzzy edit distance of the alias. - :paramtype fuzzy_edit_distance: int - """ - super().__init__(**kwargs) - self.text = text - self.case_sensitive = case_sensitive - self.accent_sensitive = accent_sensitive - self.fuzzy_edit_distance = fuzzy_edit_distance - - -class CustomEntityLookupSkill(SearchIndexerSkill): - """A skill looks for text from a custom, user-defined list of words and phrases. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "de", "en", "es", "fi", "fr", "it", "ko", and "pt". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage - :ivar entities_definition_uri: Path to a JSON or CSV file containing all the target text to - match against. This entity definition is read at the beginning of an indexer run. Any updates - to this file during an indexer run will not take effect until subsequent runs. This config must - be accessible over HTTPS. - :vartype entities_definition_uri: str - :ivar inline_entities_definition: The inline CustomEntity definition. - :vartype inline_entities_definition: list[~azure.search.documents.indexes.models.CustomEntity] - :ivar global_default_case_sensitive: A global flag for CaseSensitive. If CaseSensitive is not - set in CustomEntity, this value will be the default value. - :vartype global_default_case_sensitive: bool - :ivar global_default_accent_sensitive: A global flag for AccentSensitive. If AccentSensitive is - not set in CustomEntity, this value will be the default value. - :vartype global_default_accent_sensitive: bool - :ivar global_default_fuzzy_edit_distance: A global flag for FuzzyEditDistance. If - FuzzyEditDistance is not set in CustomEntity, this value will be the default value. - :vartype global_default_fuzzy_edit_distance: int - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "entities_definition_uri": {"key": "entitiesDefinitionUri", "type": "str"}, - "inline_entities_definition": {"key": "inlineEntitiesDefinition", "type": "[CustomEntity]"}, - "global_default_case_sensitive": {"key": "globalDefaultCaseSensitive", "type": "bool"}, - "global_default_accent_sensitive": {"key": "globalDefaultAccentSensitive", "type": "bool"}, - "global_default_fuzzy_edit_distance": {"key": "globalDefaultFuzzyEditDistance", "type": "int"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.CustomEntityLookupSkillLanguage"]] = None, - entities_definition_uri: Optional[str] = None, - inline_entities_definition: Optional[list["_models.CustomEntity"]] = None, - global_default_case_sensitive: Optional[bool] = None, - global_default_accent_sensitive: Optional[bool] = None, - global_default_fuzzy_edit_distance: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "da", "de", "en", "es", "fi", "fr", "it", "ko", and "pt". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage - :keyword entities_definition_uri: Path to a JSON or CSV file containing all the target text to - match against. This entity definition is read at the beginning of an indexer run. Any updates - to this file during an indexer run will not take effect until subsequent runs. This config must - be accessible over HTTPS. - :paramtype entities_definition_uri: str - :keyword inline_entities_definition: The inline CustomEntity definition. - :paramtype inline_entities_definition: - list[~azure.search.documents.indexes.models.CustomEntity] - :keyword global_default_case_sensitive: A global flag for CaseSensitive. If CaseSensitive is - not set in CustomEntity, this value will be the default value. - :paramtype global_default_case_sensitive: bool - :keyword global_default_accent_sensitive: A global flag for AccentSensitive. If AccentSensitive - is not set in CustomEntity, this value will be the default value. - :paramtype global_default_accent_sensitive: bool - :keyword global_default_fuzzy_edit_distance: A global flag for FuzzyEditDistance. If - FuzzyEditDistance is not set in CustomEntity, this value will be the default value. - :paramtype global_default_fuzzy_edit_distance: int - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.CustomEntityLookupSkill" - self.default_language_code = default_language_code - self.entities_definition_uri = entities_definition_uri - self.inline_entities_definition = inline_entities_definition - self.global_default_case_sensitive = global_default_case_sensitive - self.global_default_accent_sensitive = global_default_accent_sensitive - self.global_default_fuzzy_edit_distance = global_default_fuzzy_edit_distance - - -class LexicalNormalizer(_serialization.Model): - """Base type for normalizers. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CustomNormalizer - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of normalizer. Required. - :vartype odata_type: str - :ivar name: The name of the normalizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = {"odata_type": {"#Microsoft.Azure.Search.CustomNormalizer": "CustomNormalizer"}} - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the normalizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class CustomNormalizer(LexicalNormalizer): - """Allows you to configure normalization for filterable, sortable, and facetable fields, which by - default operate with strict matching. This is a user-defined configuration consisting of at - least one or more filters, which modify the token that is stored. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of normalizer. Required. - :vartype odata_type: str - :ivar name: The name of the normalizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :vartype name: str - :ivar token_filters: A list of token filters used to filter out or modify the input token. For - example, you can specify a lowercase filter that converts all characters to lowercase. The - filters are run in the order in which they are listed. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: A list of character filters used to prepare input text before it is - processed. For instance, they can replace certain characters or symbols. The filters are run in - the order in which they are listed. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "token_filters": {"key": "tokenFilters", "type": "[str]"}, - "char_filters": {"key": "charFilters", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, - char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the normalizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :paramtype name: str - :keyword token_filters: A list of token filters used to filter out or modify the input token. - For example, you can specify a lowercase filter that converts all characters to lowercase. The - filters are run in the order in which they are listed. - :paramtype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: A list of character filters used to prepare input text before it is - processed. For instance, they can replace certain characters or symbols. The filters are run in - the order in which they are listed. - :paramtype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CustomNormalizer" - self.token_filters = token_filters - self.char_filters = char_filters - - -class DataChangeDetectionPolicy(_serialization.Model): - """Base type for data change detection policies. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - HighWaterMarkChangeDetectionPolicy, SqlIntegratedChangeTrackingPolicy - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy": "HighWaterMarkChangeDetectionPolicy", - "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy": "SqlIntegratedChangeTrackingPolicy", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class DataDeletionDetectionPolicy(_serialization.Model): - """Base type for data deletion detection policies. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - NativeBlobSoftDeleteDeletionDetectionPolicy, SoftDeleteColumnDeletionDetectionPolicy - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. - Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy": "NativeBlobSoftDeleteDeletionDetectionPolicy", - "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy": "SoftDeleteColumnDeletionDetectionPolicy", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class DataSourceCredentials(_serialization.Model): - """Represents credentials that can be used to connect to a datasource. - - :ivar connection_string: The connection string for the datasource. Set to ```` (with - brackets) if you don't want the connection string updated. Set to ```` if you want to - remove the connection string value from the datasource. - :vartype connection_string: str - """ - - _attribute_map = { - "connection_string": {"key": "connectionString", "type": "str"}, - } - - def __init__(self, *, connection_string: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword connection_string: The connection string for the datasource. Set to ```` - (with brackets) if you don't want the connection string updated. Set to ```` if you - want to remove the connection string value from the datasource. - :paramtype connection_string: str - """ - super().__init__(**kwargs) - self.connection_string = connection_string - - -class DefaultCognitiveServicesAccount(CognitiveServicesAccount): - """An empty object that represents the default Azure AI service resource for a skillset. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__(self, *, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DefaultCognitiveServices" - - -class DictionaryDecompounderTokenFilter(TokenFilter): - """Decomposes compound words found in many Germanic languages. This token filter is implemented - using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar word_list: The list of words to match against. Required. - :vartype word_list: list[str] - :ivar min_word_size: The minimum word size. Only words longer than this get processed. Default - is 5. Maximum is 300. - :vartype min_word_size: int - :ivar min_subword_size: The minimum subword size. Only subwords longer than this are outputted. - Default is 2. Maximum is 300. - :vartype min_subword_size: int - :ivar max_subword_size: The maximum subword size. Only subwords shorter than this are - outputted. Default is 15. Maximum is 300. - :vartype max_subword_size: int - :ivar only_longest_match: A value indicating whether to add only the longest matching subword - to the output. Default is false. - :vartype only_longest_match: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "word_list": {"required": True}, - "min_word_size": {"maximum": 300}, - "min_subword_size": {"maximum": 300}, - "max_subword_size": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "word_list": {"key": "wordList", "type": "[str]"}, - "min_word_size": {"key": "minWordSize", "type": "int"}, - "min_subword_size": {"key": "minSubwordSize", "type": "int"}, - "max_subword_size": {"key": "maxSubwordSize", "type": "int"}, - "only_longest_match": {"key": "onlyLongestMatch", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - word_list: list[str], - min_word_size: int = 5, - min_subword_size: int = 2, - max_subword_size: int = 15, - only_longest_match: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword word_list: The list of words to match against. Required. - :paramtype word_list: list[str] - :keyword min_word_size: The minimum word size. Only words longer than this get processed. - Default is 5. Maximum is 300. - :paramtype min_word_size: int - :keyword min_subword_size: The minimum subword size. Only subwords longer than this are - outputted. Default is 2. Maximum is 300. - :paramtype min_subword_size: int - :keyword max_subword_size: The maximum subword size. Only subwords shorter than this are - outputted. Default is 15. Maximum is 300. - :paramtype max_subword_size: int - :keyword only_longest_match: A value indicating whether to add only the longest matching - subword to the output. Default is false. - :paramtype only_longest_match: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter" - self.word_list = word_list - self.min_word_size = min_word_size - self.min_subword_size = min_subword_size - self.max_subword_size = max_subword_size - self.only_longest_match = only_longest_match - - -class ScoringFunction(_serialization.Model): - """Base type for functions that can modify document scores during ranking. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - DistanceScoringFunction, FreshnessScoringFunction, MagnitudeScoringFunction, TagScoringFunction - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - } - - _subtype_map = { - "type": { - "distance": "DistanceScoringFunction", - "freshness": "FreshnessScoringFunction", - "magnitude": "MagnitudeScoringFunction", - "tag": "TagScoringFunction", - } - } - - def __init__( - self, - *, - field_name: str, - boost: float, - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.field_name = field_name - self.boost = boost - self.interpolation = interpolation - - -class DistanceScoringFunction(ScoringFunction): - """Defines a function that boosts scores based on distance from a geographic location. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the distance scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.DistanceScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "distance", "type": "DistanceScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.DistanceScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the distance scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.DistanceScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "distance" - self.parameters = parameters - - -class DistanceScoringParameters(_serialization.Model): - """Provides parameter values to a distance scoring function. - - All required parameters must be populated in order to send to server. - - :ivar reference_point_parameter: The name of the parameter passed in search queries to specify - the reference location. Required. - :vartype reference_point_parameter: str - :ivar boosting_distance: The distance in kilometers from the reference location where the - boosting range ends. Required. - :vartype boosting_distance: float - """ - - _validation = { - "reference_point_parameter": {"required": True}, - "boosting_distance": {"required": True}, - } - - _attribute_map = { - "reference_point_parameter": {"key": "referencePointParameter", "type": "str"}, - "boosting_distance": {"key": "boostingDistance", "type": "float"}, - } - - def __init__(self, *, reference_point_parameter: str, boosting_distance: float, **kwargs: Any) -> None: - """ - :keyword reference_point_parameter: The name of the parameter passed in search queries to - specify the reference location. Required. - :paramtype reference_point_parameter: str - :keyword boosting_distance: The distance in kilometers from the reference location where the - boosting range ends. Required. - :paramtype boosting_distance: float - """ - super().__init__(**kwargs) - self.reference_point_parameter = reference_point_parameter - self.boosting_distance = boosting_distance - - -class DocumentExtractionSkill(SearchIndexerSkill): - """A skill that extracts content from a file within the enrichment pipeline. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar parsing_mode: The parsingMode for the skill. Will be set to 'default' if not defined. - :vartype parsing_mode: str - :ivar data_to_extract: The type of data to be extracted for the skill. Will be set to - 'contentAndMetadata' if not defined. - :vartype data_to_extract: str - :ivar configuration: A dictionary of configurations for the skill. - :vartype configuration: dict[str, any] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "parsing_mode": {"key": "parsingMode", "type": "str"}, - "data_to_extract": {"key": "dataToExtract", "type": "str"}, - "configuration": {"key": "configuration", "type": "{object}"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - parsing_mode: Optional[str] = None, - data_to_extract: Optional[str] = None, - configuration: Optional[dict[str, Any]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword parsing_mode: The parsingMode for the skill. Will be set to 'default' if not defined. - :paramtype parsing_mode: str - :keyword data_to_extract: The type of data to be extracted for the skill. Will be set to - 'contentAndMetadata' if not defined. - :paramtype data_to_extract: str - :keyword configuration: A dictionary of configurations for the skill. - :paramtype configuration: dict[str, any] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.DocumentExtractionSkill" - self.parsing_mode = parsing_mode - self.data_to_extract = data_to_extract - self.configuration = configuration - - -class DocumentIntelligenceLayoutSkill(SearchIndexerSkill): - """A skill that extracts content and layout information, via Azure AI Services, from files within - the enrichment pipeline. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar output_format: Controls the cardinality of the output format. Default is 'markdown'. - Known values are: "text" and "markdown". - :vartype output_format: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat - :ivar output_mode: Controls the cardinality of the output produced by the skill. Default is - 'oneToMany'. "oneToMany" - :vartype output_mode: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode - :ivar markdown_header_depth: The depth of headers in the markdown output. Default is h6. Known - values are: "h1", "h2", "h3", "h4", "h5", and "h6". - :vartype markdown_header_depth: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth - :ivar extraction_options: Controls the cardinality of the content extracted from the document - by the skill. - :vartype extraction_options: list[str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions] - :ivar chunking_properties: Controls the cardinality for chunking the content. - :vartype chunking_properties: - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "output_format": {"key": "outputFormat", "type": "str"}, - "output_mode": {"key": "outputMode", "type": "str"}, - "markdown_header_depth": {"key": "markdownHeaderDepth", "type": "str"}, - "extraction_options": {"key": "extractionOptions", "type": "[str]"}, - "chunking_properties": { - "key": "chunkingProperties", - "type": "DocumentIntelligenceLayoutSkillChunkingProperties", - }, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - output_format: Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"] = "markdown", - output_mode: Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"] = "oneToMany", - markdown_header_depth: Union[str, "_models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth"] = "h6", - extraction_options: Optional[ - list[Union[str, "_models.DocumentIntelligenceLayoutSkillExtractionOptions"]] - ] = None, - chunking_properties: Optional["_models.DocumentIntelligenceLayoutSkillChunkingProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword output_format: Controls the cardinality of the output format. Default is 'markdown'. - Known values are: "text" and "markdown". - :paramtype output_format: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat - :keyword output_mode: Controls the cardinality of the output produced by the skill. Default is - 'oneToMany'. "oneToMany" - :paramtype output_mode: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode - :keyword markdown_header_depth: The depth of headers in the markdown output. Default is h6. - Known values are: "h1", "h2", "h3", "h4", "h5", and "h6". - :paramtype markdown_header_depth: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth - :keyword extraction_options: Controls the cardinality of the content extracted from the - document by the skill. - :paramtype extraction_options: list[str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions] - :keyword chunking_properties: Controls the cardinality for chunking the content. - :paramtype chunking_properties: - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill" - self.output_format = output_format - self.output_mode = output_mode - self.markdown_header_depth = markdown_header_depth - self.extraction_options = extraction_options - self.chunking_properties = chunking_properties - - -class DocumentIntelligenceLayoutSkillChunkingProperties(_serialization.Model): # pylint: disable=name-too-long - """Controls the cardinality for chunking the content. - - :ivar unit: The unit of the chunk. "characters" - :vartype unit: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit - :ivar maximum_length: The maximum chunk length in characters. Default is 500. - :vartype maximum_length: int - :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. - :vartype overlap_length: int - """ - - _attribute_map = { - "unit": {"key": "unit", "type": "str"}, - "maximum_length": {"key": "maximumLength", "type": "int"}, - "overlap_length": {"key": "overlapLength", "type": "int"}, - } - - def __init__( - self, - *, - unit: Union[str, "_models.DocumentIntelligenceLayoutSkillChunkingUnit"] = "characters", - maximum_length: Optional[int] = None, - overlap_length: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword unit: The unit of the chunk. "characters" - :paramtype unit: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit - :keyword maximum_length: The maximum chunk length in characters. Default is 500. - :paramtype maximum_length: int - :keyword overlap_length: The length of overlap provided between two text chunks. Default is 0. - :paramtype overlap_length: int - """ - super().__init__(**kwargs) - self.unit = unit - self.maximum_length = maximum_length - self.overlap_length = overlap_length - - -class DocumentKeysOrIds(_serialization.Model): - """DocumentKeysOrIds. - - :ivar document_keys: document keys to be reset. - :vartype document_keys: list[str] - :ivar datasource_document_ids: datasource document identifiers to be reset. - :vartype datasource_document_ids: list[str] - """ - - _attribute_map = { - "document_keys": {"key": "documentKeys", "type": "[str]"}, - "datasource_document_ids": {"key": "datasourceDocumentIds", "type": "[str]"}, - } - - def __init__( - self, - *, - document_keys: Optional[list[str]] = None, - datasource_document_ids: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword document_keys: document keys to be reset. - :paramtype document_keys: list[str] - :keyword datasource_document_ids: datasource document identifiers to be reset. - :paramtype datasource_document_ids: list[str] - """ - super().__init__(**kwargs) - self.document_keys = document_keys - self.datasource_document_ids = datasource_document_ids - - -class EdgeNGramTokenFilter(TokenFilter): - """Generates n-grams of the given size(s) starting from the front or the back of an input token. - This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. - :vartype max_gram: int - :ivar side: Specifies which side of the input the n-gram should be generated from. Default is - "front". Known values are: "front" and "back". - :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "side": {"key": "side", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. - :paramtype max_gram: int - :keyword side: Specifies which side of the input the n-gram should be generated from. Default - is "front". Known values are: "front" and "back". - :paramtype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.EdgeNGramTokenFilter" - self.min_gram = min_gram - self.max_gram = max_gram - self.side = side - - -class EdgeNGramTokenFilterV2(TokenFilter): - """Generates n-grams of the given size(s) starting from the front or the back of an input token. - This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - :ivar side: Specifies which side of the input the n-gram should be generated from. Default is - "front". Known values are: "front" and "back". - :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "side": {"key": "side", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - :keyword side: Specifies which side of the input the n-gram should be generated from. Default - is "front". Known values are: "front" and "back". - :paramtype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2" - self.min_gram = min_gram - self.max_gram = max_gram - self.side = side - - -class EdgeNGramTokenizer(LexicalTokenizer): - """Tokenizes the input from an edge into n-grams of the given size(s). This tokenizer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - :ivar token_chars: Character classes to keep in the tokens. - :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "token_chars": {"key": "tokenChars", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - :keyword token_chars: Character classes to keep in the tokens. - :paramtype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.EdgeNGramTokenizer" - self.min_gram = min_gram - self.max_gram = max_gram - self.token_chars = token_chars - - -class ElisionTokenFilter(TokenFilter): - """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). This - token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar articles: The set of articles to remove. - :vartype articles: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "articles": {"key": "articles", "type": "[str]"}, - } - - def __init__(self, *, name: str, articles: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword articles: The set of articles to remove. - :paramtype articles: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ElisionTokenFilter" - self.articles = articles - - -class EntityLinkingSkill(SearchIndexerSkill): - """Using the Text Analytics API, extracts linked entities from text. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[str] = None, - minimum_precision: Optional[float] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.V3.EntityLinkingSkill" - self.default_language_code = default_language_code - self.minimum_precision = minimum_precision - self.model_version = model_version - - -class EntityRecognitionSkill(SearchIndexerSkill): - """This skill is deprecated. Use the V3.EntityRecognitionSkill instead. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar categories: A list of entity categories that should be extracted. - :vartype categories: list[str or ~azure.search.documents.indexes.models.EntityCategory] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", "el", - "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", and "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage - :ivar include_typeless_entities: Determines whether or not to include entities which are well - known but don't conform to a pre-defined type. If this configuration is not set (default), set - to null or set to false, entities which don't conform to one of the pre-defined types will not - be surfaced. - :vartype include_typeless_entities: bool - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "categories": {"key": "categories", "type": "[str]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_typeless_entities": {"key": "includeTypelessEntities", "type": "bool"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - categories: Optional[list[Union[str, "_models.EntityCategory"]]] = None, - default_language_code: Optional[Union[str, "_models.EntityRecognitionSkillLanguage"]] = None, - include_typeless_entities: Optional[bool] = None, - minimum_precision: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword categories: A list of entity categories that should be extracted. - :paramtype categories: list[str or ~azure.search.documents.indexes.models.EntityCategory] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", - "el", "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", and "tr". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage - :keyword include_typeless_entities: Determines whether or not to include entities which are - well known but don't conform to a pre-defined type. If this configuration is not set (default), - set to null or set to false, entities which don't conform to one of the pre-defined types will - not be surfaced. - :paramtype include_typeless_entities: bool - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.EntityRecognitionSkill" - self.categories = categories - self.default_language_code = default_language_code - self.include_typeless_entities = include_typeless_entities - self.minimum_precision = minimum_precision - - -class EntityRecognitionSkillV3(SearchIndexerSkill): - """Using the Text Analytics API, extracts entities of different types from text. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar categories: A list of entity categories that should be extracted. - :vartype categories: list[str] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar model_version: The version of the model to use when calling the Text Analytics API. It - will default to the latest available when not specified. We recommend you do not specify this - value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "categories": {"key": "categories", "type": "[str]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - categories: Optional[list[str]] = None, - default_language_code: Optional[str] = None, - minimum_precision: Optional[float] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword categories: A list of entity categories that should be extracted. - :paramtype categories: list[str] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - :keyword model_version: The version of the model to use when calling the Text Analytics API. It - will default to the latest available when not specified. We recommend you do not specify this - value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill" - self.categories = categories - self.default_language_code = default_language_code - self.minimum_precision = minimum_precision - self.model_version = model_version - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.indexes.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.search.documents.indexes.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.search.documents.indexes.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.search.documents.indexes.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class VectorSearchAlgorithmConfiguration(_serialization.Model): - """Contains configuration options specific to the algorithm used during indexing or querying. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ExhaustiveKnnAlgorithmConfiguration, HnswAlgorithmConfiguration - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular configuration. Required. - :vartype name: str - :ivar kind: The name of the kind of algorithm being configured for use with vector search. - Required. Known values are: "hnsw" and "exhaustiveKnn". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": {"exhaustiveKnn": "ExhaustiveKnnAlgorithmConfiguration", "hnsw": "HnswAlgorithmConfiguration"} - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name to associate with this particular configuration. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - self.kind: Optional[str] = None - - -class ExhaustiveKnnAlgorithmConfiguration(VectorSearchAlgorithmConfiguration): - """Contains configuration options specific to the exhaustive KNN algorithm used during querying, - which will perform brute-force search across the entire vector index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular configuration. Required. - :vartype name: str - :ivar kind: The name of the kind of algorithm being configured for use with vector search. - Required. Known values are: "hnsw" and "exhaustiveKnn". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind - :ivar parameters: Contains the parameters specific to exhaustive KNN algorithm. - :vartype parameters: ~azure.search.documents.indexes.models.ExhaustiveKnnParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "parameters": {"key": "exhaustiveKnnParameters", "type": "ExhaustiveKnnParameters"}, - } - - def __init__( - self, *, name: str, parameters: Optional["_models.ExhaustiveKnnParameters"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: The name to associate with this particular configuration. Required. - :paramtype name: str - :keyword parameters: Contains the parameters specific to exhaustive KNN algorithm. - :paramtype parameters: ~azure.search.documents.indexes.models.ExhaustiveKnnParameters - """ - super().__init__(name=name, **kwargs) - self.kind: str = "exhaustiveKnn" - self.parameters = parameters - - -class ExhaustiveKnnParameters(_serialization.Model): - """Contains the parameters specific to exhaustive KNN algorithm. - - :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", - "euclidean", "dotProduct", and "hamming". - :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - - _attribute_map = { - "metric": {"key": "metric", "type": "str"}, - } - - def __init__( - self, *, metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, **kwargs: Any - ) -> None: - """ - :keyword metric: The similarity metric to use for vector comparisons. Known values are: - "cosine", "euclidean", "dotProduct", and "hamming". - :paramtype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - super().__init__(**kwargs) - self.metric = metric - - -class FieldMapping(_serialization.Model): - """Defines a mapping between a field in a data source and a target field in an index. - - All required parameters must be populated in order to send to server. - - :ivar source_field_name: The name of the field in the data source. Required. - :vartype source_field_name: str - :ivar target_field_name: The name of the target field in the index. Same as the source field - name by default. - :vartype target_field_name: str - :ivar mapping_function: A function to apply to each source field value before indexing. - :vartype mapping_function: ~azure.search.documents.indexes.models.FieldMappingFunction - """ - - _validation = { - "source_field_name": {"required": True}, - } - - _attribute_map = { - "source_field_name": {"key": "sourceFieldName", "type": "str"}, - "target_field_name": {"key": "targetFieldName", "type": "str"}, - "mapping_function": {"key": "mappingFunction", "type": "FieldMappingFunction"}, - } - - def __init__( - self, - *, - source_field_name: str, - target_field_name: Optional[str] = None, - mapping_function: Optional["_models.FieldMappingFunction"] = None, - **kwargs: Any - ) -> None: - """ - :keyword source_field_name: The name of the field in the data source. Required. - :paramtype source_field_name: str - :keyword target_field_name: The name of the target field in the index. Same as the source field - name by default. - :paramtype target_field_name: str - :keyword mapping_function: A function to apply to each source field value before indexing. - :paramtype mapping_function: ~azure.search.documents.indexes.models.FieldMappingFunction - """ - super().__init__(**kwargs) - self.source_field_name = source_field_name - self.target_field_name = target_field_name - self.mapping_function = mapping_function - - -class FieldMappingFunction(_serialization.Model): - """Represents a function that transforms a value from a data source before indexing. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the field mapping function. Required. - :vartype name: str - :ivar parameters: A dictionary of parameter name/value pairs to pass to the function. Each - value must be of a primitive type. - :vartype parameters: dict[str, any] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "parameters": {"key": "parameters", "type": "{object}"}, - } - - def __init__(self, *, name: str, parameters: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the field mapping function. Required. - :paramtype name: str - :keyword parameters: A dictionary of parameter name/value pairs to pass to the function. Each - value must be of a primitive type. - :paramtype parameters: dict[str, any] - """ - super().__init__(**kwargs) - self.name = name - self.parameters = parameters - - -class FreshnessScoringFunction(ScoringFunction): - """Defines a function that boosts scores based on the value of a date-time field. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the freshness scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.FreshnessScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "freshness", "type": "FreshnessScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.FreshnessScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the freshness scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.FreshnessScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "freshness" - self.parameters = parameters - - -class FreshnessScoringParameters(_serialization.Model): - """Provides parameter values to a freshness scoring function. - - All required parameters must be populated in order to send to server. - - :ivar boosting_duration: The expiration period after which boosting will stop for a particular - document. Required. - :vartype boosting_duration: ~datetime.timedelta - """ - - _validation = { - "boosting_duration": {"required": True}, - } - - _attribute_map = { - "boosting_duration": {"key": "boostingDuration", "type": "duration"}, - } - - def __init__(self, *, boosting_duration: datetime.timedelta, **kwargs: Any) -> None: - """ - :keyword boosting_duration: The expiration period after which boosting will stop for a - particular document. Required. - :paramtype boosting_duration: ~datetime.timedelta - """ - super().__init__(**kwargs) - self.boosting_duration = boosting_duration - - -class GetIndexStatisticsResult(_serialization.Model): - """Statistics for a given index. Statistics are collected periodically and are not guaranteed to - always be up-to-date. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar document_count: The number of documents in the index. Required. - :vartype document_count: int - :ivar storage_size: The amount of storage in bytes consumed by the index. Required. - :vartype storage_size: int - :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. - Required. - :vartype vector_index_size: int - """ - - _validation = { - "document_count": {"required": True, "readonly": True}, - "storage_size": {"required": True, "readonly": True}, - "vector_index_size": {"required": True, "readonly": True}, - } - - _attribute_map = { - "document_count": {"key": "documentCount", "type": "int"}, - "storage_size": {"key": "storageSize", "type": "int"}, - "vector_index_size": {"key": "vectorIndexSize", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.document_count: Optional[int] = None - self.storage_size: Optional[int] = None - self.vector_index_size: Optional[int] = None - - -class HighWaterMarkChangeDetectionPolicy(DataChangeDetectionPolicy): - """Defines a data change detection policy that captures changes based on the value of a high water - mark column. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. - :vartype odata_type: str - :ivar high_water_mark_column_name: The name of the high water mark column. Required. - :vartype high_water_mark_column_name: str - """ - - _validation = { - "odata_type": {"required": True}, - "high_water_mark_column_name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "high_water_mark_column_name": {"key": "highWaterMarkColumnName", "type": "str"}, - } - - def __init__(self, *, high_water_mark_column_name: str, **kwargs: Any) -> None: - """ - :keyword high_water_mark_column_name: The name of the high water mark column. Required. - :paramtype high_water_mark_column_name: str - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" - self.high_water_mark_column_name = high_water_mark_column_name - - -class HnswAlgorithmConfiguration(VectorSearchAlgorithmConfiguration): - """Contains configuration options specific to the HNSW approximate nearest neighbors algorithm - used during indexing and querying. The HNSW algorithm offers a tunable trade-off between search - speed and accuracy. - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular configuration. Required. - :vartype name: str - :ivar kind: The name of the kind of algorithm being configured for use with vector search. - Required. Known values are: "hnsw" and "exhaustiveKnn". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind - :ivar parameters: Contains the parameters specific to HNSW algorithm. - :vartype parameters: ~azure.search.documents.indexes.models.HnswParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "parameters": {"key": "hnswParameters", "type": "HnswParameters"}, - } - - def __init__(self, *, name: str, parameters: Optional["_models.HnswParameters"] = None, **kwargs: Any) -> None: - """ - :keyword name: The name to associate with this particular configuration. Required. - :paramtype name: str - :keyword parameters: Contains the parameters specific to HNSW algorithm. - :paramtype parameters: ~azure.search.documents.indexes.models.HnswParameters - """ - super().__init__(name=name, **kwargs) - self.kind: str = "hnsw" - self.parameters = parameters - - -class HnswParameters(_serialization.Model): - """Contains the parameters specific to the HNSW algorithm. - - :ivar m: The number of bi-directional links created for every new element during construction. - Increasing this parameter value may improve recall and reduce retrieval times for datasets with - high intrinsic dimensionality at the expense of increased memory consumption and longer - indexing time. - :vartype m: int - :ivar ef_construction: The size of the dynamic list containing the nearest neighbors, which is - used during index time. Increasing this parameter may improve index quality, at the expense of - increased indexing time. At a certain point, increasing this parameter leads to diminishing - returns. - :vartype ef_construction: int - :ivar ef_search: The size of the dynamic list containing the nearest neighbors, which is used - during search time. Increasing this parameter may improve search results, at the expense of - slower search. At a certain point, increasing this parameter leads to diminishing returns. - :vartype ef_search: int - :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", - "euclidean", "dotProduct", and "hamming". - :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - - _validation = { - "m": {"maximum": 10, "minimum": 4}, - "ef_construction": {"maximum": 1000, "minimum": 100}, - "ef_search": {"maximum": 1000, "minimum": 100}, - } - - _attribute_map = { - "m": {"key": "m", "type": "int"}, - "ef_construction": {"key": "efConstruction", "type": "int"}, - "ef_search": {"key": "efSearch", "type": "int"}, - "metric": {"key": "metric", "type": "str"}, - } - - def __init__( - self, - *, - m: int = 4, - ef_construction: int = 400, - ef_search: int = 500, - metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword m: The number of bi-directional links created for every new element during - construction. Increasing this parameter value may improve recall and reduce retrieval times for - datasets with high intrinsic dimensionality at the expense of increased memory consumption and - longer indexing time. - :paramtype m: int - :keyword ef_construction: The size of the dynamic list containing the nearest neighbors, which - is used during index time. Increasing this parameter may improve index quality, at the expense - of increased indexing time. At a certain point, increasing this parameter leads to diminishing - returns. - :paramtype ef_construction: int - :keyword ef_search: The size of the dynamic list containing the nearest neighbors, which is - used during search time. Increasing this parameter may improve search results, at the expense - of slower search. At a certain point, increasing this parameter leads to diminishing returns. - :paramtype ef_search: int - :keyword metric: The similarity metric to use for vector comparisons. Known values are: - "cosine", "euclidean", "dotProduct", and "hamming". - :paramtype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - super().__init__(**kwargs) - self.m = m - self.ef_construction = ef_construction - self.ef_search = ef_search - self.metric = metric - - -class ImageAnalysisSkill(SearchIndexerSkill): - """A skill that analyzes image files. It extracts a rich set of visual features based on the image - content. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "ar", "az", "bg", "bs", "ca", "cs", "cy", "da", "de", "el", "en", "es", "et", - "eu", "fi", "fr", "ga", "gl", "he", "hi", "hr", "hu", "id", "it", "ja", "kk", "ko", "lt", "lv", - "mk", "ms", "nb", "nl", "pl", "prs", "pt-BR", "pt", "pt-PT", "ro", "ru", "sk", "sl", "sr-Cyrl", - "sr-Latn", "sv", "th", "tr", "uk", "vi", "zh", "zh-Hans", and "zh-Hant". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.ImageAnalysisSkillLanguage - :ivar visual_features: A list of visual features. - :vartype visual_features: list[str or ~azure.search.documents.indexes.models.VisualFeature] - :ivar details: A string indicating which domain-specific details to return. - :vartype details: list[str or ~azure.search.documents.indexes.models.ImageDetail] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "visual_features": {"key": "visualFeatures", "type": "[str]"}, - "details": {"key": "details", "type": "[str]"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.ImageAnalysisSkillLanguage"]] = None, - visual_features: Optional[list[Union[str, "_models.VisualFeature"]]] = None, - details: Optional[list[Union[str, "_models.ImageDetail"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "ar", "az", "bg", "bs", "ca", "cs", "cy", "da", "de", "el", "en", - "es", "et", "eu", "fi", "fr", "ga", "gl", "he", "hi", "hr", "hu", "id", "it", "ja", "kk", "ko", - "lt", "lv", "mk", "ms", "nb", "nl", "pl", "prs", "pt-BR", "pt", "pt-PT", "ro", "ru", "sk", - "sl", "sr-Cyrl", "sr-Latn", "sv", "th", "tr", "uk", "vi", "zh", "zh-Hans", and "zh-Hant". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.ImageAnalysisSkillLanguage - :keyword visual_features: A list of visual features. - :paramtype visual_features: list[str or ~azure.search.documents.indexes.models.VisualFeature] - :keyword details: A string indicating which domain-specific details to return. - :paramtype details: list[str or ~azure.search.documents.indexes.models.ImageDetail] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Vision.ImageAnalysisSkill" - self.default_language_code = default_language_code - self.visual_features = visual_features - self.details = details - - -class IndexedOneLakeKnowledgeSource(KnowledgeSource): - """Configuration for OneLake knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar indexed_one_lake_parameters: The parameters for the OneLake knowledge source. Required. - :vartype indexed_one_lake_parameters: - ~azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - "indexed_one_lake_parameters": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "indexed_one_lake_parameters": { - "key": "indexedOneLakeParameters", - "type": "IndexedOneLakeKnowledgeSourceParameters", - }, - } - - def __init__( - self, - *, - name: str, - indexed_one_lake_parameters: "_models.IndexedOneLakeKnowledgeSourceParameters", - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword indexed_one_lake_parameters: The parameters for the OneLake knowledge source. - Required. - :paramtype indexed_one_lake_parameters: - ~azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "indexedOneLake" - self.indexed_one_lake_parameters = indexed_one_lake_parameters - - -class IndexedOneLakeKnowledgeSourceParameters(_serialization.Model): - """Parameters for OneLake knowledge source. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar fabric_workspace_id: OneLake workspace ID. Required. - :vartype fabric_workspace_id: str - :ivar lakehouse_id: Specifies which OneLake lakehouse to access. Required. - :vartype lakehouse_id: str - :ivar target_path: Optional OneLakehouse folder or shortcut to filter OneLake content. - :vartype target_path: str - :ivar ingestion_parameters: Consolidates all general ingestion settings. - :vartype ingestion_parameters: - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionParameters - :ivar created_resources: Resources created by the knowledge source. - :vartype created_resources: dict[str, str] - """ - - _validation = { - "fabric_workspace_id": {"required": True}, - "lakehouse_id": {"required": True}, - "created_resources": {"readonly": True}, - } - - _attribute_map = { - "fabric_workspace_id": {"key": "fabricWorkspaceId", "type": "str"}, - "lakehouse_id": {"key": "lakehouseId", "type": "str"}, - "target_path": {"key": "targetPath", "type": "str"}, - "ingestion_parameters": {"key": "ingestionParameters", "type": "KnowledgeSourceIngestionParameters"}, - "created_resources": {"key": "createdResources", "type": "{str}"}, - } - - def __init__( - self, - *, - fabric_workspace_id: str, - lakehouse_id: str, - target_path: Optional[str] = None, - ingestion_parameters: Optional["_models.KnowledgeSourceIngestionParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword fabric_workspace_id: OneLake workspace ID. Required. - :paramtype fabric_workspace_id: str - :keyword lakehouse_id: Specifies which OneLake lakehouse to access. Required. - :paramtype lakehouse_id: str - :keyword target_path: Optional OneLakehouse folder or shortcut to filter OneLake content. - :paramtype target_path: str - :keyword ingestion_parameters: Consolidates all general ingestion settings. - :paramtype ingestion_parameters: - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionParameters - """ - super().__init__(**kwargs) - self.fabric_workspace_id = fabric_workspace_id - self.lakehouse_id = lakehouse_id - self.target_path = target_path - self.ingestion_parameters = ingestion_parameters - self.created_resources: Optional[dict[str, str]] = None - - -class IndexedSharePointKnowledgeSource(KnowledgeSource): - """Configuration for SharePoint knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar indexed_share_point_parameters: The parameters for the SharePoint knowledge source. - Required. - :vartype indexed_share_point_parameters: - ~azure.search.documents.indexes.models.IndexedSharePointKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - "indexed_share_point_parameters": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "indexed_share_point_parameters": { - "key": "indexedSharePointParameters", - "type": "IndexedSharePointKnowledgeSourceParameters", - }, - } - - def __init__( - self, - *, - name: str, - indexed_share_point_parameters: "_models.IndexedSharePointKnowledgeSourceParameters", - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword indexed_share_point_parameters: The parameters for the SharePoint knowledge source. - Required. - :paramtype indexed_share_point_parameters: - ~azure.search.documents.indexes.models.IndexedSharePointKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "indexedSharePoint" - self.indexed_share_point_parameters = indexed_share_point_parameters - - -class IndexedSharePointKnowledgeSourceParameters(_serialization.Model): # pylint: disable=name-too-long - """Parameters for SharePoint knowledge source. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar connection_string: SharePoint connection string with format: - SharePointOnlineEndpoint=[SharePoint site url];ApplicationId=[Azure AD App - ID];ApplicationSecret=[Azure AD App client secret];TenantId=[SharePoint site tenant id]. - Required. - :vartype connection_string: str - :ivar container_name: Specifies which SharePoint libraries to access. Required. Known values - are: "defaultSiteLibrary", "allSiteLibraries", and "useQuery". - :vartype container_name: str or - ~azure.search.documents.indexes.models.IndexedSharePointContainerName - :ivar query: Optional query to filter SharePoint content. - :vartype query: str - :ivar ingestion_parameters: Consolidates all general ingestion settings. - :vartype ingestion_parameters: - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionParameters - :ivar created_resources: Resources created by the knowledge source. - :vartype created_resources: dict[str, str] - """ - - _validation = { - "connection_string": {"required": True}, - "container_name": {"required": True}, - "created_resources": {"readonly": True}, - } - - _attribute_map = { - "connection_string": {"key": "connectionString", "type": "str"}, - "container_name": {"key": "containerName", "type": "str"}, - "query": {"key": "query", "type": "str"}, - "ingestion_parameters": {"key": "ingestionParameters", "type": "KnowledgeSourceIngestionParameters"}, - "created_resources": {"key": "createdResources", "type": "{str}"}, - } - - def __init__( - self, - *, - connection_string: str, - container_name: Union[str, "_models.IndexedSharePointContainerName"], - query: Optional[str] = None, - ingestion_parameters: Optional["_models.KnowledgeSourceIngestionParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword connection_string: SharePoint connection string with format: - SharePointOnlineEndpoint=[SharePoint site url];ApplicationId=[Azure AD App - ID];ApplicationSecret=[Azure AD App client secret];TenantId=[SharePoint site tenant id]. - Required. - :paramtype connection_string: str - :keyword container_name: Specifies which SharePoint libraries to access. Required. Known values - are: "defaultSiteLibrary", "allSiteLibraries", and "useQuery". - :paramtype container_name: str or - ~azure.search.documents.indexes.models.IndexedSharePointContainerName - :keyword query: Optional query to filter SharePoint content. - :paramtype query: str - :keyword ingestion_parameters: Consolidates all general ingestion settings. - :paramtype ingestion_parameters: - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionParameters - """ - super().__init__(**kwargs) - self.connection_string = connection_string - self.container_name = container_name - self.query = query - self.ingestion_parameters = ingestion_parameters - self.created_resources: Optional[dict[str, str]] = None - - -class IndexerCurrentState(_serialization.Model): - """Represents all of the state that defines and dictates the indexer's current execution. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", - "indexingResetDocs", and "indexingResync". - :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode - :ivar all_docs_initial_tracking_state: Change tracking state used when indexing starts on all - documents in the datasource. - :vartype all_docs_initial_tracking_state: str - :ivar all_docs_final_tracking_state: Change tracking state value when indexing finishes on all - documents in the datasource. - :vartype all_docs_final_tracking_state: str - :ivar reset_docs_initial_tracking_state: Change tracking state used when indexing starts on - select, reset documents in the datasource. - :vartype reset_docs_initial_tracking_state: str - :ivar reset_docs_final_tracking_state: Change tracking state value when indexing finishes on - select, reset documents in the datasource. - :vartype reset_docs_final_tracking_state: str - :ivar reset_document_keys: The list of document keys that have been reset. The document key is - the document's unique identifier for the data in the search index. The indexer will prioritize - selectively re-ingesting these keys. - :vartype reset_document_keys: list[str] - :ivar reset_datasource_document_ids: The list of datasource document ids that have been reset. - The datasource document id is the unique identifier for the data in the datasource. The indexer - will prioritize selectively re-ingesting these ids. - :vartype reset_datasource_document_ids: list[str] - :ivar resync_initial_tracking_state: Change tracking state used when indexing starts on - selective options from the datasource. - :vartype resync_initial_tracking_state: str - :ivar resync_final_tracking_state: Change tracking state value when indexing finishes on - selective options from the datasource. - :vartype resync_final_tracking_state: str - """ - - _validation = { - "mode": {"readonly": True}, - "all_docs_initial_tracking_state": {"readonly": True}, - "all_docs_final_tracking_state": {"readonly": True}, - "reset_docs_initial_tracking_state": {"readonly": True}, - "reset_docs_final_tracking_state": {"readonly": True}, - "reset_document_keys": {"readonly": True}, - "reset_datasource_document_ids": {"readonly": True}, - "resync_initial_tracking_state": {"readonly": True}, - "resync_final_tracking_state": {"readonly": True}, - } - - _attribute_map = { - "mode": {"key": "mode", "type": "str"}, - "all_docs_initial_tracking_state": {"key": "allDocsInitialTrackingState", "type": "str"}, - "all_docs_final_tracking_state": {"key": "allDocsFinalTrackingState", "type": "str"}, - "reset_docs_initial_tracking_state": {"key": "resetDocsInitialTrackingState", "type": "str"}, - "reset_docs_final_tracking_state": {"key": "resetDocsFinalTrackingState", "type": "str"}, - "reset_document_keys": {"key": "resetDocumentKeys", "type": "[str]"}, - "reset_datasource_document_ids": {"key": "resetDatasourceDocumentIds", "type": "[str]"}, - "resync_initial_tracking_state": {"key": "resyncInitialTrackingState", "type": "str"}, - "resync_final_tracking_state": {"key": "resyncFinalTrackingState", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.mode: Optional[Union[str, "_models.IndexingMode"]] = None - self.all_docs_initial_tracking_state: Optional[str] = None - self.all_docs_final_tracking_state: Optional[str] = None - self.reset_docs_initial_tracking_state: Optional[str] = None - self.reset_docs_final_tracking_state: Optional[str] = None - self.reset_document_keys: Optional[list[str]] = None - self.reset_datasource_document_ids: Optional[list[str]] = None - self.resync_initial_tracking_state: Optional[str] = None - self.resync_final_tracking_state: Optional[str] = None - - -class IndexerExecutionResult(_serialization.Model): - """Represents the result of an individual indexer execution. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar status: The outcome of this indexer execution. Required. Known values are: - "transientFailure", "success", "inProgress", and "reset". - :vartype status: str or ~azure.search.documents.indexes.models.IndexerExecutionStatus - :ivar status_detail: The outcome of this indexer execution. Known values are: "resetDocs" and - "resync". - :vartype status_detail: str or - ~azure.search.documents.indexes.models.IndexerExecutionStatusDetail - :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", - "indexingResetDocs", and "indexingResync". - :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode - :ivar error_message: The error message indicating the top-level error, if any. - :vartype error_message: str - :ivar start_time: The start time of this indexer execution. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of this indexer execution, if the execution has already completed. - :vartype end_time: ~datetime.datetime - :ivar errors: The item-level indexing errors. Required. - :vartype errors: list[~azure.search.documents.indexes.models.SearchIndexerError] - :ivar warnings: The item-level indexing warnings. Required. - :vartype warnings: list[~azure.search.documents.indexes.models.SearchIndexerWarning] - :ivar item_count: The number of items that were processed during this indexer execution. This - includes both successfully processed items and items where indexing was attempted but failed. - Required. - :vartype item_count: int - :ivar failed_item_count: The number of items that failed to be indexed during this indexer - execution. Required. - :vartype failed_item_count: int - :ivar initial_tracking_state: Change tracking state with which an indexer execution started. - :vartype initial_tracking_state: str - :ivar final_tracking_state: Change tracking state with which an indexer execution finished. - :vartype final_tracking_state: str - """ - - _validation = { - "status": {"required": True, "readonly": True}, - "status_detail": {"readonly": True}, - "mode": {"readonly": True}, - "error_message": {"readonly": True}, - "start_time": {"readonly": True}, - "end_time": {"readonly": True}, - "errors": {"required": True, "readonly": True}, - "warnings": {"required": True, "readonly": True}, - "item_count": {"required": True, "readonly": True}, - "failed_item_count": {"required": True, "readonly": True}, - "initial_tracking_state": {"readonly": True}, - "final_tracking_state": {"readonly": True}, - } - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - "status_detail": {"key": "statusDetail", "type": "str"}, - "mode": {"key": "mode", "type": "str"}, - "error_message": {"key": "errorMessage", "type": "str"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "errors": {"key": "errors", "type": "[SearchIndexerError]"}, - "warnings": {"key": "warnings", "type": "[SearchIndexerWarning]"}, - "item_count": {"key": "itemsProcessed", "type": "int"}, - "failed_item_count": {"key": "itemsFailed", "type": "int"}, - "initial_tracking_state": {"key": "initialTrackingState", "type": "str"}, - "final_tracking_state": {"key": "finalTrackingState", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.status: Optional[Union[str, "_models.IndexerExecutionStatus"]] = None - self.status_detail: Optional[Union[str, "_models.IndexerExecutionStatusDetail"]] = None - self.mode: Optional[Union[str, "_models.IndexingMode"]] = None - self.error_message: Optional[str] = None - self.start_time: Optional[datetime.datetime] = None - self.end_time: Optional[datetime.datetime] = None - self.errors: Optional[list["_models.SearchIndexerError"]] = None - self.warnings: Optional[list["_models.SearchIndexerWarning"]] = None - self.item_count: Optional[int] = None - self.failed_item_count: Optional[int] = None - self.initial_tracking_state: Optional[str] = None - self.final_tracking_state: Optional[str] = None - - -class IndexerResyncBody(_serialization.Model): - """IndexerResyncBody. - - :ivar options: Re-sync options that have been pre-defined from data source. - :vartype options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] - """ - - _attribute_map = { - "options": {"key": "options", "type": "[str]"}, - } - - def __init__( - self, *, options: Optional[list[Union[str, "_models.IndexerResyncOption"]]] = None, **kwargs: Any - ) -> None: - """ - :keyword options: Re-sync options that have been pre-defined from data source. - :paramtype options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] - """ - super().__init__(**kwargs) - self.options = options - - -class IndexerRuntime(_serialization.Model): - """Represents the indexer's cumulative runtime consumption in the service. - - All required parameters must be populated in order to send to server. - - :ivar used_seconds: Cumulative runtime of the indexer from the beginningTime to endingTime, in - seconds. Required. - :vartype used_seconds: int - :ivar remaining_seconds: Cumulative runtime remaining for all indexers in the service from the - beginningTime to endingTime, in seconds. - :vartype remaining_seconds: int - :ivar beginning_time: Beginning UTC time of the 24-hour period considered for indexer runtime - usage (inclusive). Required. - :vartype beginning_time: ~datetime.datetime - :ivar ending_time: End UTC time of the 24-hour period considered for indexer runtime usage - (inclusive). Required. - :vartype ending_time: ~datetime.datetime - """ - - _validation = { - "used_seconds": {"required": True}, - "beginning_time": {"required": True}, - "ending_time": {"required": True}, - } - - _attribute_map = { - "used_seconds": {"key": "usedSeconds", "type": "int"}, - "remaining_seconds": {"key": "remainingSeconds", "type": "int"}, - "beginning_time": {"key": "beginningTime", "type": "iso-8601"}, - "ending_time": {"key": "endingTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - used_seconds: int, - beginning_time: datetime.datetime, - ending_time: datetime.datetime, - remaining_seconds: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword used_seconds: Cumulative runtime of the indexer from the beginningTime to endingTime, - in seconds. Required. - :paramtype used_seconds: int - :keyword remaining_seconds: Cumulative runtime remaining for all indexers in the service from - the beginningTime to endingTime, in seconds. - :paramtype remaining_seconds: int - :keyword beginning_time: Beginning UTC time of the 24-hour period considered for indexer - runtime usage (inclusive). Required. - :paramtype beginning_time: ~datetime.datetime - :keyword ending_time: End UTC time of the 24-hour period considered for indexer runtime usage - (inclusive). Required. - :paramtype ending_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.used_seconds = used_seconds - self.remaining_seconds = remaining_seconds - self.beginning_time = beginning_time - self.ending_time = ending_time - - -class IndexingParameters(_serialization.Model): - """Represents parameters for indexer execution. - - :ivar batch_size: The number of items that are read from the data source and indexed as a - single batch in order to improve performance. The default depends on the data source type. - :vartype batch_size: int - :ivar max_failed_items: The maximum number of items that can fail indexing for indexer - execution to still be considered successful. -1 means no limit. Default is 0. - :vartype max_failed_items: int - :ivar max_failed_items_per_batch: The maximum number of items in a single batch that can fail - indexing for the batch to still be considered successful. -1 means no limit. Default is 0. - :vartype max_failed_items_per_batch: int - :ivar configuration: A dictionary of indexer-specific configuration properties. Each name is - the name of a specific property. Each value must be of a primitive type. - :vartype configuration: ~azure.search.documents.indexes.models.IndexingParametersConfiguration - """ - - _attribute_map = { - "batch_size": {"key": "batchSize", "type": "int"}, - "max_failed_items": {"key": "maxFailedItems", "type": "int"}, - "max_failed_items_per_batch": {"key": "maxFailedItemsPerBatch", "type": "int"}, - "configuration": {"key": "configuration", "type": "IndexingParametersConfiguration"}, - } - - def __init__( - self, - *, - batch_size: Optional[int] = None, - max_failed_items: int = 0, - max_failed_items_per_batch: int = 0, - configuration: Optional["_models.IndexingParametersConfiguration"] = None, - **kwargs: Any - ) -> None: - """ - :keyword batch_size: The number of items that are read from the data source and indexed as a - single batch in order to improve performance. The default depends on the data source type. - :paramtype batch_size: int - :keyword max_failed_items: The maximum number of items that can fail indexing for indexer - execution to still be considered successful. -1 means no limit. Default is 0. - :paramtype max_failed_items: int - :keyword max_failed_items_per_batch: The maximum number of items in a single batch that can - fail indexing for the batch to still be considered successful. -1 means no limit. Default is 0. - :paramtype max_failed_items_per_batch: int - :keyword configuration: A dictionary of indexer-specific configuration properties. Each name is - the name of a specific property. Each value must be of a primitive type. - :paramtype configuration: - ~azure.search.documents.indexes.models.IndexingParametersConfiguration - """ - super().__init__(**kwargs) - self.batch_size = batch_size - self.max_failed_items = max_failed_items - self.max_failed_items_per_batch = max_failed_items_per_batch - self.configuration = configuration - - -class IndexingParametersConfiguration(_serialization.Model): - """A dictionary of indexer-specific configuration properties. Each name is the name of a specific - property. Each value must be of a primitive type. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar parsing_mode: Represents the parsing mode for indexing from an Azure blob data source. - Known values are: "default", "text", "delimitedText", "json", "jsonArray", "jsonLines", and - "markdown". - :vartype parsing_mode: str or ~azure.search.documents.indexes.models.BlobIndexerParsingMode - :ivar excluded_file_name_extensions: Comma-delimited list of filename extensions to ignore when - processing from Azure blob storage. For example, you could exclude ".png, .mp4" to skip over - those files during indexing. - :vartype excluded_file_name_extensions: str - :ivar indexed_file_name_extensions: Comma-delimited list of filename extensions to select when - processing from Azure blob storage. For example, you could focus indexing on specific - application files ".docx, .pptx, .msg" to specifically include those file types. - :vartype indexed_file_name_extensions: str - :ivar fail_on_unsupported_content_type: For Azure blobs, set to false if you want to continue - indexing when an unsupported content type is encountered, and you don't know all the content - types (file extensions) in advance. - :vartype fail_on_unsupported_content_type: bool - :ivar fail_on_unprocessable_document: For Azure blobs, set to false if you want to continue - indexing if a document fails indexing. - :vartype fail_on_unprocessable_document: bool - :ivar index_storage_metadata_only_for_oversized_documents: For Azure blobs, set this property - to true to still index storage metadata for blob content that is too large to process. - Oversized blobs are treated as errors by default. For limits on blob size, see - https://learn.microsoft.com/azure/search/search-limits-quotas-capacity. - :vartype index_storage_metadata_only_for_oversized_documents: bool - :ivar delimited_text_headers: For CSV blobs, specifies a comma-delimited list of column - headers, useful for mapping source fields to destination fields in an index. - :vartype delimited_text_headers: str - :ivar delimited_text_delimiter: For CSV blobs, specifies the end-of-line single-character - delimiter for CSV files where each line starts a new document (for example, "|"). - :vartype delimited_text_delimiter: str - :ivar first_line_contains_headers: For CSV blobs, indicates that the first (non-blank) line of - each blob contains headers. - :vartype first_line_contains_headers: bool - :ivar markdown_parsing_submode: Specifies the submode that will determine whether a markdown - file will be parsed into exactly one search document or multiple search documents. Default is - ``oneToMany``. Known values are: "oneToMany" and "oneToOne". - :vartype markdown_parsing_submode: str or - ~azure.search.documents.indexes.models.MarkdownParsingSubmode - :ivar markdown_header_depth: Specifies the max header depth that will be considered while - grouping markdown content. Default is ``h6``. Known values are: "h1", "h2", "h3", "h4", "h5", - and "h6". - :vartype markdown_header_depth: str or - ~azure.search.documents.indexes.models.MarkdownHeaderDepth - :ivar document_root: For JSON arrays, given a structured or semi-structured document, you can - specify a path to the array using this property. - :vartype document_root: str - :ivar data_to_extract: Specifies the data to extract from Azure blob storage and tells the - indexer which data to extract from image content when "imageAction" is set to a value other - than "none". This applies to embedded image content in a .PDF or other application, or image - files such as .jpg and .png, in Azure blobs. Known values are: "storageMetadata", - "allMetadata", and "contentAndMetadata". - :vartype data_to_extract: str or - ~azure.search.documents.indexes.models.BlobIndexerDataToExtract - :ivar image_action: Determines how to process embedded images and image files in Azure blob - storage. Setting the "imageAction" configuration to any value other than "none" requires that - a skillset also be attached to that indexer. Known values are: "none", - "generateNormalizedImages", and "generateNormalizedImagePerPage". - :vartype image_action: str or ~azure.search.documents.indexes.models.BlobIndexerImageAction - :ivar allow_skillset_to_read_file_data: If true, will create a path //document//file_data that - is an object representing the original file data downloaded from your blob data source. This - allows you to pass the original file data to a custom skill for processing within the - enrichment pipeline, or to the Document Extraction skill. - :vartype allow_skillset_to_read_file_data: bool - :ivar pdf_text_rotation_algorithm: Determines algorithm for text extraction from PDF files in - Azure blob storage. Known values are: "none" and "detectAngles". - :vartype pdf_text_rotation_algorithm: str or - ~azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm - :ivar execution_environment: Specifies the environment in which the indexer should execute. - Known values are: "standard" and "private". - :vartype execution_environment: str or - ~azure.search.documents.indexes.models.IndexerExecutionEnvironment - :ivar query_timeout: Increases the timeout beyond the 5-minute default for Azure SQL database - data sources, specified in the format "hh:mm:ss". - :vartype query_timeout: str - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "parsing_mode": {"key": "parsingMode", "type": "str"}, - "excluded_file_name_extensions": {"key": "excludedFileNameExtensions", "type": "str"}, - "indexed_file_name_extensions": {"key": "indexedFileNameExtensions", "type": "str"}, - "fail_on_unsupported_content_type": {"key": "failOnUnsupportedContentType", "type": "bool"}, - "fail_on_unprocessable_document": {"key": "failOnUnprocessableDocument", "type": "bool"}, - "index_storage_metadata_only_for_oversized_documents": { - "key": "indexStorageMetadataOnlyForOversizedDocuments", - "type": "bool", - }, - "delimited_text_headers": {"key": "delimitedTextHeaders", "type": "str"}, - "delimited_text_delimiter": {"key": "delimitedTextDelimiter", "type": "str"}, - "first_line_contains_headers": {"key": "firstLineContainsHeaders", "type": "bool"}, - "markdown_parsing_submode": {"key": "markdownParsingSubmode", "type": "str"}, - "markdown_header_depth": {"key": "markdownHeaderDepth", "type": "str"}, - "document_root": {"key": "documentRoot", "type": "str"}, - "data_to_extract": {"key": "dataToExtract", "type": "str"}, - "image_action": {"key": "imageAction", "type": "str"}, - "allow_skillset_to_read_file_data": {"key": "allowSkillsetToReadFileData", "type": "bool"}, - "pdf_text_rotation_algorithm": {"key": "pdfTextRotationAlgorithm", "type": "str"}, - "execution_environment": {"key": "executionEnvironment", "type": "str"}, - "query_timeout": {"key": "queryTimeout", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - parsing_mode: Union[str, "_models.BlobIndexerParsingMode"] = "default", - excluded_file_name_extensions: str = "", - indexed_file_name_extensions: str = "", - fail_on_unsupported_content_type: bool = False, - fail_on_unprocessable_document: bool = False, - index_storage_metadata_only_for_oversized_documents: bool = False, - delimited_text_headers: Optional[str] = None, - delimited_text_delimiter: Optional[str] = None, - first_line_contains_headers: bool = True, - markdown_parsing_submode: Union[str, "_models.MarkdownParsingSubmode"] = "oneToMany", - markdown_header_depth: Union[str, "_models.MarkdownHeaderDepth"] = "h6", - document_root: Optional[str] = None, - data_to_extract: Union[str, "_models.BlobIndexerDataToExtract"] = "contentAndMetadata", - image_action: Union[str, "_models.BlobIndexerImageAction"] = "none", - allow_skillset_to_read_file_data: bool = False, - pdf_text_rotation_algorithm: Union[str, "_models.BlobIndexerPDFTextRotationAlgorithm"] = "none", - execution_environment: Union[str, "_models.IndexerExecutionEnvironment"] = "standard", - query_timeout: str = "00:05:00", - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword parsing_mode: Represents the parsing mode for indexing from an Azure blob data source. - Known values are: "default", "text", "delimitedText", "json", "jsonArray", "jsonLines", and - "markdown". - :paramtype parsing_mode: str or ~azure.search.documents.indexes.models.BlobIndexerParsingMode - :keyword excluded_file_name_extensions: Comma-delimited list of filename extensions to ignore - when processing from Azure blob storage. For example, you could exclude ".png, .mp4" to skip - over those files during indexing. - :paramtype excluded_file_name_extensions: str - :keyword indexed_file_name_extensions: Comma-delimited list of filename extensions to select - when processing from Azure blob storage. For example, you could focus indexing on specific - application files ".docx, .pptx, .msg" to specifically include those file types. - :paramtype indexed_file_name_extensions: str - :keyword fail_on_unsupported_content_type: For Azure blobs, set to false if you want to - continue indexing when an unsupported content type is encountered, and you don't know all the - content types (file extensions) in advance. - :paramtype fail_on_unsupported_content_type: bool - :keyword fail_on_unprocessable_document: For Azure blobs, set to false if you want to continue - indexing if a document fails indexing. - :paramtype fail_on_unprocessable_document: bool - :keyword index_storage_metadata_only_for_oversized_documents: For Azure blobs, set this - property to true to still index storage metadata for blob content that is too large to process. - Oversized blobs are treated as errors by default. For limits on blob size, see - https://learn.microsoft.com/azure/search/search-limits-quotas-capacity. - :paramtype index_storage_metadata_only_for_oversized_documents: bool - :keyword delimited_text_headers: For CSV blobs, specifies a comma-delimited list of column - headers, useful for mapping source fields to destination fields in an index. - :paramtype delimited_text_headers: str - :keyword delimited_text_delimiter: For CSV blobs, specifies the end-of-line single-character - delimiter for CSV files where each line starts a new document (for example, "|"). - :paramtype delimited_text_delimiter: str - :keyword first_line_contains_headers: For CSV blobs, indicates that the first (non-blank) line - of each blob contains headers. - :paramtype first_line_contains_headers: bool - :keyword markdown_parsing_submode: Specifies the submode that will determine whether a markdown - file will be parsed into exactly one search document or multiple search documents. Default is - ``oneToMany``. Known values are: "oneToMany" and "oneToOne". - :paramtype markdown_parsing_submode: str or - ~azure.search.documents.indexes.models.MarkdownParsingSubmode - :keyword markdown_header_depth: Specifies the max header depth that will be considered while - grouping markdown content. Default is ``h6``. Known values are: "h1", "h2", "h3", "h4", "h5", - and "h6". - :paramtype markdown_header_depth: str or - ~azure.search.documents.indexes.models.MarkdownHeaderDepth - :keyword document_root: For JSON arrays, given a structured or semi-structured document, you - can specify a path to the array using this property. - :paramtype document_root: str - :keyword data_to_extract: Specifies the data to extract from Azure blob storage and tells the - indexer which data to extract from image content when "imageAction" is set to a value other - than "none". This applies to embedded image content in a .PDF or other application, or image - files such as .jpg and .png, in Azure blobs. Known values are: "storageMetadata", - "allMetadata", and "contentAndMetadata". - :paramtype data_to_extract: str or - ~azure.search.documents.indexes.models.BlobIndexerDataToExtract - :keyword image_action: Determines how to process embedded images and image files in Azure blob - storage. Setting the "imageAction" configuration to any value other than "none" requires that - a skillset also be attached to that indexer. Known values are: "none", - "generateNormalizedImages", and "generateNormalizedImagePerPage". - :paramtype image_action: str or ~azure.search.documents.indexes.models.BlobIndexerImageAction - :keyword allow_skillset_to_read_file_data: If true, will create a path //document//file_data - that is an object representing the original file data downloaded from your blob data source. - This allows you to pass the original file data to a custom skill for processing within the - enrichment pipeline, or to the Document Extraction skill. - :paramtype allow_skillset_to_read_file_data: bool - :keyword pdf_text_rotation_algorithm: Determines algorithm for text extraction from PDF files - in Azure blob storage. Known values are: "none" and "detectAngles". - :paramtype pdf_text_rotation_algorithm: str or - ~azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm - :keyword execution_environment: Specifies the environment in which the indexer should execute. - Known values are: "standard" and "private". - :paramtype execution_environment: str or - ~azure.search.documents.indexes.models.IndexerExecutionEnvironment - :keyword query_timeout: Increases the timeout beyond the 5-minute default for Azure SQL - database data sources, specified in the format "hh:mm:ss". - :paramtype query_timeout: str - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.parsing_mode = parsing_mode - self.excluded_file_name_extensions = excluded_file_name_extensions - self.indexed_file_name_extensions = indexed_file_name_extensions - self.fail_on_unsupported_content_type = fail_on_unsupported_content_type - self.fail_on_unprocessable_document = fail_on_unprocessable_document - self.index_storage_metadata_only_for_oversized_documents = index_storage_metadata_only_for_oversized_documents - self.delimited_text_headers = delimited_text_headers - self.delimited_text_delimiter = delimited_text_delimiter - self.first_line_contains_headers = first_line_contains_headers - self.markdown_parsing_submode = markdown_parsing_submode - self.markdown_header_depth = markdown_header_depth - self.document_root = document_root - self.data_to_extract = data_to_extract - self.image_action = image_action - self.allow_skillset_to_read_file_data = allow_skillset_to_read_file_data - self.pdf_text_rotation_algorithm = pdf_text_rotation_algorithm - self.execution_environment = execution_environment - self.query_timeout = query_timeout - - -class IndexingSchedule(_serialization.Model): - """Represents a schedule for indexer execution. - - All required parameters must be populated in order to send to server. - - :ivar interval: The interval of time between indexer executions. Required. - :vartype interval: ~datetime.timedelta - :ivar start_time: The time when an indexer should start running. - :vartype start_time: ~datetime.datetime - """ - - _validation = { - "interval": {"required": True}, - } - - _attribute_map = { - "interval": {"key": "interval", "type": "duration"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - } - - def __init__( - self, *, interval: datetime.timedelta, start_time: Optional[datetime.datetime] = None, **kwargs: Any - ) -> None: - """ - :keyword interval: The interval of time between indexer executions. Required. - :paramtype interval: ~datetime.timedelta - :keyword start_time: The time when an indexer should start running. - :paramtype start_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.interval = interval - self.start_time = start_time - - -class IndexStatisticsSummary(_serialization.Model): - """Statistics for a given index. Statistics are collected periodically and are not guaranteed to - always be up-to-date. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the index. Required. - :vartype name: str - :ivar document_count: The number of documents in the index. Required. - :vartype document_count: int - :ivar storage_size: The amount of storage in bytes consumed by the index. Required. - :vartype storage_size: int - :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. - Required. - :vartype vector_index_size: int - """ - - _validation = { - "name": {"required": True}, - "document_count": {"required": True, "readonly": True}, - "storage_size": {"required": True, "readonly": True}, - "vector_index_size": {"required": True, "readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "document_count": {"key": "documentCount", "type": "int"}, - "storage_size": {"key": "storageSize", "type": "int"}, - "vector_index_size": {"key": "vectorIndexSize", "type": "int"}, - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the index. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - self.document_count: Optional[int] = None - self.storage_size: Optional[int] = None - self.vector_index_size: Optional[int] = None - - -class InputFieldMappingEntry(_serialization.Model): - """Input field mapping for a skill. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the input. Required. - :vartype name: str - :ivar source: The source of the input. - :vartype source: str - :ivar source_context: The source context used for selecting recursive inputs. - :vartype source_context: str - :ivar inputs: The recursive inputs used when creating a complex type. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - name: str, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the input. Required. - :paramtype name: str - :keyword source: The source of the input. - :paramtype source: str - :keyword source_context: The source context used for selecting recursive inputs. - :paramtype source_context: str - :keyword inputs: The recursive inputs used when creating a complex type. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.name = name - self.source = source - self.source_context = source_context - self.inputs = inputs - - -class KeepTokenFilter(TokenFilter): - """A token filter that only keeps tokens with text contained in a specified list of words. This - token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar keep_words: The list of words to keep. Required. - :vartype keep_words: list[str] - :ivar lower_case_keep_words: A value indicating whether to lower case all words first. Default - is false. - :vartype lower_case_keep_words: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "keep_words": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "keep_words": {"key": "keepWords", "type": "[str]"}, - "lower_case_keep_words": {"key": "keepWordsCase", "type": "bool"}, - } - - def __init__(self, *, name: str, keep_words: list[str], lower_case_keep_words: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword keep_words: The list of words to keep. Required. - :paramtype keep_words: list[str] - :keyword lower_case_keep_words: A value indicating whether to lower case all words first. - Default is false. - :paramtype lower_case_keep_words: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeepTokenFilter" - self.keep_words = keep_words - self.lower_case_keep_words = lower_case_keep_words - - -class KeyPhraseExtractionSkill(SearchIndexerSkill): - """A skill that uses text analytics for key phrase extraction. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "nl", "en", "fi", "fr", "de", "it", "ja", "ko", "no", "pl", "pt-PT", - "pt-BR", "ru", "es", and "sv". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage - :ivar max_key_phrase_count: A number indicating how many key phrases to return. If absent, all - identified key phrases will be returned. - :vartype max_key_phrase_count: int - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "max_key_phrase_count": {"key": "maxKeyPhraseCount", "type": "int"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.KeyPhraseExtractionSkillLanguage"]] = None, - max_key_phrase_count: Optional[int] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "da", "nl", "en", "fi", "fr", "de", "it", "ja", "ko", "no", "pl", - "pt-PT", "pt-BR", "ru", "es", and "sv". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage - :keyword max_key_phrase_count: A number indicating how many key phrases to return. If absent, - all identified key phrases will be returned. - :paramtype max_key_phrase_count: int - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.KeyPhraseExtractionSkill" - self.default_language_code = default_language_code - self.max_key_phrase_count = max_key_phrase_count - self.model_version = model_version - - -class KeywordMarkerTokenFilter(TokenFilter): - """Marks terms as keywords. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar keywords: A list of words to mark as keywords. Required. - :vartype keywords: list[str] - :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted - to lower case first. Default is false. - :vartype ignore_case: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "keywords": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "keywords": {"key": "keywords", "type": "[str]"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - } - - def __init__(self, *, name: str, keywords: list[str], ignore_case: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword keywords: A list of words to mark as keywords. Required. - :paramtype keywords: list[str] - :keyword ignore_case: A value indicating whether to ignore case. If true, all words are - converted to lower case first. Default is false. - :paramtype ignore_case: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeywordMarkerTokenFilter" - self.keywords = keywords - self.ignore_case = ignore_case - - -class KeywordTokenizer(LexicalTokenizer): - """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar buffer_size: The read buffer size in bytes. Default is 256. - :vartype buffer_size: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "buffer_size": {"key": "bufferSize", "type": "int"}, - } - - def __init__(self, *, name: str, buffer_size: int = 256, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword buffer_size: The read buffer size in bytes. Default is 256. - :paramtype buffer_size: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeywordTokenizer" - self.buffer_size = buffer_size - - -class KeywordTokenizerV2(LexicalTokenizer): - """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 256. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 256, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 256. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeywordTokenizerV2" - self.max_token_length = max_token_length - - -class KnowledgeBase(_serialization.Model): - """KnowledgeBase. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge knowledge base. Required. - :vartype name: str - :ivar knowledge_sources: Required. - :vartype knowledge_sources: - list[~azure.search.documents.indexes.models.KnowledgeSourceReference] - :ivar models: Contains configuration options on how to connect to AI models. - :vartype models: list[~azure.search.documents.indexes.models.KnowledgeBaseModel] - :ivar retrieval_reasoning_effort: - :vartype retrieval_reasoning_effort: - ~azure.search.documents.indexes.models.KnowledgeRetrievalReasoningEffort - :ivar output_mode: The output configuration for this retrieval. Known values are: - "extractiveData" and "answerSynthesis". - :vartype output_mode: str or - ~azure.search.documents.indexes.models.KnowledgeRetrievalOutputMode - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar description: The description of the knowledge base. - :vartype description: str - :ivar retrieval_instructions: Instructions considered by the knowledge knowledge base when - developing query plan. - :vartype retrieval_instructions: str - :ivar answer_instructions: Instructions considered by the knowledge knowledge base when - generating answers. - :vartype answer_instructions: str - """ - - _validation = { - "name": {"required": True}, - "knowledge_sources": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "knowledge_sources": {"key": "knowledgeSources", "type": "[KnowledgeSourceReference]"}, - "models": {"key": "models", "type": "[KnowledgeBaseModel]"}, - "retrieval_reasoning_effort": {"key": "retrievalReasoningEffort", "type": "KnowledgeRetrievalReasoningEffort"}, - "output_mode": {"key": "outputMode", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "description": {"key": "description", "type": "str"}, - "retrieval_instructions": {"key": "retrievalInstructions", "type": "str"}, - "answer_instructions": {"key": "answerInstructions", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - knowledge_sources: list["_models.KnowledgeSourceReference"], - models: Optional[list["_models.KnowledgeBaseModel"]] = None, - retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, - output_mode: Optional[Union[str, "_models.KnowledgeRetrievalOutputMode"]] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - description: Optional[str] = None, - retrieval_instructions: Optional[str] = None, - answer_instructions: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge knowledge base. Required. - :paramtype name: str - :keyword knowledge_sources: Required. - :paramtype knowledge_sources: - list[~azure.search.documents.indexes.models.KnowledgeSourceReference] - :keyword models: Contains configuration options on how to connect to AI models. - :paramtype models: list[~azure.search.documents.indexes.models.KnowledgeBaseModel] - :keyword retrieval_reasoning_effort: - :paramtype retrieval_reasoning_effort: - ~azure.search.documents.indexes.models.KnowledgeRetrievalReasoningEffort - :keyword output_mode: The output configuration for this retrieval. Known values are: - "extractiveData" and "answerSynthesis". - :paramtype output_mode: str or - ~azure.search.documents.indexes.models.KnowledgeRetrievalOutputMode - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword description: The description of the knowledge base. - :paramtype description: str - :keyword retrieval_instructions: Instructions considered by the knowledge knowledge base when - developing query plan. - :paramtype retrieval_instructions: str - :keyword answer_instructions: Instructions considered by the knowledge knowledge base when - generating answers. - :paramtype answer_instructions: str - """ - super().__init__(**kwargs) - self.name = name - self.knowledge_sources = knowledge_sources - self.models = models - self.retrieval_reasoning_effort = retrieval_reasoning_effort - self.output_mode = output_mode - self.e_tag = e_tag - self.encryption_key = encryption_key - self.description = description - self.retrieval_instructions = retrieval_instructions - self.answer_instructions = answer_instructions - - -class KnowledgeBaseModel(_serialization.Model): - """Specifies the connection parameters for the model to use for query planning. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeBaseAzureOpenAIModel - - All required parameters must be populated in order to send to server. - - :ivar kind: The type of AI model. Required. "azureOpenAI" - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeBaseModelKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = {"kind": {"azureOpenAI": "KnowledgeBaseAzureOpenAIModel"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class KnowledgeBaseAzureOpenAIModel(KnowledgeBaseModel): - """Specifies the Azure OpenAI resource used to do query planning. - - All required parameters must be populated in order to send to server. - - :ivar kind: The type of AI model. Required. "azureOpenAI" - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeBaseModelKind - :ivar azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI model - endpoint. Required. - :vartype azure_open_ai_parameters: - ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - - _validation = { - "kind": {"required": True}, - "azure_open_ai_parameters": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "azure_open_ai_parameters": {"key": "azureOpenAIParameters", "type": "AzureOpenAIVectorizerParameters"}, - } - - def __init__(self, *, azure_open_ai_parameters: "_models.AzureOpenAIVectorizerParameters", **kwargs: Any) -> None: - """ - :keyword azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI model - endpoint. Required. - :paramtype azure_open_ai_parameters: - ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - super().__init__(**kwargs) - self.kind: str = "azureOpenAI" - self.azure_open_ai_parameters = azure_open_ai_parameters - - -class KnowledgeRetrievalReasoningEffort(_serialization.Model): - """KnowledgeRetrievalReasoningEffort. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeRetrievalLowReasoningEffort, KnowledgeRetrievalMediumReasoningEffort, - KnowledgeRetrievalMinimalReasoningEffort - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.indexes.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": { - "low": "KnowledgeRetrievalLowReasoningEffort", - "medium": "KnowledgeRetrievalMediumReasoningEffort", - "minimal": "KnowledgeRetrievalMinimalReasoningEffort", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class KnowledgeRetrievalLowReasoningEffort(KnowledgeRetrievalReasoningEffort): - """Run knowledge retrieval with low reasoning effort. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.indexes.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: str = "low" - - -class KnowledgeRetrievalMediumReasoningEffort(KnowledgeRetrievalReasoningEffort): - """Run knowledge retrieval with medium reasoning effort. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.indexes.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: str = "medium" - - -class KnowledgeRetrievalMinimalReasoningEffort(KnowledgeRetrievalReasoningEffort): - """Run knowledge retrieval with minimal reasoning effort. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.indexes.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: str = "minimal" - - -class KnowledgeSourceVectorizer(_serialization.Model): - """Specifies the vectorization method to be used for knowledge source embedding model, with - optional name. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeSourceAzureOpenAIVectorizer - - All required parameters must be populated in order to send to server. - - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = {"kind": {"azureOpenAI": "KnowledgeSourceAzureOpenAIVectorizer"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class KnowledgeSourceAzureOpenAIVectorizer(KnowledgeSourceVectorizer): - """Specifies the Azure OpenAI resource used to vectorize a query string. - - All required parameters must be populated in order to send to server. - - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI embedding - vectorization. - :vartype azure_open_ai_parameters: - ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "azure_open_ai_parameters": {"key": "azureOpenAIParameters", "type": "AzureOpenAIVectorizerParameters"}, - } - - def __init__( - self, *, azure_open_ai_parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = None, **kwargs: Any - ) -> None: - """ - :keyword azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI embedding - vectorization. - :paramtype azure_open_ai_parameters: - ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - super().__init__(**kwargs) - self.kind: str = "azureOpenAI" - self.azure_open_ai_parameters = azure_open_ai_parameters - - -class KnowledgeSourceIngestionParameters(_serialization.Model): - """Consolidates all general ingestion settings for knowledge sources. - - :ivar identity: An explicit identity to use for this knowledge source. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar embedding_model: Optional vectorizer configuration for vectorizing content. - :vartype embedding_model: ~azure.search.documents.indexes.models.KnowledgeSourceVectorizer - :ivar chat_completion_model: Optional chat completion model for image verbalization or context - extraction. - :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeBaseModel - :ivar disable_image_verbalization: Indicates whether image verbalization should be disabled. - Default is false. - :vartype disable_image_verbalization: bool - :ivar ingestion_schedule: Optional schedule for data ingestion. - :vartype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :ivar ingestion_permission_options: Optional list of permission types to ingest together with - document content. If specified, it will set the indexer permission options for the data source. - :vartype ingestion_permission_options: list[str or - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption] - :ivar content_extraction_mode: Optional content extraction mode. Default is 'minimal'. Known - values are: "minimal" and "standard". - :vartype content_extraction_mode: str or - ~azure.search.documents.indexes.models.KnowledgeSourceContentExtractionMode - :ivar ai_services: Optional AI Services configuration for content processing. - :vartype ai_services: ~azure.search.documents.indexes.models.AIServices - """ - - _attribute_map = { - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "embedding_model": {"key": "embeddingModel", "type": "KnowledgeSourceVectorizer"}, - "chat_completion_model": {"key": "chatCompletionModel", "type": "KnowledgeBaseModel"}, - "disable_image_verbalization": {"key": "disableImageVerbalization", "type": "bool"}, - "ingestion_schedule": {"key": "ingestionSchedule", "type": "IndexingSchedule"}, - "ingestion_permission_options": {"key": "ingestionPermissionOptions", "type": "[str]"}, - "content_extraction_mode": {"key": "contentExtractionMode", "type": "str"}, - "ai_services": {"key": "aiServices", "type": "AIServices"}, - } - - def __init__( - self, - *, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - embedding_model: Optional["_models.KnowledgeSourceVectorizer"] = None, - chat_completion_model: Optional["_models.KnowledgeBaseModel"] = None, - disable_image_verbalization: bool = False, - ingestion_schedule: Optional["_models.IndexingSchedule"] = None, - ingestion_permission_options: Optional[ - list[Union[str, "_models.KnowledgeSourceIngestionPermissionOption"]] - ] = None, - content_extraction_mode: Union[str, "_models.KnowledgeSourceContentExtractionMode"] = "minimal", - ai_services: Optional["_models.AIServices"] = None, - **kwargs: Any - ) -> None: - """ - :keyword identity: An explicit identity to use for this knowledge source. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword embedding_model: Optional vectorizer configuration for vectorizing content. - :paramtype embedding_model: ~azure.search.documents.indexes.models.KnowledgeSourceVectorizer - :keyword chat_completion_model: Optional chat completion model for image verbalization or - context extraction. - :paramtype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeBaseModel - :keyword disable_image_verbalization: Indicates whether image verbalization should be disabled. - Default is false. - :paramtype disable_image_verbalization: bool - :keyword ingestion_schedule: Optional schedule for data ingestion. - :paramtype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :keyword ingestion_permission_options: Optional list of permission types to ingest together - with document content. If specified, it will set the indexer permission options for the data - source. - :paramtype ingestion_permission_options: list[str or - ~azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption] - :keyword content_extraction_mode: Optional content extraction mode. Default is 'minimal'. Known - values are: "minimal" and "standard". - :paramtype content_extraction_mode: str or - ~azure.search.documents.indexes.models.KnowledgeSourceContentExtractionMode - :keyword ai_services: Optional AI Services configuration for content processing. - :paramtype ai_services: ~azure.search.documents.indexes.models.AIServices - """ - super().__init__(**kwargs) - self.identity = identity - self.embedding_model = embedding_model - self.chat_completion_model = chat_completion_model - self.disable_image_verbalization = disable_image_verbalization - self.ingestion_schedule = ingestion_schedule - self.ingestion_permission_options = ingestion_permission_options - self.content_extraction_mode = content_extraction_mode - self.ai_services = ai_services - - -class KnowledgeSourceReference(_serialization.Model): - """KnowledgeSourceReference. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - - -class KnowledgeSourceStatistics(_serialization.Model): - """Statistical information about knowledge source synchronization history. - - All required parameters must be populated in order to send to server. - - :ivar total_synchronization: The total number of synchronizations completed. Required. - :vartype total_synchronization: int - :ivar average_synchronization_duration: The average duration of synchronizations in HH:MM:SS - format. Required. - :vartype average_synchronization_duration: str - :ivar average_items_processed_per_synchronization: The average number of items processed per - synchronization. Required. - :vartype average_items_processed_per_synchronization: int - """ - - _validation = { - "total_synchronization": {"required": True}, - "average_synchronization_duration": {"required": True}, - "average_items_processed_per_synchronization": {"required": True}, - } - - _attribute_map = { - "total_synchronization": {"key": "totalSynchronization", "type": "int"}, - "average_synchronization_duration": {"key": "averageSynchronizationDuration", "type": "str"}, - "average_items_processed_per_synchronization": { - "key": "averageItemsProcessedPerSynchronization", - "type": "int", - }, - } - - def __init__( - self, - *, - total_synchronization: int, - average_synchronization_duration: str, - average_items_processed_per_synchronization: int, - **kwargs: Any - ) -> None: - """ - :keyword total_synchronization: The total number of synchronizations completed. Required. - :paramtype total_synchronization: int - :keyword average_synchronization_duration: The average duration of synchronizations in HH:MM:SS - format. Required. - :paramtype average_synchronization_duration: str - :keyword average_items_processed_per_synchronization: The average number of items processed per - synchronization. Required. - :paramtype average_items_processed_per_synchronization: int - """ - super().__init__(**kwargs) - self.total_synchronization = total_synchronization - self.average_synchronization_duration = average_synchronization_duration - self.average_items_processed_per_synchronization = average_items_processed_per_synchronization - - -class KnowledgeSourceStatus(_serialization.Model): - """Represents the status and synchronization history of a knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar synchronization_status: The current synchronization status of the knowledge source. - Required. Known values are: "creating", "active", and "deleting". - :vartype synchronization_status: str or - ~azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus - :ivar synchronization_interval: The synchronization interval (e.g., '1d' for daily). Null if no - schedule is configured. - :vartype synchronization_interval: str - :ivar current_synchronization_state: Current synchronization state that spans multiple indexer - runs. - :vartype current_synchronization_state: - ~azure.search.documents.indexes.models.SynchronizationState - :ivar last_synchronization_state: Details of the last completed synchronization. Null on first - sync. - :vartype last_synchronization_state: - ~azure.search.documents.indexes.models.CompletedSynchronizationState - :ivar statistics: Statistical information about the knowledge source synchronization history. - Null on first sync. - :vartype statistics: ~azure.search.documents.indexes.models.KnowledgeSourceStatistics - """ - - _validation = { - "synchronization_status": {"required": True}, - } - - _attribute_map = { - "synchronization_status": {"key": "synchronizationStatus", "type": "str"}, - "synchronization_interval": {"key": "synchronizationInterval", "type": "str"}, - "current_synchronization_state": {"key": "currentSynchronizationState", "type": "SynchronizationState"}, - "last_synchronization_state": {"key": "lastSynchronizationState", "type": "CompletedSynchronizationState"}, - "statistics": {"key": "statistics", "type": "KnowledgeSourceStatistics"}, - } - - def __init__( - self, - *, - synchronization_status: Union[str, "_models.KnowledgeSourceSynchronizationStatus"], - synchronization_interval: Optional[str] = None, - current_synchronization_state: Optional["_models.SynchronizationState"] = None, - last_synchronization_state: Optional["_models.CompletedSynchronizationState"] = None, - statistics: Optional["_models.KnowledgeSourceStatistics"] = None, - **kwargs: Any - ) -> None: - """ - :keyword synchronization_status: The current synchronization status of the knowledge source. - Required. Known values are: "creating", "active", and "deleting". - :paramtype synchronization_status: str or - ~azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus - :keyword synchronization_interval: The synchronization interval (e.g., '1d' for daily). Null if - no schedule is configured. - :paramtype synchronization_interval: str - :keyword current_synchronization_state: Current synchronization state that spans multiple - indexer runs. - :paramtype current_synchronization_state: - ~azure.search.documents.indexes.models.SynchronizationState - :keyword last_synchronization_state: Details of the last completed synchronization. Null on - first sync. - :paramtype last_synchronization_state: - ~azure.search.documents.indexes.models.CompletedSynchronizationState - :keyword statistics: Statistical information about the knowledge source synchronization - history. Null on first sync. - :paramtype statistics: ~azure.search.documents.indexes.models.KnowledgeSourceStatistics - """ - super().__init__(**kwargs) - self.synchronization_status = synchronization_status - self.synchronization_interval = synchronization_interval - self.current_synchronization_state = current_synchronization_state - self.last_synchronization_state = last_synchronization_state - self.statistics = statistics - - -class LanguageDetectionSkill(SearchIndexerSkill): - """A skill that detects the language of input text and reports a single language code for every - document submitted on the request. The language code is paired with a score indicating the - confidence of the analysis. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_country_hint: A country code to use as a hint to the language detection model if - it cannot disambiguate the language. - :vartype default_country_hint: str - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_country_hint": {"key": "defaultCountryHint", "type": "str"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_country_hint: Optional[str] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_country_hint: A country code to use as a hint to the language detection model - if it cannot disambiguate the language. - :paramtype default_country_hint: str - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.LanguageDetectionSkill" - self.default_country_hint = default_country_hint - self.model_version = model_version - - -class LengthTokenFilter(TokenFilter): - """Removes words that are too long or too short. This token filter is implemented using Apache - Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_length: The minimum length in characters. Default is 0. Maximum is 300. Must be less - than the value of max. - :vartype min_length: int - :ivar max_length: The maximum length in characters. Default and maximum is 300. - :vartype max_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_length": {"maximum": 300}, - "max_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_length": {"key": "min", "type": "int"}, - "max_length": {"key": "max", "type": "int"}, - } - - def __init__(self, *, name: str, min_length: int = 0, max_length: int = 300, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_length: The minimum length in characters. Default is 0. Maximum is 300. Must be - less than the value of max. - :paramtype min_length: int - :keyword max_length: The maximum length in characters. Default and maximum is 300. - :paramtype max_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.LengthTokenFilter" - self.min_length = min_length - self.max_length = max_length - - -class LimitTokenFilter(TokenFilter): - """Limits the number of tokens while indexing. This token filter is implemented using Apache - Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_count: The maximum number of tokens to produce. Default is 1. - :vartype max_token_count: int - :ivar consume_all_tokens: A value indicating whether all tokens from the input must be consumed - even if maxTokenCount is reached. Default is false. - :vartype consume_all_tokens: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_count": {"key": "maxTokenCount", "type": "int"}, - "consume_all_tokens": {"key": "consumeAllTokens", "type": "bool"}, - } - - def __init__(self, *, name: str, max_token_count: int = 1, consume_all_tokens: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword max_token_count: The maximum number of tokens to produce. Default is 1. - :paramtype max_token_count: int - :keyword consume_all_tokens: A value indicating whether all tokens from the input must be - consumed even if maxTokenCount is reached. Default is false. - :paramtype consume_all_tokens: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.LimitTokenFilter" - self.max_token_count = max_token_count - self.consume_all_tokens = consume_all_tokens - - -class ListAliasesResult(_serialization.Model): - """Response from a List Aliases request. If successful, it includes the associated index mappings - for all aliases. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar aliases: The aliases in the Search service. Required. - :vartype aliases: list[~azure.search.documents.indexes.models.SearchAlias] - """ - - _validation = { - "aliases": {"required": True, "readonly": True}, - } - - _attribute_map = { - "aliases": {"key": "value", "type": "[SearchAlias]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.aliases: Optional[list["_models.SearchAlias"]] = None - - -class ListDataSourcesResult(_serialization.Model): - """Response from a List Datasources request. If successful, it includes the full definitions of - all datasources. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar data_sources: The datasources in the Search service. Required. - :vartype data_sources: list[~azure.search.documents.indexes.models.SearchIndexerDataSource] - """ - - _validation = { - "data_sources": {"required": True, "readonly": True}, - } - - _attribute_map = { - "data_sources": {"key": "value", "type": "[SearchIndexerDataSource]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.data_sources: Optional[list["_models.SearchIndexerDataSource"]] = None - - -class ListIndexersResult(_serialization.Model): - """Response from a List Indexers request. If successful, it includes the full definitions of all - indexers. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar indexers: The indexers in the Search service. Required. - :vartype indexers: list[~azure.search.documents.indexes.models.SearchIndexer] - """ - - _validation = { - "indexers": {"required": True, "readonly": True}, - } - - _attribute_map = { - "indexers": {"key": "value", "type": "[SearchIndexer]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.indexers: Optional[list["_models.SearchIndexer"]] = None - - -class ListIndexesResult(_serialization.Model): - """Response from a List Indexes request. If successful, it includes the full definitions of all - indexes. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar indexes: The indexes in the Search service. Required. - :vartype indexes: list[~azure.search.documents.indexes.models.SearchIndex] - """ - - _validation = { - "indexes": {"required": True, "readonly": True}, - } - - _attribute_map = { - "indexes": {"key": "value", "type": "[SearchIndex]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.indexes: Optional[list["_models.SearchIndex"]] = None - - -class ListIndexStatsSummary(_serialization.Model): - """Response from a request to retrieve stats summary of all indexes. If successful, it includes - the stats of each index in the service. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar indexes_statistics: The Statistics summary of all indexes in the Search service. - Required. - :vartype indexes_statistics: - list[~azure.search.documents.indexes.models.IndexStatisticsSummary] - """ - - _validation = { - "indexes_statistics": {"required": True, "readonly": True}, - } - - _attribute_map = { - "indexes_statistics": {"key": "value", "type": "[IndexStatisticsSummary]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.indexes_statistics: Optional[list["_models.IndexStatisticsSummary"]] = None - - -class ListKnowledgeBasesResult(_serialization.Model): - """ListKnowledgeBasesResult. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_bases: Required. - :vartype knowledge_bases: list[~azure.search.documents.indexes.models.KnowledgeBase] - """ - - _validation = { - "knowledge_bases": {"required": True}, - } - - _attribute_map = { - "knowledge_bases": {"key": "value", "type": "[KnowledgeBase]"}, - } - - def __init__(self, *, knowledge_bases: list["_models.KnowledgeBase"], **kwargs: Any) -> None: - """ - :keyword knowledge_bases: Required. - :paramtype knowledge_bases: list[~azure.search.documents.indexes.models.KnowledgeBase] - """ - super().__init__(**kwargs) - self.knowledge_bases = knowledge_bases - - -class ListKnowledgeSourcesResult(_serialization.Model): - """ListKnowledgeSourcesResult. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_sources: Required. - :vartype knowledge_sources: list[~azure.search.documents.indexes.models.KnowledgeSource] - """ - - _validation = { - "knowledge_sources": {"required": True}, - } - - _attribute_map = { - "knowledge_sources": {"key": "value", "type": "[KnowledgeSource]"}, - } - - def __init__(self, *, knowledge_sources: list["_models.KnowledgeSource"], **kwargs: Any) -> None: - """ - :keyword knowledge_sources: Required. - :paramtype knowledge_sources: list[~azure.search.documents.indexes.models.KnowledgeSource] - """ - super().__init__(**kwargs) - self.knowledge_sources = knowledge_sources - - -class ListSkillsetsResult(_serialization.Model): - """Response from a list skillset request. If successful, it includes the full definitions of all - skillsets. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar skillsets: The skillsets defined in the Search service. Required. - :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - """ - - _validation = { - "skillsets": {"required": True, "readonly": True}, - } - - _attribute_map = { - "skillsets": {"key": "value", "type": "[SearchIndexerSkillset]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.skillsets: Optional[list["_models.SearchIndexerSkillset"]] = None - - -class ListSynonymMapsResult(_serialization.Model): - """Response from a List SynonymMaps request. If successful, it includes the full definitions of - all synonym maps. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar synonym_maps: The synonym maps in the Search service. Required. - :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] - """ - - _validation = { - "synonym_maps": {"required": True, "readonly": True}, - } - - _attribute_map = { - "synonym_maps": {"key": "value", "type": "[SynonymMap]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.synonym_maps: Optional[list["_models.SynonymMap"]] = None - - -class LuceneStandardAnalyzer(LexicalAnalyzer): - """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop - filter. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__( - self, *, name: str, max_token_length: int = 255, stopwords: Optional[list[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - :keyword stopwords: A list of stopwords. - :paramtype stopwords: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StandardAnalyzer" - self.max_token_length = max_token_length - self.stopwords = stopwords - - -class LuceneStandardTokenizer(LexicalTokenizer): - """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StandardTokenizer" - self.max_token_length = max_token_length - - -class LuceneStandardTokenizerV2(LexicalTokenizer): - """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StandardTokenizerV2" - self.max_token_length = max_token_length - - -class MagnitudeScoringFunction(ScoringFunction): - """Defines a function that boosts scores based on the magnitude of a numeric field. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the magnitude scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.MagnitudeScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "magnitude", "type": "MagnitudeScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.MagnitudeScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the magnitude scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.MagnitudeScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "magnitude" - self.parameters = parameters - - -class MagnitudeScoringParameters(_serialization.Model): - """Provides parameter values to a magnitude scoring function. - - All required parameters must be populated in order to send to server. - - :ivar boosting_range_start: The field value at which boosting starts. Required. - :vartype boosting_range_start: float - :ivar boosting_range_end: The field value at which boosting ends. Required. - :vartype boosting_range_end: float - :ivar should_boost_beyond_range_by_constant: A value indicating whether to apply a constant - boost for field values beyond the range end value; default is false. - :vartype should_boost_beyond_range_by_constant: bool - """ - - _validation = { - "boosting_range_start": {"required": True}, - "boosting_range_end": {"required": True}, - } - - _attribute_map = { - "boosting_range_start": {"key": "boostingRangeStart", "type": "float"}, - "boosting_range_end": {"key": "boostingRangeEnd", "type": "float"}, - "should_boost_beyond_range_by_constant": {"key": "constantBoostBeyondRange", "type": "bool"}, - } - - def __init__( - self, - *, - boosting_range_start: float, - boosting_range_end: float, - should_boost_beyond_range_by_constant: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword boosting_range_start: The field value at which boosting starts. Required. - :paramtype boosting_range_start: float - :keyword boosting_range_end: The field value at which boosting ends. Required. - :paramtype boosting_range_end: float - :keyword should_boost_beyond_range_by_constant: A value indicating whether to apply a constant - boost for field values beyond the range end value; default is false. - :paramtype should_boost_beyond_range_by_constant: bool - """ - super().__init__(**kwargs) - self.boosting_range_start = boosting_range_start - self.boosting_range_end = boosting_range_end - self.should_boost_beyond_range_by_constant = should_boost_beyond_range_by_constant - - -class MappingCharFilter(CharFilter): - """A character filter that applies mappings defined with the mappings option. Matching is greedy - (longest pattern matching at a given point wins). Replacement is allowed to be the empty - string. This character filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of char filter. Required. - :vartype odata_type: str - :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar mappings: A list of mappings of the following format: "a=>b" (all occurrences of the - character "a" will be replaced with character "b"). Required. - :vartype mappings: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "mappings": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "mappings": {"key": "mappings", "type": "[str]"}, - } - - def __init__(self, *, name: str, mappings: list[str], **kwargs: Any) -> None: - """ - :keyword name: The name of the char filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword mappings: A list of mappings of the following format: "a=>b" (all occurrences of the - character "a" will be replaced with character "b"). Required. - :paramtype mappings: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.MappingCharFilter" - self.mappings = mappings - - -class MergeSkill(SearchIndexerSkill): - """A skill for merging two or more strings into a single unified string, with an optional - user-defined delimiter separating each component part. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar insert_pre_tag: The tag indicates the start of the merged text. By default, the tag is an - empty space. - :vartype insert_pre_tag: str - :ivar insert_post_tag: The tag indicates the end of the merged text. By default, the tag is an - empty space. - :vartype insert_post_tag: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "insert_pre_tag": {"key": "insertPreTag", "type": "str"}, - "insert_post_tag": {"key": "insertPostTag", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - insert_pre_tag: str = " ", - insert_post_tag: str = " ", - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword insert_pre_tag: The tag indicates the start of the merged text. By default, the tag is - an empty space. - :paramtype insert_pre_tag: str - :keyword insert_post_tag: The tag indicates the end of the merged text. By default, the tag is - an empty space. - :paramtype insert_post_tag: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.MergeSkill" - self.insert_pre_tag = insert_pre_tag - self.insert_post_tag = insert_post_tag - - -class MicrosoftLanguageStemmingTokenizer(LexicalTokenizer): - """Divides text using language-specific rules and reduces words to their base forms. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :vartype max_token_length: int - :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as - the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :vartype is_search_tokenizer: bool - :ivar language: The language to use. The default is English. Known values are: "arabic", - "bangla", "bulgarian", "catalan", "croatian", "czech", "danish", "dutch", "english", - "estonian", "finnish", "french", "german", "greek", "gujarati", "hebrew", "hindi", "hungarian", - "icelandic", "indonesian", "italian", "kannada", "latvian", "lithuanian", "malay", "malayalam", - "marathi", "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", - "romanian", "russian", "serbianCyrillic", "serbianLatin", "slovak", "slovenian", "spanish", - "swedish", "tamil", "telugu", "turkish", "ukrainian", and "urdu". - :vartype language: str or - ~azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "is_search_tokenizer": {"key": "isSearchTokenizer", "type": "bool"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - max_token_length: int = 255, - is_search_tokenizer: bool = False, - language: Optional[Union[str, "_models.MicrosoftStemmingTokenizerLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :paramtype max_token_length: int - :keyword is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used - as the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :paramtype is_search_tokenizer: bool - :keyword language: The language to use. The default is English. Known values are: "arabic", - "bangla", "bulgarian", "catalan", "croatian", "czech", "danish", "dutch", "english", - "estonian", "finnish", "french", "german", "greek", "gujarati", "hebrew", "hindi", "hungarian", - "icelandic", "indonesian", "italian", "kannada", "latvian", "lithuanian", "malay", "malayalam", - "marathi", "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", - "romanian", "russian", "serbianCyrillic", "serbianLatin", "slovak", "slovenian", "spanish", - "swedish", "tamil", "telugu", "turkish", "ukrainian", and "urdu". - :paramtype language: str or - ~azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer" - self.max_token_length = max_token_length - self.is_search_tokenizer = is_search_tokenizer - self.language = language - - -class MicrosoftLanguageTokenizer(LexicalTokenizer): - """Divides text using language-specific rules. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :vartype max_token_length: int - :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as - the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :vartype is_search_tokenizer: bool - :ivar language: The language to use. The default is English. Known values are: "bangla", - "bulgarian", "catalan", "chineseSimplified", "chineseTraditional", "croatian", "czech", - "danish", "dutch", "english", "french", "german", "greek", "gujarati", "hindi", "icelandic", - "indonesian", "italian", "japanese", "kannada", "korean", "malay", "malayalam", "marathi", - "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", "romanian", - "russian", "serbianCyrillic", "serbianLatin", "slovenian", "spanish", "swedish", "tamil", - "telugu", "thai", "ukrainian", "urdu", and "vietnamese". - :vartype language: str or ~azure.search.documents.indexes.models.MicrosoftTokenizerLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "is_search_tokenizer": {"key": "isSearchTokenizer", "type": "bool"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - max_token_length: int = 255, - is_search_tokenizer: bool = False, - language: Optional[Union[str, "_models.MicrosoftTokenizerLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :paramtype max_token_length: int - :keyword is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used - as the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :paramtype is_search_tokenizer: bool - :keyword language: The language to use. The default is English. Known values are: "bangla", - "bulgarian", "catalan", "chineseSimplified", "chineseTraditional", "croatian", "czech", - "danish", "dutch", "english", "french", "german", "greek", "gujarati", "hindi", "icelandic", - "indonesian", "italian", "japanese", "kannada", "korean", "malay", "malayalam", "marathi", - "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", "romanian", - "russian", "serbianCyrillic", "serbianLatin", "slovenian", "spanish", "swedish", "tamil", - "telugu", "thai", "ukrainian", "urdu", and "vietnamese". - :paramtype language: str or ~azure.search.documents.indexes.models.MicrosoftTokenizerLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer" - self.max_token_length = max_token_length - self.is_search_tokenizer = is_search_tokenizer - self.language = language - - -class NativeBlobSoftDeleteDeletionDetectionPolicy(DataDeletionDetectionPolicy): # pylint: disable=name-too-long - """Defines a data deletion detection policy utilizing Azure Blob Storage's native soft delete - feature for deletion detection. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. - Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" - - -class NGramTokenFilter(TokenFilter): - """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. - :vartype max_gram: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - } - - def __init__(self, *, name: str, min_gram: int = 1, max_gram: int = 2, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. - :paramtype max_gram: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NGramTokenFilter" - self.min_gram = min_gram - self.max_gram = max_gram - - -class NGramTokenFilterV2(TokenFilter): - """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - } - - def __init__(self, *, name: str, min_gram: int = 1, max_gram: int = 2, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NGramTokenFilterV2" - self.min_gram = min_gram - self.max_gram = max_gram - - -class NGramTokenizer(LexicalTokenizer): - """Tokenizes the input into n-grams of the given size(s). This tokenizer is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - :ivar token_chars: Character classes to keep in the tokens. - :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "token_chars": {"key": "tokenChars", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - :keyword token_chars: Character classes to keep in the tokens. - :paramtype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NGramTokenizer" - self.min_gram = min_gram - self.max_gram = max_gram - self.token_chars = token_chars - - -class OcrSkill(SearchIndexerSkill): - """A skill that extracts text from image files. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "af", "sq", "anp", "ar", "ast", "awa", "az", "bfy", "eu", "be", "be-cyrl", - "be-latn", "bho", "bi", "brx", "bs", "bra", "br", "bg", "bns", "bua", "ca", "ceb", "rab", "ch", - "hne", "zh-Hans", "zh-Hant", "kw", "co", "crh", "hr", "cs", "da", "prs", "dhi", "doi", "nl", - "en", "myv", "et", "fo", "fj", "fil", "fi", "fr", "fur", "gag", "gl", "de", "gil", "gon", "el", - "kl", "gvr", "ht", "hlb", "hni", "bgc", "haw", "hi", "mww", "hoc", "hu", "is", "smn", "id", - "ia", "iu", "ga", "it", "ja", "Jns", "jv", "kea", "kac", "xnr", "krc", "kaa-cyrl", "kaa", - "csb", "kk-cyrl", "kk-latn", "klr", "kha", "quc", "ko", "kfq", "kpy", "kos", "kum", "ku-arab", - "ku-latn", "kru", "ky", "lkt", "la", "lt", "dsb", "smj", "lb", "bfz", "ms", "mt", "kmj", "gv", - "mi", "mr", "mn", "cnr-cyrl", "cnr-latn", "nap", "ne", "niu", "nog", "sme", "nb", "no", "oc", - "os", "ps", "fa", "pl", "pt", "pa", "ksh", "ro", "rm", "ru", "sck", "sm", "sa", "sat", "sco", - "gd", "sr", "sr-Cyrl", "sr-Latn", "xsr", "srx", "sms", "sk", "sl", "so", "sma", "es", "sw", - "sv", "tg", "tt", "tet", "thf", "to", "tr", "tk", "tyv", "hsb", "ur", "ug", "uz-arab", - "uz-cyrl", "uz", "vo", "wae", "cy", "fy", "yua", "za", "zu", "unk", and "is". - :vartype default_language_code: str or ~azure.search.documents.indexes.models.OcrSkillLanguage - :ivar should_detect_orientation: A value indicating to turn orientation detection on or not. - Default is false. - :vartype should_detect_orientation: bool - :ivar line_ending: Defines the sequence of characters to use between the lines of text - recognized by the OCR skill. The default value is "space". Known values are: "space", - "carriageReturn", "lineFeed", and "carriageReturnLineFeed". - :vartype line_ending: str or ~azure.search.documents.indexes.models.OcrLineEnding - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "should_detect_orientation": {"key": "detectOrientation", "type": "bool"}, - "line_ending": {"key": "lineEnding", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.OcrSkillLanguage"]] = None, - should_detect_orientation: bool = False, - line_ending: Optional[Union[str, "_models.OcrLineEnding"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "af", "sq", "anp", "ar", "ast", "awa", "az", "bfy", "eu", "be", - "be-cyrl", "be-latn", "bho", "bi", "brx", "bs", "bra", "br", "bg", "bns", "bua", "ca", "ceb", - "rab", "ch", "hne", "zh-Hans", "zh-Hant", "kw", "co", "crh", "hr", "cs", "da", "prs", "dhi", - "doi", "nl", "en", "myv", "et", "fo", "fj", "fil", "fi", "fr", "fur", "gag", "gl", "de", "gil", - "gon", "el", "kl", "gvr", "ht", "hlb", "hni", "bgc", "haw", "hi", "mww", "hoc", "hu", "is", - "smn", "id", "ia", "iu", "ga", "it", "ja", "Jns", "jv", "kea", "kac", "xnr", "krc", "kaa-cyrl", - "kaa", "csb", "kk-cyrl", "kk-latn", "klr", "kha", "quc", "ko", "kfq", "kpy", "kos", "kum", - "ku-arab", "ku-latn", "kru", "ky", "lkt", "la", "lt", "dsb", "smj", "lb", "bfz", "ms", "mt", - "kmj", "gv", "mi", "mr", "mn", "cnr-cyrl", "cnr-latn", "nap", "ne", "niu", "nog", "sme", "nb", - "no", "oc", "os", "ps", "fa", "pl", "pt", "pa", "ksh", "ro", "rm", "ru", "sck", "sm", "sa", - "sat", "sco", "gd", "sr", "sr-Cyrl", "sr-Latn", "xsr", "srx", "sms", "sk", "sl", "so", "sma", - "es", "sw", "sv", "tg", "tt", "tet", "thf", "to", "tr", "tk", "tyv", "hsb", "ur", "ug", - "uz-arab", "uz-cyrl", "uz", "vo", "wae", "cy", "fy", "yua", "za", "zu", "unk", and "is". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.OcrSkillLanguage - :keyword should_detect_orientation: A value indicating to turn orientation detection on or not. - Default is false. - :paramtype should_detect_orientation: bool - :keyword line_ending: Defines the sequence of characters to use between the lines of text - recognized by the OCR skill. The default value is "space". Known values are: "space", - "carriageReturn", "lineFeed", and "carriageReturnLineFeed". - :paramtype line_ending: str or ~azure.search.documents.indexes.models.OcrLineEnding - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Vision.OcrSkill" - self.default_language_code = default_language_code - self.should_detect_orientation = should_detect_orientation - self.line_ending = line_ending - - -class OutputFieldMappingEntry(_serialization.Model): - """Output field mapping for a skill. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the output defined by the skill. Required. - :vartype name: str - :ivar target_name: The target name of the output. It is optional and default to name. - :vartype target_name: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "target_name": {"key": "targetName", "type": "str"}, - } - - def __init__(self, *, name: str, target_name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the output defined by the skill. Required. - :paramtype name: str - :keyword target_name: The target name of the output. It is optional and default to name. - :paramtype target_name: str - """ - super().__init__(**kwargs) - self.name = name - self.target_name = target_name - - -class PathHierarchyTokenizerV2(LexicalTokenizer): - """Tokenizer for path-like hierarchies. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar delimiter: The delimiter character to use. Default is "/". - :vartype delimiter: str - :ivar replacement: A value that, if set, replaces the delimiter character. Default is "/". - :vartype replacement: str - :ivar max_token_length: The maximum token length. Default and maximum is 300. - :vartype max_token_length: int - :ivar reverse_token_order: A value indicating whether to generate tokens in reverse order. - Default is false. - :vartype reverse_token_order: bool - :ivar number_of_tokens_to_skip: The number of initial tokens to skip. Default is 0. - :vartype number_of_tokens_to_skip: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "delimiter": {"key": "delimiter", "type": "str"}, - "replacement": {"key": "replacement", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "reverse_token_order": {"key": "reverse", "type": "bool"}, - "number_of_tokens_to_skip": {"key": "skip", "type": "int"}, - } - - def __init__( - self, - *, - name: str, - delimiter: str = "/", - replacement: str = "/", - max_token_length: int = 300, - reverse_token_order: bool = False, - number_of_tokens_to_skip: int = 0, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword delimiter: The delimiter character to use. Default is "/". - :paramtype delimiter: str - :keyword replacement: A value that, if set, replaces the delimiter character. Default is "/". - :paramtype replacement: str - :keyword max_token_length: The maximum token length. Default and maximum is 300. - :paramtype max_token_length: int - :keyword reverse_token_order: A value indicating whether to generate tokens in reverse order. - Default is false. - :paramtype reverse_token_order: bool - :keyword number_of_tokens_to_skip: The number of initial tokens to skip. Default is 0. - :paramtype number_of_tokens_to_skip: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2" - self.delimiter = delimiter - self.replacement = replacement - self.max_token_length = max_token_length - self.reverse_token_order = reverse_token_order - self.number_of_tokens_to_skip = number_of_tokens_to_skip - - -class PatternAnalyzer(LexicalAnalyzer): - """Flexibly separates text into terms via a regular expression pattern. This analyzer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar lower_case_terms: A value indicating whether terms should be lower-cased. Default is - true. - :vartype lower_case_terms: bool - :ivar pattern: A regular expression pattern to match token separators. Default is an expression - that matches one or more non-word characters. - :vartype pattern: str - :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :vartype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "lower_case_terms": {"key": "lowercase", "type": "bool"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "str"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - lower_case_terms: bool = True, - pattern: str = r"\W+", - flags: Optional[Union[str, "_models.RegexFlags"]] = None, - stopwords: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword lower_case_terms: A value indicating whether terms should be lower-cased. Default is - true. - :paramtype lower_case_terms: bool - :keyword pattern: A regular expression pattern to match token separators. Default is an - expression that matches one or more non-word characters. - :paramtype pattern: str - :keyword flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :paramtype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :keyword stopwords: A list of stopwords. - :paramtype stopwords: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternAnalyzer" - self.lower_case_terms = lower_case_terms - self.pattern = pattern - self.flags = flags - self.stopwords = stopwords - - -class PatternCaptureTokenFilter(TokenFilter): - """Uses Java regexes to emit multiple tokens - one for each capture group in one or more patterns. - This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar patterns: A list of patterns to match against each token. Required. - :vartype patterns: list[str] - :ivar preserve_original: A value indicating whether to return the original token even if one of - the patterns matches. Default is true. - :vartype preserve_original: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "patterns": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "patterns": {"key": "patterns", "type": "[str]"}, - "preserve_original": {"key": "preserveOriginal", "type": "bool"}, - } - - def __init__(self, *, name: str, patterns: list[str], preserve_original: bool = True, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword patterns: A list of patterns to match against each token. Required. - :paramtype patterns: list[str] - :keyword preserve_original: A value indicating whether to return the original token even if one - of the patterns matches. Default is true. - :paramtype preserve_original: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternCaptureTokenFilter" - self.patterns = patterns - self.preserve_original = preserve_original - - -class PatternReplaceCharFilter(CharFilter): - """A character filter that replaces characters in the input string. It uses a regular expression - to identify character sequences to preserve and a replacement pattern to identify characters to - replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\s+(bb)", and - replacement "$1#$2", the result would be "aa#bb aa#bb". This character filter is implemented - using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of char filter. Required. - :vartype odata_type: str - :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar pattern: A regular expression pattern. Required. - :vartype pattern: str - :ivar replacement: The replacement text. Required. - :vartype replacement: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "pattern": {"required": True}, - "replacement": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "replacement": {"key": "replacement", "type": "str"}, - } - - def __init__(self, *, name: str, pattern: str, replacement: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the char filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword pattern: A regular expression pattern. Required. - :paramtype pattern: str - :keyword replacement: The replacement text. Required. - :paramtype replacement: str - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternReplaceCharFilter" - self.pattern = pattern - self.replacement = replacement - - -class PatternReplaceTokenFilter(TokenFilter): - """A character filter that replaces characters in the input string. It uses a regular expression - to identify character sequences to preserve and a replacement pattern to identify characters to - replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\s+(bb)", and - replacement "$1#$2", the result would be "aa#bb aa#bb". This token filter is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar pattern: A regular expression pattern. Required. - :vartype pattern: str - :ivar replacement: The replacement text. Required. - :vartype replacement: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "pattern": {"required": True}, - "replacement": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "replacement": {"key": "replacement", "type": "str"}, - } - - def __init__(self, *, name: str, pattern: str, replacement: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword pattern: A regular expression pattern. Required. - :paramtype pattern: str - :keyword replacement: The replacement text. Required. - :paramtype replacement: str - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternReplaceTokenFilter" - self.pattern = pattern - self.replacement = replacement - - -class PatternTokenizer(LexicalTokenizer): - """Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar pattern: A regular expression pattern to match token separators. Default is an expression - that matches one or more non-word characters. - :vartype pattern: str - :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :vartype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :ivar group: The zero-based ordinal of the matching group in the regular expression pattern to - extract into tokens. Use -1 if you want to use the entire pattern to split the input into - tokens, irrespective of matching groups. Default is -1. - :vartype group: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "str"}, - "group": {"key": "group", "type": "int"}, - } - - def __init__( - self, - *, - name: str, - pattern: str = r"\W+", - flags: Optional[Union[str, "_models.RegexFlags"]] = None, - group: int = -1, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword pattern: A regular expression pattern to match token separators. Default is an - expression that matches one or more non-word characters. - :paramtype pattern: str - :keyword flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :paramtype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :keyword group: The zero-based ordinal of the matching group in the regular expression pattern - to extract into tokens. Use -1 if you want to use the entire pattern to split the input into - tokens, irrespective of matching groups. Default is -1. - :paramtype group: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternTokenizer" - self.pattern = pattern - self.flags = flags - self.group = group - - -class PhoneticTokenFilter(TokenFilter): - """Create tokens for phonetic matches. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar encoder: The phonetic encoder to use. Default is "metaphone". Known values are: - "metaphone", "doubleMetaphone", "soundex", "refinedSoundex", "caverphone1", "caverphone2", - "cologne", "nysiis", "koelnerPhonetik", "haasePhonetik", and "beiderMorse". - :vartype encoder: str or ~azure.search.documents.indexes.models.PhoneticEncoder - :ivar replace_original_tokens: A value indicating whether encoded tokens should replace - original tokens. If false, encoded tokens are added as synonyms. Default is true. - :vartype replace_original_tokens: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "encoder": {"key": "encoder", "type": "str"}, - "replace_original_tokens": {"key": "replace", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - encoder: Optional[Union[str, "_models.PhoneticEncoder"]] = None, - replace_original_tokens: bool = True, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword encoder: The phonetic encoder to use. Default is "metaphone". Known values are: - "metaphone", "doubleMetaphone", "soundex", "refinedSoundex", "caverphone1", "caverphone2", - "cologne", "nysiis", "koelnerPhonetik", "haasePhonetik", and "beiderMorse". - :paramtype encoder: str or ~azure.search.documents.indexes.models.PhoneticEncoder - :keyword replace_original_tokens: A value indicating whether encoded tokens should replace - original tokens. If false, encoded tokens are added as synonyms. Default is true. - :paramtype replace_original_tokens: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PhoneticTokenFilter" - self.encoder = encoder - self.replace_original_tokens = replace_original_tokens - - -class PIIDetectionSkill(SearchIndexerSkill): - """Using the Text Analytics API, extracts personal information from an input text and gives you - the option of masking it. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar masking_mode: A parameter that provides various ways to mask the personal information - detected in the input text. Default is 'none'. Known values are: "none" and "replace". - :vartype masking_mode: str or - ~azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - :ivar pii_categories: A list of PII entity categories that should be extracted and masked. - :vartype pii_categories: list[str] - :ivar domain: If specified, will set the PII domain to include only a subset of the entity - categories. Possible values include: 'phi', 'none'. Default is 'none'. - :vartype domain: str - :ivar mask: The character used to mask the text if the maskingMode parameter is set to replace. - Default is '*'. - :vartype mask: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - "mask": {"max_length": 1}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "masking_mode": {"key": "maskingMode", "type": "str"}, - "model_version": {"key": "modelVersion", "type": "str"}, - "pii_categories": {"key": "piiCategories", "type": "[str]"}, - "domain": {"key": "domain", "type": "str"}, - "mask": {"key": "mask", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[str] = None, - minimum_precision: Optional[float] = None, - masking_mode: Optional[Union[str, "_models.PIIDetectionSkillMaskingMode"]] = None, - model_version: Optional[str] = None, - pii_categories: Optional[list[str]] = None, - domain: Optional[str] = None, - mask: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - :keyword masking_mode: A parameter that provides various ways to mask the personal information - detected in the input text. Default is 'none'. Known values are: "none" and "replace". - :paramtype masking_mode: str or - ~azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - :keyword pii_categories: A list of PII entity categories that should be extracted and masked. - :paramtype pii_categories: list[str] - :keyword domain: If specified, will set the PII domain to include only a subset of the entity - categories. Possible values include: 'phi', 'none'. Default is 'none'. - :paramtype domain: str - :keyword mask: The character used to mask the text if the maskingMode parameter is set to - replace. Default is '*'. - :paramtype mask: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.PIIDetectionSkill" - self.default_language_code = default_language_code - self.minimum_precision = minimum_precision - self.masking_mode = masking_mode - self.model_version = model_version - self.pii_categories = pii_categories - self.domain = domain - self.mask = mask - - -class RemoteSharePointKnowledgeSource(KnowledgeSource): - """Configuration for remote SharePoint knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar remote_share_point_parameters: The parameters for the knowledge source. - :vartype remote_share_point_parameters: - ~azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "remote_share_point_parameters": { - "key": "remoteSharePointParameters", - "type": "RemoteSharePointKnowledgeSourceParameters", - }, - } - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - remote_share_point_parameters: Optional["_models.RemoteSharePointKnowledgeSourceParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword remote_share_point_parameters: The parameters for the knowledge source. - :paramtype remote_share_point_parameters: - ~azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "remoteSharePoint" - self.remote_share_point_parameters = remote_share_point_parameters - - -class RemoteSharePointKnowledgeSourceParameters(_serialization.Model): # pylint: disable=name-too-long - """Parameters for remote SharePoint knowledge source. - - :ivar filter_expression: Keyword Query Language (KQL) expression with queryable SharePoint - properties and attributes to scope the retrieval before the query runs. See documentation: - https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference. - :vartype filter_expression: str - :ivar resource_metadata: A list of metadata fields to be returned for each item in the - response. Only retrievable metadata properties can be included in this list. By default, no - metadata is returned. Optional. - :vartype resource_metadata: list[str] - :ivar container_type_id: Container ID for SharePoint Embedded connection. When this is null, it - will use SharePoint Online. - :vartype container_type_id: str - """ - - _attribute_map = { - "filter_expression": {"key": "filterExpression", "type": "str"}, - "resource_metadata": {"key": "resourceMetadata", "type": "[str]"}, - "container_type_id": {"key": "containerTypeId", "type": "str"}, - } - - def __init__( - self, - *, - filter_expression: Optional[str] = None, - resource_metadata: Optional[list[str]] = None, - container_type_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword filter_expression: Keyword Query Language (KQL) expression with queryable SharePoint - properties and attributes to scope the retrieval before the query runs. See documentation: - https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference. - :paramtype filter_expression: str - :keyword resource_metadata: A list of metadata fields to be returned for each item in the - response. Only retrievable metadata properties can be included in this list. By default, no - metadata is returned. Optional. - :paramtype resource_metadata: list[str] - :keyword container_type_id: Container ID for SharePoint Embedded connection. When this is null, - it will use SharePoint Online. - :paramtype container_type_id: str - """ - super().__init__(**kwargs) - self.filter_expression = filter_expression - self.resource_metadata = resource_metadata - self.container_type_id = container_type_id - - -class RequestOptions(_serialization.Model): - """Parameter group. - - :ivar x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :vartype x_ms_client_request_id: str - """ - - _attribute_map = { - "x_ms_client_request_id": {"key": "x-ms-client-request-id", "type": "str"}, - } - - def __init__(self, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :paramtype x_ms_client_request_id: str - """ - super().__init__(**kwargs) - self.x_ms_client_request_id = x_ms_client_request_id - - -class RescoringOptions(_serialization.Model): - """Contains the options for rescoring. - - :ivar enable_rescoring: If set to true, after the initial search on the compressed vectors, the - similarity scores are recalculated using the full-precision vectors. This will improve recall - at the expense of latency. - :vartype enable_rescoring: bool - :ivar default_oversampling: Default oversampling factor. Oversampling retrieves a greater set - of potential documents to offset the resolution loss due to quantization. This increases the - set of results that will be rescored on full-precision vectors. Minimum value is 1, meaning no - oversampling (1x). This parameter can only be set when 'enableRescoring' is true. Higher values - improve recall at the expense of latency. - :vartype default_oversampling: float - :ivar rescore_storage_method: Controls the storage method for original vectors. This setting is - immutable. Known values are: "preserveOriginals" and "discardOriginals". - :vartype rescore_storage_method: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod - """ - - _attribute_map = { - "enable_rescoring": {"key": "enableRescoring", "type": "bool"}, - "default_oversampling": {"key": "defaultOversampling", "type": "float"}, - "rescore_storage_method": {"key": "rescoreStorageMethod", "type": "str"}, - } - - def __init__( - self, - *, - enable_rescoring: bool = True, - default_oversampling: Optional[float] = None, - rescore_storage_method: Optional[Union[str, "_models.VectorSearchCompressionRescoreStorageMethod"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword enable_rescoring: If set to true, after the initial search on the compressed vectors, - the similarity scores are recalculated using the full-precision vectors. This will improve - recall at the expense of latency. - :paramtype enable_rescoring: bool - :keyword default_oversampling: Default oversampling factor. Oversampling retrieves a greater - set of potential documents to offset the resolution loss due to quantization. This increases - the set of results that will be rescored on full-precision vectors. Minimum value is 1, meaning - no oversampling (1x). This parameter can only be set when 'enableRescoring' is true. Higher - values improve recall at the expense of latency. - :paramtype default_oversampling: float - :keyword rescore_storage_method: Controls the storage method for original vectors. This setting - is immutable. Known values are: "preserveOriginals" and "discardOriginals". - :paramtype rescore_storage_method: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod - """ - super().__init__(**kwargs) - self.enable_rescoring = enable_rescoring - self.default_oversampling = default_oversampling - self.rescore_storage_method = rescore_storage_method - - -class ResourceCounter(_serialization.Model): - """Represents a resource's usage and quota. - - All required parameters must be populated in order to send to server. - - :ivar usage: The resource usage amount. Required. - :vartype usage: int - :ivar quota: The resource amount quota. - :vartype quota: int - """ - - _validation = { - "usage": {"required": True}, - } - - _attribute_map = { - "usage": {"key": "usage", "type": "int"}, - "quota": {"key": "quota", "type": "int"}, - } - - def __init__(self, *, usage: int, quota: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword usage: The resource usage amount. Required. - :paramtype usage: int - :keyword quota: The resource amount quota. - :paramtype quota: int - """ - super().__init__(**kwargs) - self.usage = usage - self.quota = quota - - -class ScalarQuantizationCompression(VectorSearchCompression): - """Contains configuration options specific to the scalar quantization compression method used - during indexing and querying. - - All required parameters must be populated in order to send to server. - - :ivar compression_name: The name to associate with this particular configuration. Required. - :vartype compression_name: str - :ivar kind: The name of the kind of compression method being configured for use with vector - search. Required. Known values are: "scalarQuantization" and "binaryQuantization". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind - :ivar rescoring_options: Contains the options for rescoring. - :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the - vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :vartype truncation_dimension: int - :ivar parameters: Contains the parameters specific to Scalar Quantization. - :vartype parameters: ~azure.search.documents.indexes.models.ScalarQuantizationParameters - """ - - _validation = { - "compression_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "compression_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "rescoring_options": {"key": "rescoringOptions", "type": "RescoringOptions"}, - "truncation_dimension": {"key": "truncationDimension", "type": "int"}, - "parameters": {"key": "scalarQuantizationParameters", "type": "ScalarQuantizationParameters"}, - } - - def __init__( - self, - *, - compression_name: str, - rescoring_options: Optional["_models.RescoringOptions"] = None, - truncation_dimension: Optional[int] = None, - parameters: Optional["_models.ScalarQuantizationParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword compression_name: The name to associate with this particular configuration. Required. - :paramtype compression_name: str - :keyword rescoring_options: Contains the options for rescoring. - :paramtype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :keyword truncation_dimension: The number of dimensions to truncate the vectors to. Truncating - the vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :paramtype truncation_dimension: int - :keyword parameters: Contains the parameters specific to Scalar Quantization. - :paramtype parameters: ~azure.search.documents.indexes.models.ScalarQuantizationParameters - """ - super().__init__( - compression_name=compression_name, - rescoring_options=rescoring_options, - truncation_dimension=truncation_dimension, - **kwargs - ) - self.kind: str = "scalarQuantization" - self.parameters = parameters - - -class ScalarQuantizationParameters(_serialization.Model): - """Contains the parameters specific to Scalar Quantization. - - :ivar quantized_data_type: The quantized data type of compressed vector values. "int8" - :vartype quantized_data_type: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionTarget - """ - - _attribute_map = { - "quantized_data_type": {"key": "quantizedDataType", "type": "str"}, - } - - def __init__( - self, - *, - quantized_data_type: Optional[Union[str, "_models.VectorSearchCompressionTarget"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword quantized_data_type: The quantized data type of compressed vector values. "int8" - :paramtype quantized_data_type: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionTarget - """ - super().__init__(**kwargs) - self.quantized_data_type = quantized_data_type - - -class ScoringProfile(_serialization.Model): - """Defines parameters for a search index that influence scoring in search queries. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the scoring profile. Required. - :vartype name: str - :ivar text_weights: Parameters that boost scoring based on text matches in certain index - fields. - :vartype text_weights: ~azure.search.documents.indexes.models.TextWeights - :ivar functions: The collection of functions that influence the scoring of documents. - :vartype functions: list[~azure.search.documents.indexes.models.ScoringFunction] - :ivar function_aggregation: A value indicating how the results of individual scoring functions - should be combined. Defaults to "Sum". Ignored if there are no scoring functions. Known values - are: "sum", "average", "minimum", "maximum", "firstMatching", and "product". - :vartype function_aggregation: str or - ~azure.search.documents.indexes.models.ScoringFunctionAggregation - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "text_weights": {"key": "text", "type": "TextWeights"}, - "functions": {"key": "functions", "type": "[ScoringFunction]"}, - "function_aggregation": {"key": "functionAggregation", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - text_weights: Optional["_models.TextWeights"] = None, - functions: Optional[list["_models.ScoringFunction"]] = None, - function_aggregation: Optional[Union[str, "_models.ScoringFunctionAggregation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the scoring profile. Required. - :paramtype name: str - :keyword text_weights: Parameters that boost scoring based on text matches in certain index - fields. - :paramtype text_weights: ~azure.search.documents.indexes.models.TextWeights - :keyword functions: The collection of functions that influence the scoring of documents. - :paramtype functions: list[~azure.search.documents.indexes.models.ScoringFunction] - :keyword function_aggregation: A value indicating how the results of individual scoring - functions should be combined. Defaults to "Sum". Ignored if there are no scoring functions. - Known values are: "sum", "average", "minimum", "maximum", "firstMatching", and "product". - :paramtype function_aggregation: str or - ~azure.search.documents.indexes.models.ScoringFunctionAggregation - """ - super().__init__(**kwargs) - self.name = name - self.text_weights = text_weights - self.functions = functions - self.function_aggregation = function_aggregation - - -class SearchAlias(_serialization.Model): - """Represents an index alias, which describes a mapping from the alias name to an index. The alias - name can be used in place of the index name for supported operations. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the alias. Required. - :vartype name: str - :ivar indexes: The name of the index this alias maps to. Only one index name may be specified. - Required. - :vartype indexes: list[str] - :ivar e_tag: The ETag of the alias. - :vartype e_tag: str - """ - - _validation = { - "name": {"required": True}, - "indexes": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "indexes": {"key": "indexes", "type": "[str]"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - } - - def __init__(self, *, name: str, indexes: list[str], e_tag: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the alias. Required. - :paramtype name: str - :keyword indexes: The name of the index this alias maps to. Only one index name may be - specified. Required. - :paramtype indexes: list[str] - :keyword e_tag: The ETag of the alias. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.name = name - self.indexes = indexes - self.e_tag = e_tag - - -class SearchField(_serialization.Model): - """Represents a field in an index definition, which describes the name, data type, and search - behavior of a field. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the field, which must be unique within the fields collection of the - index or parent field. Required. - :vartype name: str - :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", - "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", - "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". - :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType - :ivar key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type Edm.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is false for simple fields and null for complex fields. - :vartype key: bool - :ivar retrievable: A value indicating whether the field can be returned in a search result. You - can disable this option if you want to use a field (for example, margin) as a filter, sorting, - or scoring mechanism but do not want the field to be visible to the end user. This property - must be true for key fields, and it must be null for complex fields. This property can be - changed on existing fields. Enabling this property does not cause any increase in index storage - requirements. Default is true for simple fields, false for vector fields, and null for complex - fields. - :vartype retrievable: bool - :ivar stored: An immutable value indicating whether the field will be persisted separately on - disk to be returned in a search result. You can disable this option if you don't plan to return - the field contents in a search response to save on storage overhead. This can only be set - during index creation and only for vector fields. This property cannot be changed for existing - fields or set as false for new fields. If this property is set as false, the property - 'retrievable' must also be set to false. This property must be true or unset for key fields, - for new fields, and for non-vector fields, and it must be null for complex fields. Disabling - this property will reduce index storage requirements. The default is true for vector fields. - :vartype stored: bool - :ivar searchable: A value indicating whether the field is full-text searchable. This means it - will undergo analysis such as word-breaking during indexing. If you set a searchable field to a - value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Fields of type Edm.String or - Collection(Edm.String) are searchable by default. This property must be false for simple fields - of other non-string data types, and it must be null for complex fields. Note: searchable fields - consume extra space in your index to accommodate additional tokenized versions of the field - value for full-text searches. If you want to save space in your index and you don't need a - field to be included in searches, set searchable to false. - :vartype searchable: bool - :ivar filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so - comparisons are for exact matches only. For example, if you set such a field f to "sunny day", - $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property - must be null for complex fields. Default is true for simple fields and null for complex fields. - :vartype filterable: bool - :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default, the search engine sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. Complex fields - cannot be sortable and the sortable property must be null for such fields. The default for - sortable is true for single-valued simple fields, false for multi-valued simple fields, and - null for complex fields. - :vartype sortable: bool - :ivar facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or - Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple - fields. - :vartype facetable: bool - :ivar permission_filter: A value indicating whether the field should be used as a permission - filter. Known values are: "userIds", "groupIds", and "rbacScope". - :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :ivar sensitivity_label: A value indicating whether the field should be used for sensitivity - label filtering. This enables document-level filtering based on Microsoft Purview sensitivity - labels. - :vartype sensitivity_label: bool - :ivar analyzer: The name of the analyzer to use for the field. This option can be used only - with searchable fields and it can't be set together with either searchAnalyzer or - indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null - for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar search_analyzer: The name of the analyzer used at search time for the field. This option - can be used only with searchable fields. It must be set together with indexAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. This - analyzer can be updated on an existing field. Must be null for complex fields. Known values - are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", - "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", - "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", - "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", - "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", - "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", - "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", - "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", - "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", - "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", - "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype search_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar index_analyzer: The name of the analyzer used at indexing time for the field. This option - can be used only with searchable fields. It must be set together with searchAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. Once the - analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known - values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", - "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype index_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar normalizer: The name of the normalizer to use for the field. This option can be used only - with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it - cannot be changed for the field. Must be null for complex fields. Known values are: - "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :ivar vector_search_dimensions: The dimensionality of the vector field. - :vartype vector_search_dimensions: int - :ivar vector_search_profile_name: The name of the vector search profile that specifies the - algorithm and vectorizer to use when searching the vector field. - :vartype vector_search_profile_name: str - :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" - :vartype vector_encoding_format: str or - ~azure.search.documents.indexes.models.VectorEncodingFormat - :ivar synonym_maps: A list of the names of synonym maps to associate with this field. This - option can be used only with searchable fields. Currently only one synonym map per field is - supported. Assigning a synonym map to a field ensures that query terms targeting that field are - expanded at query-time using the rules in the synonym map. This attribute can be changed on - existing fields. Must be null or an empty collection for complex fields. - :vartype synonym_maps: list[str] - :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or - Collection(Edm.ComplexType). Must be null or empty for simple fields. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - """ - - _validation = { - "name": {"required": True}, - "type": {"required": True}, - "vector_search_dimensions": {"maximum": 4096, "minimum": 2}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "key": {"key": "key", "type": "bool"}, - "retrievable": {"key": "retrievable", "type": "bool"}, - "stored": {"key": "stored", "type": "bool"}, - "searchable": {"key": "searchable", "type": "bool"}, - "filterable": {"key": "filterable", "type": "bool"}, - "sortable": {"key": "sortable", "type": "bool"}, - "facetable": {"key": "facetable", "type": "bool"}, - "permission_filter": {"key": "permissionFilter", "type": "str"}, - "sensitivity_label": {"key": "sensitivityLabel", "type": "bool"}, - "analyzer": {"key": "analyzer", "type": "str"}, - "search_analyzer": {"key": "searchAnalyzer", "type": "str"}, - "index_analyzer": {"key": "indexAnalyzer", "type": "str"}, - "normalizer": {"key": "normalizer", "type": "str"}, - "vector_search_dimensions": {"key": "dimensions", "type": "int"}, - "vector_search_profile_name": {"key": "vectorSearchProfile", "type": "str"}, - "vector_encoding_format": {"key": "vectorEncoding", "type": "str"}, - "synonym_maps": {"key": "synonymMaps", "type": "[str]"}, - "fields": {"key": "fields", "type": "[SearchField]"}, - } - - def __init__( - self, - *, - name: str, - type: Union[str, "_models.SearchFieldDataType"], - key: Optional[bool] = None, - retrievable: Optional[bool] = None, - stored: Optional[bool] = None, - searchable: Optional[bool] = None, - filterable: Optional[bool] = None, - sortable: Optional[bool] = None, - facetable: Optional[bool] = None, - permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = None, - sensitivity_label: Optional[bool] = None, - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - search_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - index_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, - vector_search_dimensions: Optional[int] = None, - vector_search_profile_name: Optional[str] = None, - vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = None, - synonym_maps: Optional[list[str]] = None, - fields: Optional[list["_models.SearchField"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the field, which must be unique within the fields collection of the - index or parent field. Required. - :paramtype name: str - :keyword type: The data type of the field. Required. Known values are: "Edm.String", - "Edm.Int32", "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", - "Edm.GeographyPoint", "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", - and "Edm.Byte". - :paramtype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType - :keyword key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type Edm.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is false for simple fields and null for complex fields. - :paramtype key: bool - :keyword retrievable: A value indicating whether the field can be returned in a search result. - You can disable this option if you want to use a field (for example, margin) as a filter, - sorting, or scoring mechanism but do not want the field to be visible to the end user. This - property must be true for key fields, and it must be null for complex fields. This property can - be changed on existing fields. Enabling this property does not cause any increase in index - storage requirements. Default is true for simple fields, false for vector fields, and null for - complex fields. - :paramtype retrievable: bool - :keyword stored: An immutable value indicating whether the field will be persisted separately - on disk to be returned in a search result. You can disable this option if you don't plan to - return the field contents in a search response to save on storage overhead. This can only be - set during index creation and only for vector fields. This property cannot be changed for - existing fields or set as false for new fields. If this property is set as false, the property - 'retrievable' must also be set to false. This property must be true or unset for key fields, - for new fields, and for non-vector fields, and it must be null for complex fields. Disabling - this property will reduce index storage requirements. The default is true for vector fields. - :paramtype stored: bool - :keyword searchable: A value indicating whether the field is full-text searchable. This means - it will undergo analysis such as word-breaking during indexing. If you set a searchable field - to a value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Fields of type Edm.String or - Collection(Edm.String) are searchable by default. This property must be false for simple fields - of other non-string data types, and it must be null for complex fields. Note: searchable fields - consume extra space in your index to accommodate additional tokenized versions of the field - value for full-text searches. If you want to save space in your index and you don't need a - field to be included in searches, set searchable to false. - :paramtype searchable: bool - :keyword filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so - comparisons are for exact matches only. For example, if you set such a field f to "sunny day", - $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property - must be null for complex fields. Default is true for simple fields and null for complex fields. - :paramtype filterable: bool - :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default, the search engine sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. Complex fields - cannot be sortable and the sortable property must be null for such fields. The default for - sortable is true for single-valued simple fields, false for multi-valued simple fields, and - null for complex fields. - :paramtype sortable: bool - :keyword facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or - Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple - fields. - :paramtype facetable: bool - :keyword permission_filter: A value indicating whether the field should be used as a permission - filter. Known values are: "userIds", "groupIds", and "rbacScope". - :paramtype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :keyword sensitivity_label: A value indicating whether the field should be used for sensitivity - label filtering. This enables document-level filtering based on Microsoft Purview sensitivity - labels. - :paramtype sensitivity_label: bool - :keyword analyzer: The name of the analyzer to use for the field. This option can be used only - with searchable fields and it can't be set together with either searchAnalyzer or - indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null - for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :paramtype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword search_analyzer: The name of the analyzer used at search time for the field. This - option can be used only with searchable fields. It must be set together with indexAnalyzer and - it cannot be set together with the analyzer option. This property cannot be set to the name of - a language analyzer; use the analyzer property instead if you need a language analyzer. This - analyzer can be updated on an existing field. Must be null for complex fields. Known values - are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", - "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", - "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", - "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", - "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", - "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", - "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", - "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", - "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", - "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", - "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :paramtype search_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword index_analyzer: The name of the analyzer used at indexing time for the field. This - option can be used only with searchable fields. It must be set together with searchAnalyzer and - it cannot be set together with the analyzer option. This property cannot be set to the name of - a language analyzer; use the analyzer property instead if you need a language analyzer. Once - the analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. - Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", - "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :paramtype index_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword normalizer: The name of the normalizer to use for the field. This option can be used - only with fields with filterable, sortable, or facetable enabled. Once the normalizer is - chosen, it cannot be changed for the field. Must be null for complex fields. Known values are: - "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :paramtype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :keyword vector_search_dimensions: The dimensionality of the vector field. - :paramtype vector_search_dimensions: int - :keyword vector_search_profile_name: The name of the vector search profile that specifies the - algorithm and vectorizer to use when searching the vector field. - :paramtype vector_search_profile_name: str - :keyword vector_encoding_format: The encoding format to interpret the field contents. - "packedBit" - :paramtype vector_encoding_format: str or - ~azure.search.documents.indexes.models.VectorEncodingFormat - :keyword synonym_maps: A list of the names of synonym maps to associate with this field. This - option can be used only with searchable fields. Currently only one synonym map per field is - supported. Assigning a synonym map to a field ensures that query terms targeting that field are - expanded at query-time using the rules in the synonym map. This attribute can be changed on - existing fields. Must be null or an empty collection for complex fields. - :paramtype synonym_maps: list[str] - :keyword fields: A list of sub-fields if this is a field of type Edm.ComplexType or - Collection(Edm.ComplexType). Must be null or empty for simple fields. - :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] - """ - super().__init__(**kwargs) - self.name = name - self.type = type - self.key = key - self.retrievable = retrievable - self.stored = stored - self.searchable = searchable - self.filterable = filterable - self.sortable = sortable - self.facetable = facetable - self.permission_filter = permission_filter - self.sensitivity_label = sensitivity_label - self.analyzer = analyzer - self.search_analyzer = search_analyzer - self.index_analyzer = index_analyzer - self.normalizer = normalizer - self.vector_search_dimensions = vector_search_dimensions - self.vector_search_profile_name = vector_search_profile_name - self.vector_encoding_format = vector_encoding_format - self.synonym_maps = synonym_maps - self.fields = fields - - -class SearchIndex(_serialization.Model): - """Represents a search index definition, which describes the fields and search behavior of an - index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the index. Required. - :vartype name: str - :ivar description: The description of the index. - :vartype description: str - :ivar fields: The fields of the index. Required. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - :ivar scoring_profiles: The scoring profiles for the index. - :vartype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] - :ivar default_scoring_profile: The name of the scoring profile to use if none is specified in - the query. If this property is not set and no scoring profile is specified in the query, then - default scoring (tf-idf) will be used. - :vartype default_scoring_profile: str - :ivar cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. - :vartype cors_options: ~azure.search.documents.indexes.models.CorsOptions - :ivar suggesters: The suggesters for the index. - :vartype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] - :ivar analyzers: The analyzers for the index. - :vartype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] - :ivar tokenizers: The tokenizers for the index. - :vartype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] - :ivar token_filters: The token filters for the index. - :vartype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] - :ivar char_filters: The character filters for the index. - :vartype char_filters: list[~azure.search.documents.indexes.models.CharFilter] - :ivar normalizers: The normalizers for the index. - :vartype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar similarity: The type of similarity algorithm to be used when scoring and ranking the - documents matching a search query. The similarity algorithm can only be defined at index - creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity - algorithm is used. - :vartype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm - :ivar semantic_search: Defines parameters for a search index that influence semantic - capabilities. - :vartype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch - :ivar vector_search: Contains configuration options related to vector search. - :vartype vector_search: ~azure.search.documents.indexes.models.VectorSearch - :ivar permission_filter_option: A value indicating whether permission filtering is enabled for - the index. Known values are: "enabled" and "disabled". - :vartype permission_filter_option: str or - ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption - :ivar purview_enabled: A value indicating whether the index is leveraging Purview-specific - features. This property defaults to false and cannot be changed after index creation. - :vartype purview_enabled: bool - :ivar e_tag: The ETag of the index. - :vartype e_tag: str - """ - - _validation = { - "name": {"required": True}, - "fields": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "fields": {"key": "fields", "type": "[SearchField]"}, - "scoring_profiles": {"key": "scoringProfiles", "type": "[ScoringProfile]"}, - "default_scoring_profile": {"key": "defaultScoringProfile", "type": "str"}, - "cors_options": {"key": "corsOptions", "type": "CorsOptions"}, - "suggesters": {"key": "suggesters", "type": "[SearchSuggester]"}, - "analyzers": {"key": "analyzers", "type": "[LexicalAnalyzer]"}, - "tokenizers": {"key": "tokenizers", "type": "[LexicalTokenizer]"}, - "token_filters": {"key": "tokenFilters", "type": "[TokenFilter]"}, - "char_filters": {"key": "charFilters", "type": "[CharFilter]"}, - "normalizers": {"key": "normalizers", "type": "[LexicalNormalizer]"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "similarity": {"key": "similarity", "type": "SimilarityAlgorithm"}, - "semantic_search": {"key": "semantic", "type": "SemanticSearch"}, - "vector_search": {"key": "vectorSearch", "type": "VectorSearch"}, - "permission_filter_option": {"key": "permissionFilterOption", "type": "str"}, - "purview_enabled": {"key": "purviewEnabled", "type": "bool"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - fields: list["_models.SearchField"], - description: Optional[str] = None, - scoring_profiles: Optional[list["_models.ScoringProfile"]] = None, - default_scoring_profile: Optional[str] = None, - cors_options: Optional["_models.CorsOptions"] = None, - suggesters: Optional[list["_models.SearchSuggester"]] = None, - analyzers: Optional[list["_models.LexicalAnalyzer"]] = None, - tokenizers: Optional[list["_models.LexicalTokenizer"]] = None, - token_filters: Optional[list["_models.TokenFilter"]] = None, - char_filters: Optional[list["_models.CharFilter"]] = None, - normalizers: Optional[list["_models.LexicalNormalizer"]] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - similarity: Optional["_models.SimilarityAlgorithm"] = None, - semantic_search: Optional["_models.SemanticSearch"] = None, - vector_search: Optional["_models.VectorSearch"] = None, - permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = None, - purview_enabled: Optional[bool] = None, - e_tag: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the index. Required. - :paramtype name: str - :keyword description: The description of the index. - :paramtype description: str - :keyword fields: The fields of the index. Required. - :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] - :keyword scoring_profiles: The scoring profiles for the index. - :paramtype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] - :keyword default_scoring_profile: The name of the scoring profile to use if none is specified - in the query. If this property is not set and no scoring profile is specified in the query, - then default scoring (tf-idf) will be used. - :paramtype default_scoring_profile: str - :keyword cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. - :paramtype cors_options: ~azure.search.documents.indexes.models.CorsOptions - :keyword suggesters: The suggesters for the index. - :paramtype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] - :keyword analyzers: The analyzers for the index. - :paramtype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] - :keyword tokenizers: The tokenizers for the index. - :paramtype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] - :keyword token_filters: The token filters for the index. - :paramtype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] - :keyword char_filters: The character filters for the index. - :paramtype char_filters: list[~azure.search.documents.indexes.models.CharFilter] - :keyword normalizers: The normalizers for the index. - :paramtype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword similarity: The type of similarity algorithm to be used when scoring and ranking the - documents matching a search query. The similarity algorithm can only be defined at index - creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity - algorithm is used. - :paramtype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm - :keyword semantic_search: Defines parameters for a search index that influence semantic - capabilities. - :paramtype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch - :keyword vector_search: Contains configuration options related to vector search. - :paramtype vector_search: ~azure.search.documents.indexes.models.VectorSearch - :keyword permission_filter_option: A value indicating whether permission filtering is enabled - for the index. Known values are: "enabled" and "disabled". - :paramtype permission_filter_option: str or - ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption - :keyword purview_enabled: A value indicating whether the index is leveraging Purview-specific - features. This property defaults to false and cannot be changed after index creation. - :paramtype purview_enabled: bool - :keyword e_tag: The ETag of the index. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.fields = fields - self.scoring_profiles = scoring_profiles - self.default_scoring_profile = default_scoring_profile - self.cors_options = cors_options - self.suggesters = suggesters - self.analyzers = analyzers - self.tokenizers = tokenizers - self.token_filters = token_filters - self.char_filters = char_filters - self.normalizers = normalizers - self.encryption_key = encryption_key - self.similarity = similarity - self.semantic_search = semantic_search - self.vector_search = vector_search - self.permission_filter_option = permission_filter_option - self.purview_enabled = purview_enabled - self.e_tag = e_tag - - -class SearchIndexer(_serialization.Model): - """Represents an indexer. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the indexer. Required. - :vartype name: str - :ivar description: The description of the indexer. - :vartype description: str - :ivar data_source_name: The name of the datasource from which this indexer reads data. - Required. - :vartype data_source_name: str - :ivar skillset_name: The name of the skillset executing with this indexer. - :vartype skillset_name: str - :ivar target_index_name: The name of the index to which this indexer writes data. Required. - :vartype target_index_name: str - :ivar schedule: The schedule for this indexer. - :vartype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :ivar parameters: Parameters for indexer execution. - :vartype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :ivar field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :vartype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar output_field_mappings: Output field mappings are applied after enrichment and immediately - before indexing. - :vartype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar is_disabled: A value indicating whether the indexer is disabled. Default is false. - :vartype is_disabled: bool - :ivar e_tag: The ETag of the indexer. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar cache: Adds caching to an enrichment pipeline to allow for incremental modification steps - without having to rebuild the index every time. - :vartype cache: ~azure.search.documents.indexes.models.SearchIndexerCache - """ - - _validation = { - "name": {"required": True}, - "data_source_name": {"required": True}, - "target_index_name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "data_source_name": {"key": "dataSourceName", "type": "str"}, - "skillset_name": {"key": "skillsetName", "type": "str"}, - "target_index_name": {"key": "targetIndexName", "type": "str"}, - "schedule": {"key": "schedule", "type": "IndexingSchedule"}, - "parameters": {"key": "parameters", "type": "IndexingParameters"}, - "field_mappings": {"key": "fieldMappings", "type": "[FieldMapping]"}, - "output_field_mappings": {"key": "outputFieldMappings", "type": "[FieldMapping]"}, - "is_disabled": {"key": "disabled", "type": "bool"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "cache": {"key": "cache", "type": "SearchIndexerCache"}, - } - - def __init__( - self, - *, - name: str, - data_source_name: str, - target_index_name: str, - description: Optional[str] = None, - skillset_name: Optional[str] = None, - schedule: Optional["_models.IndexingSchedule"] = None, - parameters: Optional["_models.IndexingParameters"] = None, - field_mappings: Optional[list["_models.FieldMapping"]] = None, - output_field_mappings: Optional[list["_models.FieldMapping"]] = None, - is_disabled: bool = False, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - cache: Optional["_models.SearchIndexerCache"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the indexer. Required. - :paramtype name: str - :keyword description: The description of the indexer. - :paramtype description: str - :keyword data_source_name: The name of the datasource from which this indexer reads data. - Required. - :paramtype data_source_name: str - :keyword skillset_name: The name of the skillset executing with this indexer. - :paramtype skillset_name: str - :keyword target_index_name: The name of the index to which this indexer writes data. Required. - :paramtype target_index_name: str - :keyword schedule: The schedule for this indexer. - :paramtype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :keyword parameters: Parameters for indexer execution. - :paramtype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :keyword field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :paramtype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword output_field_mappings: Output field mappings are applied after enrichment and - immediately before indexing. - :paramtype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword is_disabled: A value indicating whether the indexer is disabled. Default is false. - :paramtype is_disabled: bool - :keyword e_tag: The ETag of the indexer. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword cache: Adds caching to an enrichment pipeline to allow for incremental modification - steps without having to rebuild the index every time. - :paramtype cache: ~azure.search.documents.indexes.models.SearchIndexerCache - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.data_source_name = data_source_name - self.skillset_name = skillset_name - self.target_index_name = target_index_name - self.schedule = schedule - self.parameters = parameters - self.field_mappings = field_mappings - self.output_field_mappings = output_field_mappings - self.is_disabled = is_disabled - self.e_tag = e_tag - self.encryption_key = encryption_key - self.cache = cache - - -class SearchIndexerCache(_serialization.Model): - """SearchIndexerCache. - - :ivar id: A guid for the SearchIndexerCache. - :vartype id: str - :ivar storage_connection_string: The connection string to the storage account where the cache - data will be persisted. - :vartype storage_connection_string: str - :ivar enable_reprocessing: Specifies whether incremental reprocessing is enabled. - :vartype enable_reprocessing: bool - :ivar identity: The user-assigned managed identity used for connections to the enrichment - cache. If the connection string indicates an identity (ResourceId) and it's not specified, the - system-assigned managed identity is used. On updates to the indexer, if the identity is - unspecified, the value remains unchanged. If set to "none", the value of this property is - cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "storage_connection_string": {"key": "storageConnectionString", "type": "str"}, - "enable_reprocessing": {"key": "enableReprocessing", "type": "bool"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - storage_connection_string: Optional[str] = None, - enable_reprocessing: Optional[bool] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: A guid for the SearchIndexerCache. - :paramtype id: str - :keyword storage_connection_string: The connection string to the storage account where the - cache data will be persisted. - :paramtype storage_connection_string: str - :keyword enable_reprocessing: Specifies whether incremental reprocessing is enabled. - :paramtype enable_reprocessing: bool - :keyword identity: The user-assigned managed identity used for connections to the enrichment - cache. If the connection string indicates an identity (ResourceId) and it's not specified, the - system-assigned managed identity is used. On updates to the indexer, if the identity is - unspecified, the value remains unchanged. If set to "none", the value of this property is - cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.id = id - self.storage_connection_string = storage_connection_string - self.enable_reprocessing = enable_reprocessing - self.identity = identity - - -class SearchIndexerDataContainer(_serialization.Model): - """Represents information about the entity (such as Azure SQL table or CosmosDB collection) that - will be indexed. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the table or view (for Azure SQL data source) or collection (for - CosmosDB data source) that will be indexed. Required. - :vartype name: str - :ivar query: A query that is applied to this data container. The syntax and meaning of this - parameter is datasource-specific. Not supported by Azure SQL datasources. - :vartype query: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "query": {"key": "query", "type": "str"}, - } - - def __init__(self, *, name: str, query: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the table or view (for Azure SQL data source) or collection (for - CosmosDB data source) that will be indexed. Required. - :paramtype name: str - :keyword query: A query that is applied to this data container. The syntax and meaning of this - parameter is datasource-specific. Not supported by Azure SQL datasources. - :paramtype query: str - """ - super().__init__(**kwargs) - self.name = name - self.query = query - - -class SearchIndexerDataIdentity(_serialization.Model): - """Abstract base type for data identities. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - SearchIndexerDataNoneIdentity, SearchIndexerDataUserAssignedIdentity - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of identity. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.DataNoneIdentity": "SearchIndexerDataNoneIdentity", - "#Microsoft.Azure.Search.DataUserAssignedIdentity": "SearchIndexerDataUserAssignedIdentity", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class SearchIndexerDataNoneIdentity(SearchIndexerDataIdentity): - """Clears the identity property of a datasource. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of identity. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DataNoneIdentity" - - -class SearchIndexerDataSource(_serialization.Model): - """Represents a datasource definition, which can be used to configure an indexer. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the datasource. Required. - :vartype name: str - :ivar description: The description of the datasource. - :vartype description: str - :ivar type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", - "azureblob", "azuretable", "mysql", "adlsgen2", "onelake", and "sharepoint". - :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :ivar sub_type: A specific type of the data source, in case the resource is capable of - different modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts. - :vartype sub_type: str - :ivar credentials: Credentials for the datasource. Required. - :vartype credentials: ~azure.search.documents.indexes.models.DataSourceCredentials - :ivar container: The data container for the datasource. Required. - :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :ivar identity: An explicit managed identity to use for this datasource. If not specified and - the connection string is a managed identity, the system-assigned managed identity is used. If - not specified, the value remains unchanged. If "none" is specified, the value of this property - is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar indexer_permission_options: Ingestion options with various types of permission data. - :vartype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :ivar data_change_detection_policy: The data change detection policy for the datasource. - :vartype data_change_detection_policy: - ~azure.search.documents.indexes.models.DataChangeDetectionPolicy - :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource. - :vartype data_deletion_detection_policy: - ~azure.search.documents.indexes.models.DataDeletionDetectionPolicy - :ivar e_tag: The ETag of the data source. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition. Once you have encrypted your data source definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your datasource definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - _validation = { - "name": {"required": True}, - "type": {"required": True}, - "sub_type": {"readonly": True}, - "credentials": {"required": True}, - "container": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "sub_type": {"key": "subType", "type": "str"}, - "credentials": {"key": "credentials", "type": "DataSourceCredentials"}, - "container": {"key": "container", "type": "SearchIndexerDataContainer"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "indexer_permission_options": {"key": "indexerPermissionOptions", "type": "[str]"}, - "data_change_detection_policy": {"key": "dataChangeDetectionPolicy", "type": "DataChangeDetectionPolicy"}, - "data_deletion_detection_policy": {"key": "dataDeletionDetectionPolicy", "type": "DataDeletionDetectionPolicy"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - } - - def __init__( - self, - *, - name: str, - type: Union[str, "_models.SearchIndexerDataSourceType"], - credentials: "_models.DataSourceCredentials", - container: "_models.SearchIndexerDataContainer", - description: Optional[str] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = None, - data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = None, - data_deletion_detection_policy: Optional["_models.DataDeletionDetectionPolicy"] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the datasource. Required. - :paramtype name: str - :keyword description: The description of the datasource. - :paramtype description: str - :keyword type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", - "azureblob", "azuretable", "mysql", "adlsgen2", "onelake", and "sharepoint". - :paramtype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :keyword credentials: Credentials for the datasource. Required. - :paramtype credentials: ~azure.search.documents.indexes.models.DataSourceCredentials - :keyword container: The data container for the datasource. Required. - :paramtype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :keyword identity: An explicit managed identity to use for this datasource. If not specified - and the connection string is a managed identity, the system-assigned managed identity is used. - If not specified, the value remains unchanged. If "none" is specified, the value of this - property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword indexer_permission_options: Ingestion options with various types of permission data. - :paramtype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :keyword data_change_detection_policy: The data change detection policy for the datasource. - :paramtype data_change_detection_policy: - ~azure.search.documents.indexes.models.DataChangeDetectionPolicy - :keyword data_deletion_detection_policy: The data deletion detection policy for the datasource. - :paramtype data_deletion_detection_policy: - ~azure.search.documents.indexes.models.DataDeletionDetectionPolicy - :keyword e_tag: The ETag of the data source. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition. Once you have encrypted your data source definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your datasource definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.type = type - self.sub_type: Optional[str] = None - self.credentials = credentials - self.container = container - self.identity = identity - self.indexer_permission_options = indexer_permission_options - self.data_change_detection_policy = data_change_detection_policy - self.data_deletion_detection_policy = data_deletion_detection_policy - self.e_tag = e_tag - self.encryption_key = encryption_key - - -class SearchIndexerDataUserAssignedIdentity(SearchIndexerDataIdentity): - """Specifies the identity for a datasource to use. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of identity. Required. - :vartype odata_type: str - :ivar resource_id: The fully qualified Azure resource Id of a user assigned managed identity - typically in the form - "/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId" - that should have been assigned to the search service. Required. - :vartype resource_id: str - """ - - _validation = { - "odata_type": {"required": True}, - "resource_id": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "resource_id": {"key": "userAssignedIdentity", "type": "str"}, - } - - def __init__(self, *, resource_id: str, **kwargs: Any) -> None: - """ - :keyword resource_id: The fully qualified Azure resource Id of a user assigned managed identity - typically in the form - "/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId" - that should have been assigned to the search service. Required. - :paramtype resource_id: str - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DataUserAssignedIdentity" - self.resource_id = resource_id - - -class SearchIndexerError(_serialization.Model): - """Represents an item- or document-level indexing error. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar key: The key of the item for which indexing failed. - :vartype key: str - :ivar error_message: The message describing the error that occurred while processing the item. - Required. - :vartype error_message: str - :ivar status_code: The status code indicating why the indexing operation failed. Possible - values include: 400 for a malformed input document, 404 for document not found, 409 for a - version conflict, 422 when the index is temporarily unavailable, or 503 for when the service is - too busy. Required. - :vartype status_code: int - :ivar name: The name of the source at which the error originated. For example, this could refer - to a particular skill in the attached skillset. This may not be always available. - :vartype name: str - :ivar details: Additional, verbose details about the error to assist in debugging the indexer. - This may not be always available. - :vartype details: str - :ivar documentation_link: A link to a troubleshooting guide for these classes of errors. This - may not be always available. - :vartype documentation_link: str - """ - - _validation = { - "key": {"readonly": True}, - "error_message": {"required": True, "readonly": True}, - "status_code": {"required": True, "readonly": True}, - "name": {"readonly": True}, - "details": {"readonly": True}, - "documentation_link": {"readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "error_message": {"key": "errorMessage", "type": "str"}, - "status_code": {"key": "statusCode", "type": "int"}, - "name": {"key": "name", "type": "str"}, - "details": {"key": "details", "type": "str"}, - "documentation_link": {"key": "documentationLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.key: Optional[str] = None - self.error_message: Optional[str] = None - self.status_code: Optional[int] = None - self.name: Optional[str] = None - self.details: Optional[str] = None - self.documentation_link: Optional[str] = None - - -class SearchIndexerIndexProjection(_serialization.Model): - """Definition of additional projections to secondary search indexes. - - All required parameters must be populated in order to send to server. - - :ivar selectors: A list of projections to be performed to secondary search indexes. Required. - :vartype selectors: - list[~azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector] - :ivar parameters: A dictionary of index projection-specific configuration properties. Each name - is the name of a specific property. Each value must be of a primitive type. - :vartype parameters: - ~azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters - """ - - _validation = { - "selectors": {"required": True}, - } - - _attribute_map = { - "selectors": {"key": "selectors", "type": "[SearchIndexerIndexProjectionSelector]"}, - "parameters": {"key": "parameters", "type": "SearchIndexerIndexProjectionsParameters"}, - } - - def __init__( - self, - *, - selectors: list["_models.SearchIndexerIndexProjectionSelector"], - parameters: Optional["_models.SearchIndexerIndexProjectionsParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword selectors: A list of projections to be performed to secondary search indexes. - Required. - :paramtype selectors: - list[~azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector] - :keyword parameters: A dictionary of index projection-specific configuration properties. Each - name is the name of a specific property. Each value must be of a primitive type. - :paramtype parameters: - ~azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters - """ - super().__init__(**kwargs) - self.selectors = selectors - self.parameters = parameters - - -class SearchIndexerIndexProjectionSelector(_serialization.Model): - """Description for what data to store in the designated search index. - - All required parameters must be populated in order to send to server. - - :ivar target_index_name: Name of the search index to project to. Must have a key field with the - 'keyword' analyzer set. Required. - :vartype target_index_name: str - :ivar parent_key_field_name: Name of the field in the search index to map the parent document's - key value to. Must be a string field that is filterable and not the key field. Required. - :vartype parent_key_field_name: str - :ivar source_context: Source context for the projections. Represents the cardinality at which - the document will be split into multiple sub documents. Required. - :vartype source_context: str - :ivar mappings: Mappings for the projection, or which source should be mapped to which field in - the target index. Required. - :vartype mappings: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - - _validation = { - "target_index_name": {"required": True}, - "parent_key_field_name": {"required": True}, - "source_context": {"required": True}, - "mappings": {"required": True}, - } - - _attribute_map = { - "target_index_name": {"key": "targetIndexName", "type": "str"}, - "parent_key_field_name": {"key": "parentKeyFieldName", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "mappings": {"key": "mappings", "type": "[InputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - target_index_name: str, - parent_key_field_name: str, - source_context: str, - mappings: list["_models.InputFieldMappingEntry"], - **kwargs: Any - ) -> None: - """ - :keyword target_index_name: Name of the search index to project to. Must have a key field with - the 'keyword' analyzer set. Required. - :paramtype target_index_name: str - :keyword parent_key_field_name: Name of the field in the search index to map the parent - document's key value to. Must be a string field that is filterable and not the key field. - Required. - :paramtype parent_key_field_name: str - :keyword source_context: Source context for the projections. Represents the cardinality at - which the document will be split into multiple sub documents. Required. - :paramtype source_context: str - :keyword mappings: Mappings for the projection, or which source should be mapped to which field - in the target index. Required. - :paramtype mappings: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.target_index_name = target_index_name - self.parent_key_field_name = parent_key_field_name - self.source_context = source_context - self.mappings = mappings - - -class SearchIndexerIndexProjectionsParameters(_serialization.Model): - """A dictionary of index projection-specific configuration properties. Each name is the name of a - specific property. Each value must be of a primitive type. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar projection_mode: Defines behavior of the index projections in relation to the rest of the - indexer. Known values are: "skipIndexingParentDocuments" and "includeIndexingParentDocuments". - :vartype projection_mode: str or ~azure.search.documents.indexes.models.IndexProjectionMode - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "projection_mode": {"key": "projectionMode", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - projection_mode: Optional[Union[str, "_models.IndexProjectionMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword projection_mode: Defines behavior of the index projections in relation to the rest of - the indexer. Known values are: "skipIndexingParentDocuments" and - "includeIndexingParentDocuments". - :paramtype projection_mode: str or ~azure.search.documents.indexes.models.IndexProjectionMode - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.projection_mode = projection_mode - - -class SearchIndexerKnowledgeStore(_serialization.Model): - """Definition of additional projections to azure blob, table, or files, of enriched data. - - All required parameters must be populated in order to send to server. - - :ivar storage_connection_string: The connection string to the storage account projections will - be stored in. Required. - :vartype storage_connection_string: str - :ivar projections: A list of additional projections to perform during indexing. Required. - :vartype projections: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection] - :ivar identity: The user-assigned managed identity used for connections to Azure Storage when - writing knowledge store projections. If the connection string indicates an identity - (ResourceId) and it's not specified, the system-assigned managed identity is used. On updates - to the indexer, if the identity is unspecified, the value remains unchanged. If set to "none", - the value of this property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar parameters: A dictionary of knowledge store-specific configuration properties. Each name - is the name of a specific property. Each value must be of a primitive type. - :vartype parameters: - ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters - """ - - _validation = { - "storage_connection_string": {"required": True}, - "projections": {"required": True}, - } - - _attribute_map = { - "storage_connection_string": {"key": "storageConnectionString", "type": "str"}, - "projections": {"key": "projections", "type": "[SearchIndexerKnowledgeStoreProjection]"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "parameters": {"key": "parameters", "type": "SearchIndexerKnowledgeStoreParameters"}, - } - - def __init__( - self, - *, - storage_connection_string: str, - projections: list["_models.SearchIndexerKnowledgeStoreProjection"], - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - parameters: Optional["_models.SearchIndexerKnowledgeStoreParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword storage_connection_string: The connection string to the storage account projections - will be stored in. Required. - :paramtype storage_connection_string: str - :keyword projections: A list of additional projections to perform during indexing. Required. - :paramtype projections: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection] - :keyword identity: The user-assigned managed identity used for connections to Azure Storage - when writing knowledge store projections. If the connection string indicates an identity - (ResourceId) and it's not specified, the system-assigned managed identity is used. On updates - to the indexer, if the identity is unspecified, the value remains unchanged. If set to "none", - the value of this property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword parameters: A dictionary of knowledge store-specific configuration properties. Each - name is the name of a specific property. Each value must be of a primitive type. - :paramtype parameters: - ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters - """ - super().__init__(**kwargs) - self.storage_connection_string = storage_connection_string - self.projections = projections - self.identity = identity - self.parameters = parameters - - -class SearchIndexerKnowledgeStoreProjectionSelector(_serialization.Model): # pylint: disable=name-too-long - """Abstract class to share properties between concrete selectors. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - - _attribute_map = { - "reference_key_name": {"key": "referenceKeyName", "type": "str"}, - "generated_key_name": {"key": "generatedKeyName", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reference_key_name: Name of reference key to different projection. - :paramtype reference_key_name: str - :keyword generated_key_name: Name of generated key to store projection under. - :paramtype generated_key_name: str - :keyword source: Source data to project. - :paramtype source: str - :keyword source_context: Source context for complex projections. - :paramtype source_context: str - :keyword inputs: Nested inputs for complex projections. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.reference_key_name = reference_key_name - self.generated_key_name = generated_key_name - self.source = source - self.source_context = source_context - self.inputs = inputs - - -class SearchIndexerKnowledgeStoreBlobProjectionSelector( - SearchIndexerKnowledgeStoreProjectionSelector -): # pylint: disable=name-too-long - """Abstract class to share properties between concrete selectors. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar storage_container: Blob container to store projections in. Required. - :vartype storage_container: str - """ - - _validation = { - "storage_container": {"required": True}, - } - - _attribute_map = { - "reference_key_name": {"key": "referenceKeyName", "type": "str"}, - "generated_key_name": {"key": "generatedKeyName", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "storage_container": {"key": "storageContainer", "type": "str"}, - } - - def __init__( - self, - *, - storage_container: str, - reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reference_key_name: Name of reference key to different projection. - :paramtype reference_key_name: str - :keyword generated_key_name: Name of generated key to store projection under. - :paramtype generated_key_name: str - :keyword source: Source data to project. - :paramtype source: str - :keyword source_context: Source context for complex projections. - :paramtype source_context: str - :keyword inputs: Nested inputs for complex projections. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword storage_container: Blob container to store projections in. Required. - :paramtype storage_container: str - """ - super().__init__( - reference_key_name=reference_key_name, - generated_key_name=generated_key_name, - source=source, - source_context=source_context, - inputs=inputs, - **kwargs - ) - self.storage_container = storage_container - - -class SearchIndexerKnowledgeStoreFileProjectionSelector( - SearchIndexerKnowledgeStoreBlobProjectionSelector -): # pylint: disable=name-too-long - """Projection definition for what data to store in Azure Files. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar storage_container: Blob container to store projections in. Required. - :vartype storage_container: str - """ - - -class SearchIndexerKnowledgeStoreObjectProjectionSelector( - SearchIndexerKnowledgeStoreBlobProjectionSelector -): # pylint: disable=name-too-long - """Projection definition for what data to store in Azure Blob. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar storage_container: Blob container to store projections in. Required. - :vartype storage_container: str - """ - - -class SearchIndexerKnowledgeStoreParameters(_serialization.Model): - """A dictionary of knowledge store-specific configuration properties. Each name is the name of a - specific property. Each value must be of a primitive type. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar synthesize_generated_key_name: Whether or not projections should synthesize a generated - key name if one isn't already present. - :vartype synthesize_generated_key_name: bool - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "synthesize_generated_key_name": {"key": "synthesizeGeneratedKeyName", "type": "bool"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - synthesize_generated_key_name: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword synthesize_generated_key_name: Whether or not projections should synthesize a - generated key name if one isn't already present. - :paramtype synthesize_generated_key_name: bool - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.synthesize_generated_key_name = synthesize_generated_key_name - - -class SearchIndexerKnowledgeStoreProjection(_serialization.Model): - """Container object for various projection selectors. - - :ivar tables: Projections to Azure Table storage. - :vartype tables: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector] - :ivar objects: Projections to Azure Blob storage. - :vartype objects: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector] - :ivar files: Projections to Azure File storage. - :vartype files: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector] - """ - - _attribute_map = { - "tables": {"key": "tables", "type": "[SearchIndexerKnowledgeStoreTableProjectionSelector]"}, - "objects": {"key": "objects", "type": "[SearchIndexerKnowledgeStoreObjectProjectionSelector]"}, - "files": {"key": "files", "type": "[SearchIndexerKnowledgeStoreFileProjectionSelector]"}, - } - - def __init__( - self, - *, - tables: Optional[list["_models.SearchIndexerKnowledgeStoreTableProjectionSelector"]] = None, - objects: Optional[list["_models.SearchIndexerKnowledgeStoreObjectProjectionSelector"]] = None, - files: Optional[list["_models.SearchIndexerKnowledgeStoreFileProjectionSelector"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword tables: Projections to Azure Table storage. - :paramtype tables: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector] - :keyword objects: Projections to Azure Blob storage. - :paramtype objects: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector] - :keyword files: Projections to Azure File storage. - :paramtype files: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector] - """ - super().__init__(**kwargs) - self.tables = tables - self.objects = objects - self.files = files - - -class SearchIndexerKnowledgeStoreTableProjectionSelector( - SearchIndexerKnowledgeStoreProjectionSelector -): # pylint: disable=name-too-long - """Description for what data to store in Azure Tables. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar table_name: Name of the Azure table to store projected data in. Required. - :vartype table_name: str - """ - - _validation = { - "table_name": {"required": True}, - } - - _attribute_map = { - "reference_key_name": {"key": "referenceKeyName", "type": "str"}, - "generated_key_name": {"key": "generatedKeyName", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "table_name": {"key": "tableName", "type": "str"}, - } - - def __init__( - self, - *, - table_name: str, - reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reference_key_name: Name of reference key to different projection. - :paramtype reference_key_name: str - :keyword generated_key_name: Name of generated key to store projection under. - :paramtype generated_key_name: str - :keyword source: Source data to project. - :paramtype source: str - :keyword source_context: Source context for complex projections. - :paramtype source_context: str - :keyword inputs: Nested inputs for complex projections. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword table_name: Name of the Azure table to store projected data in. Required. - :paramtype table_name: str - """ - super().__init__( - reference_key_name=reference_key_name, - generated_key_name=generated_key_name, - source=source, - source_context=source_context, - inputs=inputs, - **kwargs - ) - self.table_name = table_name - - -class SearchIndexerLimits(_serialization.Model): - """SearchIndexerLimits. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar max_run_time: The maximum duration that the indexer is permitted to run for one - execution. - :vartype max_run_time: ~datetime.timedelta - :ivar max_document_extraction_size: The maximum size of a document, in bytes, which will be - considered valid for indexing. - :vartype max_document_extraction_size: int - :ivar max_document_content_characters_to_extract: The maximum number of characters that will be - extracted from a document picked up for indexing. - :vartype max_document_content_characters_to_extract: int - """ - - _validation = { - "max_run_time": {"readonly": True}, - "max_document_extraction_size": {"readonly": True}, - "max_document_content_characters_to_extract": {"readonly": True}, - } - - _attribute_map = { - "max_run_time": {"key": "maxRunTime", "type": "duration"}, - "max_document_extraction_size": {"key": "maxDocumentExtractionSize", "type": "int"}, - "max_document_content_characters_to_extract": {"key": "maxDocumentContentCharactersToExtract", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.max_run_time: Optional[datetime.timedelta] = None - self.max_document_extraction_size: Optional[int] = None - self.max_document_content_characters_to_extract: Optional[int] = None - - -class SearchIndexerSkillset(_serialization.Model): - """A list of skills. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the skillset. Required. - :vartype name: str - :ivar description: The description of the skillset. - :vartype description: str - :ivar skills: A list of skills in the skillset. Required. - :vartype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] - :ivar cognitive_services_account: Details about the Azure AI service to be used when running - skills. - :vartype cognitive_services_account: - ~azure.search.documents.indexes.models.CognitiveServicesAccount - :ivar knowledge_store: Definition of additional projections to Azure blob, table, or files, of - enriched data. - :vartype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore - :ivar index_projection: Definition of additional projections to secondary search index(es). - :vartype index_projection: ~azure.search.documents.indexes.models.SearchIndexerIndexProjection - :ivar e_tag: The ETag of the skillset. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your skillset - definition when you want full assurance that no one, not even Microsoft, can decrypt your - skillset definition. Once you have encrypted your skillset definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your skillset definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - _validation = { - "name": {"required": True}, - "skills": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "skills": {"key": "skills", "type": "[SearchIndexerSkill]"}, - "cognitive_services_account": {"key": "cognitiveServices", "type": "CognitiveServicesAccount"}, - "knowledge_store": {"key": "knowledgeStore", "type": "SearchIndexerKnowledgeStore"}, - "index_projection": {"key": "indexProjections", "type": "SearchIndexerIndexProjection"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - } - - def __init__( - self, - *, - name: str, - skills: list["_models.SearchIndexerSkill"], - description: Optional[str] = None, - cognitive_services_account: Optional["_models.CognitiveServicesAccount"] = None, - knowledge_store: Optional["_models.SearchIndexerKnowledgeStore"] = None, - index_projection: Optional["_models.SearchIndexerIndexProjection"] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skillset. Required. - :paramtype name: str - :keyword description: The description of the skillset. - :paramtype description: str - :keyword skills: A list of skills in the skillset. Required. - :paramtype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] - :keyword cognitive_services_account: Details about the Azure AI service to be used when running - skills. - :paramtype cognitive_services_account: - ~azure.search.documents.indexes.models.CognitiveServicesAccount - :keyword knowledge_store: Definition of additional projections to Azure blob, table, or files, - of enriched data. - :paramtype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore - :keyword index_projection: Definition of additional projections to secondary search index(es). - :paramtype index_projection: - ~azure.search.documents.indexes.models.SearchIndexerIndexProjection - :keyword e_tag: The ETag of the skillset. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your skillset - definition when you want full assurance that no one, not even Microsoft, can decrypt your - skillset definition. Once you have encrypted your skillset definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your skillset definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.skills = skills - self.cognitive_services_account = cognitive_services_account - self.knowledge_store = knowledge_store - self.index_projection = index_projection - self.e_tag = e_tag - self.encryption_key = encryption_key - - -class SearchIndexerStatus(_serialization.Model): - """Represents the current status and execution history of an indexer. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the indexer. Required. - :vartype name: str - :ivar status: Overall indexer status. Required. Known values are: "unknown", "error", and - "running". - :vartype status: str or ~azure.search.documents.indexes.models.IndexerStatus - :ivar runtime: Snapshot of the indexer’s cumulative runtime consumption for the service over - the current UTC period. Required. - :vartype runtime: ~azure.search.documents.indexes.models.IndexerRuntime - :ivar last_result: The result of the most recent or an in-progress indexer execution. - :vartype last_result: ~azure.search.documents.indexes.models.IndexerExecutionResult - :ivar execution_history: History of the recent indexer executions, sorted in reverse - chronological order. Required. - :vartype execution_history: list[~azure.search.documents.indexes.models.IndexerExecutionResult] - :ivar limits: The execution limits for the indexer. Required. - :vartype limits: ~azure.search.documents.indexes.models.SearchIndexerLimits - :ivar current_state: All of the state that defines and dictates the indexer's current - execution. - :vartype current_state: ~azure.search.documents.indexes.models.IndexerCurrentState - """ - - _validation = { - "name": {"required": True, "readonly": True}, - "status": {"required": True, "readonly": True}, - "runtime": {"required": True, "readonly": True}, - "last_result": {"readonly": True}, - "execution_history": {"required": True, "readonly": True}, - "limits": {"required": True, "readonly": True}, - "current_state": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "runtime": {"key": "runtime", "type": "IndexerRuntime"}, - "last_result": {"key": "lastResult", "type": "IndexerExecutionResult"}, - "execution_history": {"key": "executionHistory", "type": "[IndexerExecutionResult]"}, - "limits": {"key": "limits", "type": "SearchIndexerLimits"}, - "current_state": {"key": "currentState", "type": "IndexerCurrentState"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.status: Optional[Union[str, "_models.IndexerStatus"]] = None - self.runtime: Optional["_models.IndexerRuntime"] = None - self.last_result: Optional["_models.IndexerExecutionResult"] = None - self.execution_history: Optional[list["_models.IndexerExecutionResult"]] = None - self.limits: Optional["_models.SearchIndexerLimits"] = None - self.current_state: Optional["_models.IndexerCurrentState"] = None - - -class SearchIndexerWarning(_serialization.Model): - """Represents an item-level warning. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar key: The key of the item which generated a warning. - :vartype key: str - :ivar message: The message describing the warning that occurred while processing the item. - Required. - :vartype message: str - :ivar name: The name of the source at which the warning originated. For example, this could - refer to a particular skill in the attached skillset. This may not be always available. - :vartype name: str - :ivar details: Additional, verbose details about the warning to assist in debugging the - indexer. This may not be always available. - :vartype details: str - :ivar documentation_link: A link to a troubleshooting guide for these classes of warnings. This - may not be always available. - :vartype documentation_link: str - """ - - _validation = { - "key": {"readonly": True}, - "message": {"required": True, "readonly": True}, - "name": {"readonly": True}, - "details": {"readonly": True}, - "documentation_link": {"readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "details": {"key": "details", "type": "str"}, - "documentation_link": {"key": "documentationLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.key: Optional[str] = None - self.message: Optional[str] = None - self.name: Optional[str] = None - self.details: Optional[str] = None - self.documentation_link: Optional[str] = None - - -class SearchIndexFieldReference(_serialization.Model): - """SearchIndexFieldReference. - - All required parameters must be populated in order to send to server. - - :ivar name: Required. - :vartype name: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - - -class SearchIndexKnowledgeSource(KnowledgeSource): - """Knowledge Source targeting a search index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar search_index_parameters: The parameters for the knowledge source. Required. - :vartype search_index_parameters: - ~azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - "search_index_parameters": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "search_index_parameters": {"key": "searchIndexParameters", "type": "SearchIndexKnowledgeSourceParameters"}, - } - - def __init__( - self, - *, - name: str, - search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters", - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword search_index_parameters: The parameters for the knowledge source. Required. - :paramtype search_index_parameters: - ~azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "searchIndex" - self.search_index_parameters = search_index_parameters - - -class SearchIndexKnowledgeSourceParameters(_serialization.Model): - """Parameters for search index knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar search_index_name: The name of the Search index. Required. - :vartype search_index_name: str - :ivar source_data_fields: Used to request additional fields for referenced source data. - :vartype source_data_fields: - list[~azure.search.documents.indexes.models.SearchIndexFieldReference] - :ivar search_fields: Used to restrict which fields to search on the search index. - :vartype search_fields: list[~azure.search.documents.indexes.models.SearchIndexFieldReference] - :ivar semantic_configuration_name: Used to specify a different semantic configuration on the - target search index other than the default one. - :vartype semantic_configuration_name: str - """ - - _validation = { - "search_index_name": {"required": True}, - } - - _attribute_map = { - "search_index_name": {"key": "searchIndexName", "type": "str"}, - "source_data_fields": {"key": "sourceDataFields", "type": "[SearchIndexFieldReference]"}, - "search_fields": {"key": "searchFields", "type": "[SearchIndexFieldReference]"}, - "semantic_configuration_name": {"key": "semanticConfigurationName", "type": "str"}, - } - - def __init__( - self, - *, - search_index_name: str, - source_data_fields: Optional[list["_models.SearchIndexFieldReference"]] = None, - search_fields: Optional[list["_models.SearchIndexFieldReference"]] = None, - semantic_configuration_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword search_index_name: The name of the Search index. Required. - :paramtype search_index_name: str - :keyword source_data_fields: Used to request additional fields for referenced source data. - :paramtype source_data_fields: - list[~azure.search.documents.indexes.models.SearchIndexFieldReference] - :keyword search_fields: Used to restrict which fields to search on the search index. - :paramtype search_fields: - list[~azure.search.documents.indexes.models.SearchIndexFieldReference] - :keyword semantic_configuration_name: Used to specify a different semantic configuration on the - target search index other than the default one. - :paramtype semantic_configuration_name: str - """ - super().__init__(**kwargs) - self.search_index_name = search_index_name - self.source_data_fields = source_data_fields - self.search_fields = search_fields - self.semantic_configuration_name = semantic_configuration_name - - -class SearchResourceEncryptionKey(_serialization.Model): - """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be - used to encrypt or decrypt data-at-rest, such as indexes and synonym maps. - - All required parameters must be populated in order to send to server. - - :ivar key_name: The name of your Azure Key Vault key to be used to encrypt your data at rest. - Required. - :vartype key_name: str - :ivar key_version: The version of your Azure Key Vault key to be used to encrypt your data at - rest. - :vartype key_version: str - :ivar vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that contains - the key to be used to encrypt your data at rest. An example URI might be - ``https://my-keyvault-name.vault.azure.net``. Required. - :vartype vault_uri: str - :ivar access_credentials: Optional Azure Active Directory credentials used for accessing your - Azure Key Vault. Not required if using managed identity instead. - :vartype access_credentials: - ~azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials - :ivar identity: An explicit managed identity to use for this encryption key. If not specified - and the access credentials property is null, the system-assigned managed identity is used. On - update to the resource, if the explicit identity is unspecified, it remains unchanged. If - "none" is specified, the value of this property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _validation = { - "key_name": {"required": True}, - "vault_uri": {"required": True}, - } - - _attribute_map = { - "key_name": {"key": "keyVaultKeyName", "type": "str"}, - "key_version": {"key": "keyVaultKeyVersion", "type": "str"}, - "vault_uri": {"key": "keyVaultUri", "type": "str"}, - "access_credentials": {"key": "accessCredentials", "type": "AzureActiveDirectoryApplicationCredentials"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - key_name: str, - vault_uri: str, - key_version: Optional[str] = None, - access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword key_name: The name of your Azure Key Vault key to be used to encrypt your data at - rest. Required. - :paramtype key_name: str - :keyword key_version: The version of your Azure Key Vault key to be used to encrypt your data - at rest. - :paramtype key_version: str - :keyword vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that - contains the key to be used to encrypt your data at rest. An example URI might be - ``https://my-keyvault-name.vault.azure.net``. Required. - :paramtype vault_uri: str - :keyword access_credentials: Optional Azure Active Directory credentials used for accessing - your Azure Key Vault. Not required if using managed identity instead. - :paramtype access_credentials: - ~azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials - :keyword identity: An explicit managed identity to use for this encryption key. If not - specified and the access credentials property is null, the system-assigned managed identity is - used. On update to the resource, if the explicit identity is unspecified, it remains unchanged. - If "none" is specified, the value of this property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.key_name = key_name - self.key_version = key_version - self.vault_uri = vault_uri - self.access_credentials = access_credentials - self.identity = identity - - -class SearchServiceCounters(_serialization.Model): - """Represents service-level resource counters and quotas. - - All required parameters must be populated in order to send to server. - - :ivar alias_counter: Total number of aliases. Required. - :vartype alias_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar document_counter: Total number of documents across all indexes in the service. Required. - :vartype document_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar index_counter: Total number of indexes. Required. - :vartype index_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar indexer_counter: Total number of indexers. Required. - :vartype indexer_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar data_source_counter: Total number of data sources. Required. - :vartype data_source_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar storage_size_counter: Total size of used storage in bytes. Required. - :vartype storage_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar synonym_map_counter: Total number of synonym maps. Required. - :vartype synonym_map_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar skillset_counter: Total number of skillsets. Required. - :vartype skillset_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar vector_index_size_counter: Total memory consumption of all vector indexes within the - service, in bytes. Required. - :vartype vector_index_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - """ - - _validation = { - "alias_counter": {"required": True}, - "document_counter": {"required": True}, - "index_counter": {"required": True}, - "indexer_counter": {"required": True}, - "data_source_counter": {"required": True}, - "storage_size_counter": {"required": True}, - "synonym_map_counter": {"required": True}, - "skillset_counter": {"required": True}, - "vector_index_size_counter": {"required": True}, - } - - _attribute_map = { - "alias_counter": {"key": "aliasesCount", "type": "ResourceCounter"}, - "document_counter": {"key": "documentCount", "type": "ResourceCounter"}, - "index_counter": {"key": "indexesCount", "type": "ResourceCounter"}, - "indexer_counter": {"key": "indexersCount", "type": "ResourceCounter"}, - "data_source_counter": {"key": "dataSourcesCount", "type": "ResourceCounter"}, - "storage_size_counter": {"key": "storageSize", "type": "ResourceCounter"}, - "synonym_map_counter": {"key": "synonymMaps", "type": "ResourceCounter"}, - "skillset_counter": {"key": "skillsetCount", "type": "ResourceCounter"}, - "vector_index_size_counter": {"key": "vectorIndexSize", "type": "ResourceCounter"}, - } - - def __init__( - self, - *, - alias_counter: "_models.ResourceCounter", - document_counter: "_models.ResourceCounter", - index_counter: "_models.ResourceCounter", - indexer_counter: "_models.ResourceCounter", - data_source_counter: "_models.ResourceCounter", - storage_size_counter: "_models.ResourceCounter", - synonym_map_counter: "_models.ResourceCounter", - skillset_counter: "_models.ResourceCounter", - vector_index_size_counter: "_models.ResourceCounter", - **kwargs: Any - ) -> None: - """ - :keyword alias_counter: Total number of aliases. Required. - :paramtype alias_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword document_counter: Total number of documents across all indexes in the service. - Required. - :paramtype document_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword index_counter: Total number of indexes. Required. - :paramtype index_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword indexer_counter: Total number of indexers. Required. - :paramtype indexer_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword data_source_counter: Total number of data sources. Required. - :paramtype data_source_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword storage_size_counter: Total size of used storage in bytes. Required. - :paramtype storage_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword synonym_map_counter: Total number of synonym maps. Required. - :paramtype synonym_map_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword skillset_counter: Total number of skillsets. Required. - :paramtype skillset_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword vector_index_size_counter: Total memory consumption of all vector indexes within the - service, in bytes. Required. - :paramtype vector_index_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - """ - super().__init__(**kwargs) - self.alias_counter = alias_counter - self.document_counter = document_counter - self.index_counter = index_counter - self.indexer_counter = indexer_counter - self.data_source_counter = data_source_counter - self.storage_size_counter = storage_size_counter - self.synonym_map_counter = synonym_map_counter - self.skillset_counter = skillset_counter - self.vector_index_size_counter = vector_index_size_counter - - -class SearchServiceLimits(_serialization.Model): - """Represents various service level limits. - - :ivar max_fields_per_index: The maximum allowed fields per index. - :vartype max_fields_per_index: int - :ivar max_field_nesting_depth_per_index: The maximum depth which you can nest sub-fields in an - index, including the top-level complex field. For example, a/b/c has a nesting depth of 3. - :vartype max_field_nesting_depth_per_index: int - :ivar max_complex_collection_fields_per_index: The maximum number of fields of type - Collection(Edm.ComplexType) allowed in an index. - :vartype max_complex_collection_fields_per_index: int - :ivar max_complex_objects_in_collections_per_document: The maximum number of objects in complex - collections allowed per document. - :vartype max_complex_objects_in_collections_per_document: int - :ivar max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per index. - :vartype max_storage_per_index_in_bytes: int - :ivar max_cumulative_indexer_runtime_seconds: The maximum cumulative runtime in seconds allowed - for all indexers in the service over the current UTC period. - :vartype max_cumulative_indexer_runtime_seconds: int - """ - - _attribute_map = { - "max_fields_per_index": {"key": "maxFieldsPerIndex", "type": "int"}, - "max_field_nesting_depth_per_index": {"key": "maxFieldNestingDepthPerIndex", "type": "int"}, - "max_complex_collection_fields_per_index": {"key": "maxComplexCollectionFieldsPerIndex", "type": "int"}, - "max_complex_objects_in_collections_per_document": { - "key": "maxComplexObjectsInCollectionsPerDocument", - "type": "int", - }, - "max_storage_per_index_in_bytes": {"key": "maxStoragePerIndex", "type": "int"}, - "max_cumulative_indexer_runtime_seconds": {"key": "maxCumulativeIndexerRuntimeSeconds", "type": "int"}, - } - - def __init__( - self, - *, - max_fields_per_index: Optional[int] = None, - max_field_nesting_depth_per_index: Optional[int] = None, - max_complex_collection_fields_per_index: Optional[int] = None, - max_complex_objects_in_collections_per_document: Optional[int] = None, - max_storage_per_index_in_bytes: Optional[int] = None, - max_cumulative_indexer_runtime_seconds: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword max_fields_per_index: The maximum allowed fields per index. - :paramtype max_fields_per_index: int - :keyword max_field_nesting_depth_per_index: The maximum depth which you can nest sub-fields in - an index, including the top-level complex field. For example, a/b/c has a nesting depth of 3. - :paramtype max_field_nesting_depth_per_index: int - :keyword max_complex_collection_fields_per_index: The maximum number of fields of type - Collection(Edm.ComplexType) allowed in an index. - :paramtype max_complex_collection_fields_per_index: int - :keyword max_complex_objects_in_collections_per_document: The maximum number of objects in - complex collections allowed per document. - :paramtype max_complex_objects_in_collections_per_document: int - :keyword max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per - index. - :paramtype max_storage_per_index_in_bytes: int - :keyword max_cumulative_indexer_runtime_seconds: The maximum cumulative runtime in seconds - allowed for all indexers in the service over the current UTC period. - :paramtype max_cumulative_indexer_runtime_seconds: int - """ - super().__init__(**kwargs) - self.max_fields_per_index = max_fields_per_index - self.max_field_nesting_depth_per_index = max_field_nesting_depth_per_index - self.max_complex_collection_fields_per_index = max_complex_collection_fields_per_index - self.max_complex_objects_in_collections_per_document = max_complex_objects_in_collections_per_document - self.max_storage_per_index_in_bytes = max_storage_per_index_in_bytes - self.max_cumulative_indexer_runtime_seconds = max_cumulative_indexer_runtime_seconds - - -class SearchServiceStatistics(_serialization.Model): - """Response from a get service statistics request. If successful, it includes service level - counters, indexer runtime information, and limits. - - All required parameters must be populated in order to send to server. - - :ivar counters: Service level resource counters. Required. - :vartype counters: ~azure.search.documents.indexes.models.SearchServiceCounters - :ivar indexers_runtime: Service level indexers runtime information. Required. - :vartype indexers_runtime: ~azure.search.documents.indexes.models.ServiceIndexersRuntime - :ivar limits: Service level general limits. Required. - :vartype limits: ~azure.search.documents.indexes.models.SearchServiceLimits - """ - - _validation = { - "counters": {"required": True}, - "indexers_runtime": {"required": True}, - "limits": {"required": True}, - } - - _attribute_map = { - "counters": {"key": "counters", "type": "SearchServiceCounters"}, - "indexers_runtime": {"key": "indexersRuntime", "type": "ServiceIndexersRuntime"}, - "limits": {"key": "limits", "type": "SearchServiceLimits"}, - } - - def __init__( - self, - *, - counters: "_models.SearchServiceCounters", - indexers_runtime: "_models.ServiceIndexersRuntime", - limits: "_models.SearchServiceLimits", - **kwargs: Any - ) -> None: - """ - :keyword counters: Service level resource counters. Required. - :paramtype counters: ~azure.search.documents.indexes.models.SearchServiceCounters - :keyword indexers_runtime: Service level indexers runtime information. Required. - :paramtype indexers_runtime: ~azure.search.documents.indexes.models.ServiceIndexersRuntime - :keyword limits: Service level general limits. Required. - :paramtype limits: ~azure.search.documents.indexes.models.SearchServiceLimits - """ - super().__init__(**kwargs) - self.counters = counters - self.indexers_runtime = indexers_runtime - self.limits = limits - - -class SearchSuggester(_serialization.Model): - """Defines how the Suggest API should apply to a group of fields in the index. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the suggester. Required. - :vartype name: str - :ivar search_mode: A value indicating the capabilities of the suggester. Required. Default - value is "analyzingInfixMatching". - :vartype search_mode: str - :ivar source_fields: The list of field names to which the suggester applies. Each field must be - searchable. Required. - :vartype source_fields: list[str] - """ - - _validation = { - "name": {"required": True}, - "search_mode": {"required": True, "constant": True}, - "source_fields": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "search_mode": {"key": "searchMode", "type": "str"}, - "source_fields": {"key": "sourceFields", "type": "[str]"}, - } - - search_mode = "analyzingInfixMatching" - - def __init__(self, *, name: str, source_fields: list[str], **kwargs: Any) -> None: - """ - :keyword name: The name of the suggester. Required. - :paramtype name: str - :keyword source_fields: The list of field names to which the suggester applies. Each field must - be searchable. Required. - :paramtype source_fields: list[str] - """ - super().__init__(**kwargs) - self.name = name - self.source_fields = source_fields - - -class SemanticConfiguration(_serialization.Model): - """Defines a specific configuration to be used in the context of semantic capabilities. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the semantic configuration. Required. - :vartype name: str - :ivar prioritized_fields: Describes the title, content, and keyword fields to be used for - semantic ranking, captions, highlights, and answers. At least one of the three sub properties - (titleField, prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required. - :vartype prioritized_fields: ~azure.search.documents.indexes.models.SemanticPrioritizedFields - :ivar ranking_order: Specifies the score type to be used for the sort order of the search - results. Known values are: "BoostedRerankerScore" and "RerankerScore". - :vartype ranking_order: str or ~azure.search.documents.indexes.models.RankingOrder - :ivar flighting_opt_in: Determines which semantic or query rewrite models to use during model - flighting/upgrades. - :vartype flighting_opt_in: bool - """ - - _validation = { - "name": {"required": True}, - "prioritized_fields": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "prioritized_fields": {"key": "prioritizedFields", "type": "SemanticPrioritizedFields"}, - "ranking_order": {"key": "rankingOrder", "type": "str"}, - "flighting_opt_in": {"key": "flightingOptIn", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - prioritized_fields: "_models.SemanticPrioritizedFields", - ranking_order: Optional[Union[str, "_models.RankingOrder"]] = None, - flighting_opt_in: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the semantic configuration. Required. - :paramtype name: str - :keyword prioritized_fields: Describes the title, content, and keyword fields to be used for - semantic ranking, captions, highlights, and answers. At least one of the three sub properties - (titleField, prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required. - :paramtype prioritized_fields: ~azure.search.documents.indexes.models.SemanticPrioritizedFields - :keyword ranking_order: Specifies the score type to be used for the sort order of the search - results. Known values are: "BoostedRerankerScore" and "RerankerScore". - :paramtype ranking_order: str or ~azure.search.documents.indexes.models.RankingOrder - :keyword flighting_opt_in: Determines which semantic or query rewrite models to use during - model flighting/upgrades. - :paramtype flighting_opt_in: bool - """ - super().__init__(**kwargs) - self.name = name - self.prioritized_fields = prioritized_fields - self.ranking_order = ranking_order - self.flighting_opt_in = flighting_opt_in - - -class SemanticField(_serialization.Model): - """A field that is used as part of the semantic configuration. - - All required parameters must be populated in order to send to server. - - :ivar field_name: Required. - :vartype field_name: str - """ - - _validation = { - "field_name": {"required": True}, - } - - _attribute_map = { - "field_name": {"key": "fieldName", "type": "str"}, - } - - def __init__(self, *, field_name: str, **kwargs: Any) -> None: - """ - :keyword field_name: Required. - :paramtype field_name: str - """ - super().__init__(**kwargs) - self.field_name = field_name - - -class SemanticPrioritizedFields(_serialization.Model): - """Describes the title, content, and keywords fields to be used for semantic ranking, captions, - highlights, and answers. - - :ivar title_field: Defines the title field to be used for semantic ranking, captions, - highlights, and answers. If you don't have a title field in your index, leave this blank. - :vartype title_field: ~azure.search.documents.indexes.models.SemanticField - :ivar content_fields: Defines the content fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain text in - natural language form. The order of the fields in the array represents their priority. Fields - with lower priority may get truncated if the content is long. - :vartype content_fields: list[~azure.search.documents.indexes.models.SemanticField] - :ivar keywords_fields: Defines the keyword fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain a list of - keywords. The order of the fields in the array represents their priority. Fields with lower - priority may get truncated if the content is long. - :vartype keywords_fields: list[~azure.search.documents.indexes.models.SemanticField] - """ - - _attribute_map = { - "title_field": {"key": "titleField", "type": "SemanticField"}, - "content_fields": {"key": "prioritizedContentFields", "type": "[SemanticField]"}, - "keywords_fields": {"key": "prioritizedKeywordsFields", "type": "[SemanticField]"}, - } - - def __init__( - self, - *, - title_field: Optional["_models.SemanticField"] = None, - content_fields: Optional[list["_models.SemanticField"]] = None, - keywords_fields: Optional[list["_models.SemanticField"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword title_field: Defines the title field to be used for semantic ranking, captions, - highlights, and answers. If you don't have a title field in your index, leave this blank. - :paramtype title_field: ~azure.search.documents.indexes.models.SemanticField - :keyword content_fields: Defines the content fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain text in - natural language form. The order of the fields in the array represents their priority. Fields - with lower priority may get truncated if the content is long. - :paramtype content_fields: list[~azure.search.documents.indexes.models.SemanticField] - :keyword keywords_fields: Defines the keyword fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain a list of - keywords. The order of the fields in the array represents their priority. Fields with lower - priority may get truncated if the content is long. - :paramtype keywords_fields: list[~azure.search.documents.indexes.models.SemanticField] - """ - super().__init__(**kwargs) - self.title_field = title_field - self.content_fields = content_fields - self.keywords_fields = keywords_fields - - -class SemanticSearch(_serialization.Model): - """Defines parameters for a search index that influence semantic capabilities. - - :ivar default_configuration_name: Allows you to set the name of a default semantic - configuration in your index, making it optional to pass it on as a query parameter every time. - :vartype default_configuration_name: str - :ivar configurations: The semantic configurations for the index. - :vartype configurations: list[~azure.search.documents.indexes.models.SemanticConfiguration] - """ - - _attribute_map = { - "default_configuration_name": {"key": "defaultConfiguration", "type": "str"}, - "configurations": {"key": "configurations", "type": "[SemanticConfiguration]"}, - } - - def __init__( - self, - *, - default_configuration_name: Optional[str] = None, - configurations: Optional[list["_models.SemanticConfiguration"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword default_configuration_name: Allows you to set the name of a default semantic - configuration in your index, making it optional to pass it on as a query parameter every time. - :paramtype default_configuration_name: str - :keyword configurations: The semantic configurations for the index. - :paramtype configurations: list[~azure.search.documents.indexes.models.SemanticConfiguration] - """ - super().__init__(**kwargs) - self.default_configuration_name = default_configuration_name - self.configurations = configurations - - -class SentimentSkill(SearchIndexerSkill): - """This skill is deprecated. Use the V3.SentimentSkill instead. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", "ru", - "es", "sv", and "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.SentimentSkillLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.SentimentSkillLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", - "ru", "es", "sv", and "tr". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.SentimentSkillLanguage - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.SentimentSkill" - self.default_language_code = default_language_code - - -class SentimentSkillV3(SearchIndexerSkill): - """Using the Text Analytics API, evaluates unstructured text and for each record, provides - sentiment labels (such as "negative", "neutral" and "positive") based on the highest confidence - score found by the service at a sentence and document-level. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar include_opinion_mining: If set to true, the skill output will include information from - Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated - assessment (adjective) in the text. Default is false. - :vartype include_opinion_mining: bool - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_opinion_mining": {"key": "includeOpinionMining", "type": "bool"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[str] = None, - include_opinion_mining: bool = False, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword include_opinion_mining: If set to true, the skill output will include information from - Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated - assessment (adjective) in the text. Default is false. - :paramtype include_opinion_mining: bool - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.V3.SentimentSkill" - self.default_language_code = default_language_code - self.include_opinion_mining = include_opinion_mining - self.model_version = model_version - - -class ServiceIndexersRuntime(_serialization.Model): - """Represents service level indexers runtime information. - - All required parameters must be populated in order to send to server. - - :ivar used_seconds: Cumulative runtime of all indexers in the service from the beginningTime to - endingTime, in seconds. Required. - :vartype used_seconds: int - :ivar remaining_seconds: Cumulative runtime remaining for all indexers in the service from the - beginningTime to endingTime, in seconds. - :vartype remaining_seconds: int - :ivar beginning_time: Beginning UTC time of the 24-hour period considered for indexer runtime - usage (inclusive). Required. - :vartype beginning_time: ~datetime.datetime - :ivar ending_time: End UTC time of the 24-hour period considered for indexer runtime usage - (inclusive). Required. - :vartype ending_time: ~datetime.datetime - """ - - _validation = { - "used_seconds": {"required": True}, - "beginning_time": {"required": True}, - "ending_time": {"required": True}, - } - - _attribute_map = { - "used_seconds": {"key": "usedSeconds", "type": "int"}, - "remaining_seconds": {"key": "remainingSeconds", "type": "int"}, - "beginning_time": {"key": "beginningTime", "type": "iso-8601"}, - "ending_time": {"key": "endingTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - used_seconds: int, - beginning_time: datetime.datetime, - ending_time: datetime.datetime, - remaining_seconds: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword used_seconds: Cumulative runtime of all indexers in the service from the beginningTime - to endingTime, in seconds. Required. - :paramtype used_seconds: int - :keyword remaining_seconds: Cumulative runtime remaining for all indexers in the service from - the beginningTime to endingTime, in seconds. - :paramtype remaining_seconds: int - :keyword beginning_time: Beginning UTC time of the 24-hour period considered for indexer - runtime usage (inclusive). Required. - :paramtype beginning_time: ~datetime.datetime - :keyword ending_time: End UTC time of the 24-hour period considered for indexer runtime usage - (inclusive). Required. - :paramtype ending_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.used_seconds = used_seconds - self.remaining_seconds = remaining_seconds - self.beginning_time = beginning_time - self.ending_time = ending_time - - -class ShaperSkill(SearchIndexerSkill): - """A skill for reshaping the outputs. It creates a complex type to support composite fields (also - known as multipart fields). - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.ShaperSkill" - - -class ShingleTokenFilter(TokenFilter): - """Creates combinations of tokens as a single token. This token filter is implemented using Apache - Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_shingle_size: The maximum shingle size. Default and minimum value is 2. - :vartype max_shingle_size: int - :ivar min_shingle_size: The minimum shingle size. Default and minimum value is 2. Must be less - than the value of maxShingleSize. - :vartype min_shingle_size: int - :ivar output_unigrams: A value indicating whether the output stream will contain the input - tokens (unigrams) as well as shingles. Default is true. - :vartype output_unigrams: bool - :ivar output_unigrams_if_no_shingles: A value indicating whether to output unigrams for those - times when no shingles are available. This property takes precedence when outputUnigrams is set - to false. Default is false. - :vartype output_unigrams_if_no_shingles: bool - :ivar token_separator: The string to use when joining adjacent tokens to form a shingle. - Default is a single space (" "). - :vartype token_separator: str - :ivar filter_token: The string to insert for each position at which there is no token. Default - is an underscore ("_"). - :vartype filter_token: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_shingle_size": {"minimum": 2}, - "min_shingle_size": {"minimum": 2}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_shingle_size": {"key": "maxShingleSize", "type": "int"}, - "min_shingle_size": {"key": "minShingleSize", "type": "int"}, - "output_unigrams": {"key": "outputUnigrams", "type": "bool"}, - "output_unigrams_if_no_shingles": {"key": "outputUnigramsIfNoShingles", "type": "bool"}, - "token_separator": {"key": "tokenSeparator", "type": "str"}, - "filter_token": {"key": "filterToken", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - max_shingle_size: int = 2, - min_shingle_size: int = 2, - output_unigrams: bool = True, - output_unigrams_if_no_shingles: bool = False, - token_separator: str = " ", - filter_token: str = "_", - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword max_shingle_size: The maximum shingle size. Default and minimum value is 2. - :paramtype max_shingle_size: int - :keyword min_shingle_size: The minimum shingle size. Default and minimum value is 2. Must be - less than the value of maxShingleSize. - :paramtype min_shingle_size: int - :keyword output_unigrams: A value indicating whether the output stream will contain the input - tokens (unigrams) as well as shingles. Default is true. - :paramtype output_unigrams: bool - :keyword output_unigrams_if_no_shingles: A value indicating whether to output unigrams for - those times when no shingles are available. This property takes precedence when outputUnigrams - is set to false. Default is false. - :paramtype output_unigrams_if_no_shingles: bool - :keyword token_separator: The string to use when joining adjacent tokens to form a shingle. - Default is a single space (" "). - :paramtype token_separator: str - :keyword filter_token: The string to insert for each position at which there is no token. - Default is an underscore ("_"). - :paramtype filter_token: str - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ShingleTokenFilter" - self.max_shingle_size = max_shingle_size - self.min_shingle_size = min_shingle_size - self.output_unigrams = output_unigrams - self.output_unigrams_if_no_shingles = output_unigrams_if_no_shingles - self.token_separator = token_separator - self.filter_token = filter_token - - -class SkillNames(_serialization.Model): - """SkillNames. - - :ivar skill_names: the names of skills to be reset. - :vartype skill_names: list[str] - """ - - _attribute_map = { - "skill_names": {"key": "skillNames", "type": "[str]"}, - } - - def __init__(self, *, skill_names: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword skill_names: the names of skills to be reset. - :paramtype skill_names: list[str] - """ - super().__init__(**kwargs) - self.skill_names = skill_names - - -class SnowballTokenFilter(TokenFilter): - """A filter that stems words using a Snowball-generated stemmer. This token filter is implemented - using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar language: The language to use. Required. Known values are: "armenian", "basque", - "catalan", "danish", "dutch", "english", "finnish", "french", "german", "german2", "hungarian", - "italian", "kp", "lovins", "norwegian", "porter", "portuguese", "romanian", "russian", - "spanish", "swedish", and "turkish". - :vartype language: str or ~azure.search.documents.indexes.models.SnowballTokenFilterLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "language": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__( - self, *, name: str, language: Union[str, "_models.SnowballTokenFilterLanguage"], **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword language: The language to use. Required. Known values are: "armenian", "basque", - "catalan", "danish", "dutch", "english", "finnish", "french", "german", "german2", "hungarian", - "italian", "kp", "lovins", "norwegian", "porter", "portuguese", "romanian", "russian", - "spanish", "swedish", and "turkish". - :paramtype language: str or ~azure.search.documents.indexes.models.SnowballTokenFilterLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SnowballTokenFilter" - self.language = language - - -class SoftDeleteColumnDeletionDetectionPolicy(DataDeletionDetectionPolicy): - """Defines a data deletion detection policy that implements a soft-deletion strategy. It - determines whether an item should be deleted based on the value of a designated 'soft delete' - column. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. - Required. - :vartype odata_type: str - :ivar soft_delete_column_name: The name of the column to use for soft-deletion detection. - :vartype soft_delete_column_name: str - :ivar soft_delete_marker_value: The marker value that identifies an item as deleted. - :vartype soft_delete_marker_value: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "soft_delete_column_name": {"key": "softDeleteColumnName", "type": "str"}, - "soft_delete_marker_value": {"key": "softDeleteMarkerValue", "type": "str"}, - } - - def __init__( - self, - *, - soft_delete_column_name: Optional[str] = None, - soft_delete_marker_value: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword soft_delete_column_name: The name of the column to use for soft-deletion detection. - :paramtype soft_delete_column_name: str - :keyword soft_delete_marker_value: The marker value that identifies an item as deleted. - :paramtype soft_delete_marker_value: str - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy" - self.soft_delete_column_name = soft_delete_column_name - self.soft_delete_marker_value = soft_delete_marker_value - - -class SplitSkill(SearchIndexerSkill): - """A skill to split a string into chunks of text. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "am", "bs", "cs", "da", "de", "en", "es", "et", "fi", "fr", "he", "hi", "hr", - "hu", "id", "is", "it", "ja", "ko", "lv", "nb", "nl", "pl", "pt", "pt-br", "ru", "sk", "sl", - "sr", "sv", "tr", "ur", "zh", and "is". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.SplitSkillLanguage - :ivar text_split_mode: A value indicating which split mode to perform. Known values are: - "pages" and "sentences". - :vartype text_split_mode: str or ~azure.search.documents.indexes.models.TextSplitMode - :ivar maximum_page_length: The desired maximum page length. Default is 10000. - :vartype maximum_page_length: int - :ivar page_overlap_length: Only applicable when textSplitMode is set to 'pages'. If specified, - n+1th chunk will start with this number of characters/tokens from the end of the nth chunk. - :vartype page_overlap_length: int - :ivar maximum_pages_to_take: Only applicable when textSplitMode is set to 'pages'. If - specified, the SplitSkill will discontinue splitting after processing the first - 'maximumPagesToTake' pages, in order to improve performance when only a few initial pages are - needed from each document. - :vartype maximum_pages_to_take: int - :ivar unit: Only applies if textSplitMode is set to pages. There are two possible values. The - choice of the values will decide the length (maximumPageLength and pageOverlapLength) - measurement. The default is 'characters', which means the length will be measured by character. - Known values are: "characters" and "azureOpenAITokens". - :vartype unit: str or ~azure.search.documents.indexes.models.SplitSkillUnit - :ivar parameters: Only applies if the unit is set to azureOpenAITokens. If specified, the - splitSkill will use these parameters when performing the tokenization. The parameters are a - valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. - :vartype parameters: ~azure.search.documents.indexes.models.AzureOpenAITokenizerParameters - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "text_split_mode": {"key": "textSplitMode", "type": "str"}, - "maximum_page_length": {"key": "maximumPageLength", "type": "int"}, - "page_overlap_length": {"key": "pageOverlapLength", "type": "int"}, - "maximum_pages_to_take": {"key": "maximumPagesToTake", "type": "int"}, - "unit": {"key": "unit", "type": "str"}, - "parameters": {"key": "azureOpenAITokenizerParameters", "type": "AzureOpenAITokenizerParameters"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.SplitSkillLanguage"]] = None, - text_split_mode: Optional[Union[str, "_models.TextSplitMode"]] = None, - maximum_page_length: Optional[int] = None, - page_overlap_length: Optional[int] = None, - maximum_pages_to_take: Optional[int] = None, - unit: Optional[Union[str, "_models.SplitSkillUnit"]] = None, - parameters: Optional["_models.AzureOpenAITokenizerParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "am", "bs", "cs", "da", "de", "en", "es", "et", "fi", "fr", "he", - "hi", "hr", "hu", "id", "is", "it", "ja", "ko", "lv", "nb", "nl", "pl", "pt", "pt-br", "ru", - "sk", "sl", "sr", "sv", "tr", "ur", "zh", and "is". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.SplitSkillLanguage - :keyword text_split_mode: A value indicating which split mode to perform. Known values are: - "pages" and "sentences". - :paramtype text_split_mode: str or ~azure.search.documents.indexes.models.TextSplitMode - :keyword maximum_page_length: The desired maximum page length. Default is 10000. - :paramtype maximum_page_length: int - :keyword page_overlap_length: Only applicable when textSplitMode is set to 'pages'. If - specified, n+1th chunk will start with this number of characters/tokens from the end of the nth - chunk. - :paramtype page_overlap_length: int - :keyword maximum_pages_to_take: Only applicable when textSplitMode is set to 'pages'. If - specified, the SplitSkill will discontinue splitting after processing the first - 'maximumPagesToTake' pages, in order to improve performance when only a few initial pages are - needed from each document. - :paramtype maximum_pages_to_take: int - :keyword unit: Only applies if textSplitMode is set to pages. There are two possible values. - The choice of the values will decide the length (maximumPageLength and pageOverlapLength) - measurement. The default is 'characters', which means the length will be measured by character. - Known values are: "characters" and "azureOpenAITokens". - :paramtype unit: str or ~azure.search.documents.indexes.models.SplitSkillUnit - :keyword parameters: Only applies if the unit is set to azureOpenAITokens. If specified, the - splitSkill will use these parameters when performing the tokenization. The parameters are a - valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. - :paramtype parameters: ~azure.search.documents.indexes.models.AzureOpenAITokenizerParameters - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.SplitSkill" - self.default_language_code = default_language_code - self.text_split_mode = text_split_mode - self.maximum_page_length = maximum_page_length - self.page_overlap_length = page_overlap_length - self.maximum_pages_to_take = maximum_pages_to_take - self.unit = unit - self.parameters = parameters - - -class SqlIntegratedChangeTrackingPolicy(DataChangeDetectionPolicy): - """Defines a data change detection policy that captures changes using the Integrated Change - Tracking feature of Azure SQL Database. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy" - - -class StemmerOverrideTokenFilter(TokenFilter): - """Provides the ability to override other stemming filters with custom dictionary-based stemming. - Any dictionary-stemmed terms will be marked as keywords so that they will not be stemmed with - stemmers down the chain. Must be placed before any stemming filters. This token filter is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar rules: A list of stemming rules in the following format: "word => stem", for example: - "ran => run". Required. - :vartype rules: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "rules": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "rules": {"key": "rules", "type": "[str]"}, - } - - def __init__(self, *, name: str, rules: list[str], **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword rules: A list of stemming rules in the following format: "word => stem", for example: - "ran => run". Required. - :paramtype rules: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StemmerOverrideTokenFilter" - self.rules = rules - - -class StemmerTokenFilter(TokenFilter): - """Language specific stemming filter. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar language: The language to use. Required. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "dutchKp", - "english", "lightEnglish", "minimalEnglish", "possessiveEnglish", "porter2", "lovins", - "finnish", "lightFinnish", "french", "lightFrench", "minimalFrench", "galician", - "minimalGalician", "german", "german2", "lightGerman", "minimalGerman", "greek", "hindi", - "hungarian", "lightHungarian", "indonesian", "irish", "italian", "lightItalian", "sorani", - "latvian", "norwegian", "lightNorwegian", "minimalNorwegian", "lightNynorsk", "minimalNynorsk", - "portuguese", "lightPortuguese", "minimalPortuguese", "portugueseRslp", "romanian", "russian", - "lightRussian", "spanish", "lightSpanish", "swedish", "lightSwedish", and "turkish". - :vartype language: str or ~azure.search.documents.indexes.models.StemmerTokenFilterLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "language": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__(self, *, name: str, language: Union[str, "_models.StemmerTokenFilterLanguage"], **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword language: The language to use. Required. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "dutchKp", - "english", "lightEnglish", "minimalEnglish", "possessiveEnglish", "porter2", "lovins", - "finnish", "lightFinnish", "french", "lightFrench", "minimalFrench", "galician", - "minimalGalician", "german", "german2", "lightGerman", "minimalGerman", "greek", "hindi", - "hungarian", "lightHungarian", "indonesian", "irish", "italian", "lightItalian", "sorani", - "latvian", "norwegian", "lightNorwegian", "minimalNorwegian", "lightNynorsk", "minimalNynorsk", - "portuguese", "lightPortuguese", "minimalPortuguese", "portugueseRslp", "romanian", "russian", - "lightRussian", "spanish", "lightSpanish", "swedish", "lightSwedish", and "turkish". - :paramtype language: str or ~azure.search.documents.indexes.models.StemmerTokenFilterLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StemmerTokenFilter" - self.language = language - - -class StopAnalyzer(LexicalAnalyzer): - """Divides text at non-letters; Applies the lowercase and stopword token filters. This analyzer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__(self, *, name: str, stopwords: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword stopwords: A list of stopwords. - :paramtype stopwords: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StopAnalyzer" - self.stopwords = stopwords - - -class StopwordsTokenFilter(TokenFilter): - """Removes stop words from a token stream. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar stopwords: The list of stopwords. This property and the stopwords list property cannot - both be set. - :vartype stopwords: list[str] - :ivar stopwords_list: A predefined list of stopwords to use. This property and the stopwords - property cannot both be set. Default is English. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", - "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", - "irish", "italian", "latvian", "norwegian", "persian", "portuguese", "romanian", "russian", - "sorani", "spanish", "swedish", "thai", and "turkish". - :vartype stopwords_list: str or ~azure.search.documents.indexes.models.StopwordsList - :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted - to lower case first. Default is false. - :vartype ignore_case: bool - :ivar remove_trailing_stop_words: A value indicating whether to ignore the last search term if - it's a stop word. Default is true. - :vartype remove_trailing_stop_words: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - "stopwords_list": {"key": "stopwordsList", "type": "str"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - "remove_trailing_stop_words": {"key": "removeTrailing", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - stopwords: Optional[list[str]] = None, - stopwords_list: Optional[Union[str, "_models.StopwordsList"]] = None, - ignore_case: bool = False, - remove_trailing_stop_words: bool = True, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword stopwords: The list of stopwords. This property and the stopwords list property cannot - both be set. - :paramtype stopwords: list[str] - :keyword stopwords_list: A predefined list of stopwords to use. This property and the stopwords - property cannot both be set. Default is English. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", - "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", - "irish", "italian", "latvian", "norwegian", "persian", "portuguese", "romanian", "russian", - "sorani", "spanish", "swedish", "thai", and "turkish". - :paramtype stopwords_list: str or ~azure.search.documents.indexes.models.StopwordsList - :keyword ignore_case: A value indicating whether to ignore case. If true, all words are - converted to lower case first. Default is false. - :paramtype ignore_case: bool - :keyword remove_trailing_stop_words: A value indicating whether to ignore the last search term - if it's a stop word. Default is true. - :paramtype remove_trailing_stop_words: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StopwordsTokenFilter" - self.stopwords = stopwords - self.stopwords_list = stopwords_list - self.ignore_case = ignore_case - self.remove_trailing_stop_words = remove_trailing_stop_words - - -class SynchronizationState(_serialization.Model): - """Represents the current state of an ongoing synchronization that spans multiple indexer runs. - - All required parameters must be populated in order to send to server. - - :ivar start_time: The start time of the current synchronization. Required. - :vartype start_time: ~datetime.datetime - :ivar items_updates_processed: The number of item updates successfully processed in the current - synchronization. Required. - :vartype items_updates_processed: int - :ivar items_updates_failed: The number of item updates that failed in the current - synchronization. Required. - :vartype items_updates_failed: int - :ivar items_skipped: The number of items skipped in the current synchronization. Required. - :vartype items_skipped: int - """ - - _validation = { - "start_time": {"required": True}, - "items_updates_processed": {"required": True}, - "items_updates_failed": {"required": True}, - "items_skipped": {"required": True}, - } - - _attribute_map = { - "start_time": {"key": "startTime", "type": "iso-8601"}, - "items_updates_processed": {"key": "itemsUpdatesProcessed", "type": "int"}, - "items_updates_failed": {"key": "itemsUpdatesFailed", "type": "int"}, - "items_skipped": {"key": "itemsSkipped", "type": "int"}, - } - - def __init__( - self, - *, - start_time: datetime.datetime, - items_updates_processed: int, - items_updates_failed: int, - items_skipped: int, - **kwargs: Any - ) -> None: - """ - :keyword start_time: The start time of the current synchronization. Required. - :paramtype start_time: ~datetime.datetime - :keyword items_updates_processed: The number of item updates successfully processed in the - current synchronization. Required. - :paramtype items_updates_processed: int - :keyword items_updates_failed: The number of item updates that failed in the current - synchronization. Required. - :paramtype items_updates_failed: int - :keyword items_skipped: The number of items skipped in the current synchronization. Required. - :paramtype items_skipped: int - """ - super().__init__(**kwargs) - self.start_time = start_time - self.items_updates_processed = items_updates_processed - self.items_updates_failed = items_updates_failed - self.items_skipped = items_skipped - - -class SynonymMap(_serialization.Model): - """Represents a synonym map definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the synonym map. Required. - :vartype name: str - :ivar format: The format of the synonym map. Only the 'solr' format is currently supported. - Required. Default value is "solr". - :vartype format: str - :ivar synonyms: A series of synonym rules in the specified synonym map format. The rules must - be separated by newlines. Required. - :vartype synonyms: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar e_tag: The ETag of the synonym map. - :vartype e_tag: str - """ - - _validation = { - "name": {"required": True}, - "format": {"required": True, "constant": True}, - "synonyms": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "format": {"key": "format", "type": "str"}, - "synonyms": {"key": "synonyms", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - } - - format = "solr" - - def __init__( - self, - *, - name: str, - synonyms: str, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - e_tag: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the synonym map. Required. - :paramtype name: str - :keyword synonyms: A series of synonym rules in the specified synonym map format. The rules - must be separated by newlines. Required. - :paramtype synonyms: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword e_tag: The ETag of the synonym map. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.name = name - self.synonyms = synonyms - self.encryption_key = encryption_key - self.e_tag = e_tag - - -class SynonymTokenFilter(TokenFilter): - """Matches single or multi-word synonyms in a token stream. This token filter is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar synonyms: A list of synonyms in following one of two formats: 1. incredible, - unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced - with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma - separated list of equivalent words. Set the expand option to change how this list is - interpreted. Required. - :vartype synonyms: list[str] - :ivar ignore_case: A value indicating whether to case-fold input for matching. Default is - false. - :vartype ignore_case: bool - :ivar expand: A value indicating whether all words in the list of synonyms (if => notation is - not used) will map to one another. If true, all words in the list of synonyms (if => notation - is not used) will map to one another. The following list: incredible, unbelievable, fabulous, - amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, - unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, - fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => - incredible. Default is true. - :vartype expand: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "synonyms": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "synonyms": {"key": "synonyms", "type": "[str]"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - "expand": {"key": "expand", "type": "bool"}, - } - - def __init__( - self, *, name: str, synonyms: list[str], ignore_case: bool = False, expand: bool = True, **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword synonyms: A list of synonyms in following one of two formats: 1. incredible, - unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced - with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma - separated list of equivalent words. Set the expand option to change how this list is - interpreted. Required. - :paramtype synonyms: list[str] - :keyword ignore_case: A value indicating whether to case-fold input for matching. Default is - false. - :paramtype ignore_case: bool - :keyword expand: A value indicating whether all words in the list of synonyms (if => notation - is not used) will map to one another. If true, all words in the list of synonyms (if => - notation is not used) will map to one another. The following list: incredible, unbelievable, - fabulous, amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, - unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, - fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => - incredible. Default is true. - :paramtype expand: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SynonymTokenFilter" - self.synonyms = synonyms - self.ignore_case = ignore_case - self.expand = expand - - -class TagScoringFunction(ScoringFunction): - """Defines a function that boosts scores of documents with string values matching a given list of - tags. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the tag scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.TagScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "tag", "type": "TagScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.TagScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the tag scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.TagScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "tag" - self.parameters = parameters - - -class TagScoringParameters(_serialization.Model): - """Provides parameter values to a tag scoring function. - - All required parameters must be populated in order to send to server. - - :ivar tags_parameter: The name of the parameter passed in search queries to specify the list of - tags to compare against the target field. Required. - :vartype tags_parameter: str - """ - - _validation = { - "tags_parameter": {"required": True}, - } - - _attribute_map = { - "tags_parameter": {"key": "tagsParameter", "type": "str"}, - } - - def __init__(self, *, tags_parameter: str, **kwargs: Any) -> None: - """ - :keyword tags_parameter: The name of the parameter passed in search queries to specify the list - of tags to compare against the target field. Required. - :paramtype tags_parameter: str - """ - super().__init__(**kwargs) - self.tags_parameter = tags_parameter - - -class TextTranslationSkill(SearchIndexerSkill): - """A skill to translate text from one language to another. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_to_language_code: The language code to translate documents into for documents - that don't specify the to language explicitly. Required. Known values are: "af", "ar", "bn", - "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", - "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :vartype default_to_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :ivar default_from_language_code: The language code to translate documents from for documents - that don't specify the from language explicitly. Known values are: "af", "ar", "bn", "bs", - "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", "fi", - "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :vartype default_from_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :ivar suggested_from: The language code to translate documents from when neither the - fromLanguageCode input nor the defaultFromLanguageCode parameter are provided, and the - automatic language detection is unsuccessful. Default is ``en``. Known values are: "af", "ar", - "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", - "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", - "tlh", "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", - "pt-br", "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", - "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and - "is". - :vartype suggested_from: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "default_to_language_code": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_to_language_code": {"key": "defaultToLanguageCode", "type": "str"}, - "default_from_language_code": {"key": "defaultFromLanguageCode", "type": "str"}, - "suggested_from": {"key": "suggestedFrom", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - default_to_language_code: Union[str, "_models.TextTranslationSkillLanguage"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_from_language_code: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, - suggested_from: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_to_language_code: The language code to translate documents into for documents - that don't specify the to language explicitly. Required. Known values are: "af", "ar", "bn", - "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", - "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :paramtype default_to_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :keyword default_from_language_code: The language code to translate documents from for - documents that don't specify the from language explicitly. Known values are: "af", "ar", "bn", - "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", - "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :paramtype default_from_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :keyword suggested_from: The language code to translate documents from when neither the - fromLanguageCode input nor the defaultFromLanguageCode parameter are provided, and the - automatic language detection is unsuccessful. Default is ``en``. Known values are: "af", "ar", - "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", - "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", - "tlh", "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", - "pt-br", "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", - "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and - "is". - :paramtype suggested_from: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.TranslationSkill" - self.default_to_language_code = default_to_language_code - self.default_from_language_code = default_from_language_code - self.suggested_from = suggested_from - - -class TextWeights(_serialization.Model): - """Defines weights on index fields for which matches should boost scoring in search queries. - - All required parameters must be populated in order to send to server. - - :ivar weights: The dictionary of per-field weights to boost document scoring. The keys are - field names and the values are the weights for each field. Required. - :vartype weights: dict[str, float] - """ - - _validation = { - "weights": {"required": True}, - } - - _attribute_map = { - "weights": {"key": "weights", "type": "{float}"}, - } - - def __init__(self, *, weights: dict[str, float], **kwargs: Any) -> None: - """ - :keyword weights: The dictionary of per-field weights to boost document scoring. The keys are - field names and the values are the weights for each field. Required. - :paramtype weights: dict[str, float] - """ - super().__init__(**kwargs) - self.weights = weights - - -class TruncateTokenFilter(TokenFilter): - """Truncates the terms to a specific length. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar length: The length at which terms will be truncated. Default and maximum is 300. - :vartype length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "length": {"key": "length", "type": "int"}, - } - - def __init__(self, *, name: str, length: int = 300, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword length: The length at which terms will be truncated. Default and maximum is 300. - :paramtype length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.TruncateTokenFilter" - self.length = length - - -class UaxUrlEmailTokenizer(LexicalTokenizer): - """Tokenizes urls and emails as one token. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer" - self.max_token_length = max_token_length - - -class UniqueTokenFilter(TokenFilter): - """Filters out tokens with same text as the previous token. This token filter is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar only_on_same_position: A value indicating whether to remove duplicates only at the same - position. Default is false. - :vartype only_on_same_position: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "only_on_same_position": {"key": "onlyOnSamePosition", "type": "bool"}, - } - - def __init__(self, *, name: str, only_on_same_position: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword only_on_same_position: A value indicating whether to remove duplicates only at the - same position. Default is false. - :paramtype only_on_same_position: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.UniqueTokenFilter" - self.only_on_same_position = only_on_same_position - - -class VectorSearch(_serialization.Model): - """Contains configuration options related to vector search. - - :ivar profiles: Defines combinations of configurations to use with vector search. - :vartype profiles: list[~azure.search.documents.indexes.models.VectorSearchProfile] - :ivar algorithms: Contains configuration options specific to the algorithm used during indexing - or querying. - :vartype algorithms: - list[~azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration] - :ivar vectorizers: Contains configuration options on how to vectorize text vector queries. - :vartype vectorizers: list[~azure.search.documents.indexes.models.VectorSearchVectorizer] - :ivar compressions: Contains configuration options specific to the compression method used - during indexing or querying. - :vartype compressions: list[~azure.search.documents.indexes.models.VectorSearchCompression] - """ - - _attribute_map = { - "profiles": {"key": "profiles", "type": "[VectorSearchProfile]"}, - "algorithms": {"key": "algorithms", "type": "[VectorSearchAlgorithmConfiguration]"}, - "vectorizers": {"key": "vectorizers", "type": "[VectorSearchVectorizer]"}, - "compressions": {"key": "compressions", "type": "[VectorSearchCompression]"}, - } - - def __init__( - self, - *, - profiles: Optional[list["_models.VectorSearchProfile"]] = None, - algorithms: Optional[list["_models.VectorSearchAlgorithmConfiguration"]] = None, - vectorizers: Optional[list["_models.VectorSearchVectorizer"]] = None, - compressions: Optional[list["_models.VectorSearchCompression"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword profiles: Defines combinations of configurations to use with vector search. - :paramtype profiles: list[~azure.search.documents.indexes.models.VectorSearchProfile] - :keyword algorithms: Contains configuration options specific to the algorithm used during - indexing or querying. - :paramtype algorithms: - list[~azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration] - :keyword vectorizers: Contains configuration options on how to vectorize text vector queries. - :paramtype vectorizers: list[~azure.search.documents.indexes.models.VectorSearchVectorizer] - :keyword compressions: Contains configuration options specific to the compression method used - during indexing or querying. - :paramtype compressions: list[~azure.search.documents.indexes.models.VectorSearchCompression] - """ - super().__init__(**kwargs) - self.profiles = profiles - self.algorithms = algorithms - self.vectorizers = vectorizers - self.compressions = compressions - - -class VectorSearchProfile(_serialization.Model): - """Defines a combination of configurations to use with vector search. - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular vector search profile. Required. - :vartype name: str - :ivar algorithm_configuration_name: The name of the vector search algorithm configuration that - specifies the algorithm and optional parameters. Required. - :vartype algorithm_configuration_name: str - :ivar vectorizer_name: The name of the vectorization being configured for use with vector - search. - :vartype vectorizer_name: str - :ivar compression_name: The name of the compression method configuration that specifies the - compression method and optional parameters. - :vartype compression_name: str - """ - - _validation = { - "name": {"required": True}, - "algorithm_configuration_name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "algorithm_configuration_name": {"key": "algorithm", "type": "str"}, - "vectorizer_name": {"key": "vectorizer", "type": "str"}, - "compression_name": {"key": "compression", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - algorithm_configuration_name: str, - vectorizer_name: Optional[str] = None, - compression_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name to associate with this particular vector search profile. Required. - :paramtype name: str - :keyword algorithm_configuration_name: The name of the vector search algorithm configuration - that specifies the algorithm and optional parameters. Required. - :paramtype algorithm_configuration_name: str - :keyword vectorizer_name: The name of the vectorization being configured for use with vector - search. - :paramtype vectorizer_name: str - :keyword compression_name: The name of the compression method configuration that specifies the - compression method and optional parameters. - :paramtype compression_name: str - """ - super().__init__(**kwargs) - self.name = name - self.algorithm_configuration_name = algorithm_configuration_name - self.vectorizer_name = vectorizer_name - self.compression_name = compression_name - - -class VisionVectorizeSkill(SearchIndexerSkill): - """Allows you to generate a vector embedding for a given image or text input using the Azure AI - Services Vision Vectorize API. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "model_version": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - model_version: str, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Vision.VectorizeSkill" - self.model_version = model_version - - -class WebApiVectorizer(VectorSearchVectorizer): - """Specifies a user-defined vectorizer for generating the vector embedding of a query string. - Integration of an external vectorizer is achieved using the custom Web API interface of a - skillset. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar web_api_parameters: Specifies the properties of the user-defined vectorizer. - :vartype web_api_parameters: ~azure.search.documents.indexes.models.WebApiVectorizerParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "web_api_parameters": {"key": "customWebApiParameters", "type": "WebApiVectorizerParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword web_api_parameters: Specifies the properties of the user-defined vectorizer. - :paramtype web_api_parameters: - ~azure.search.documents.indexes.models.WebApiVectorizerParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "customWebApi" - self.web_api_parameters = web_api_parameters - - -class WebApiVectorizerParameters(_serialization.Model): - """Specifies the properties for connecting to a user-defined vectorizer. - - :ivar url: The URI of the Web API providing the vectorizer. - :vartype url: str - :ivar http_headers: The headers required to make the HTTP request. - :vartype http_headers: dict[str, str] - :ivar http_method: The method for the HTTP request. - :vartype http_method: str - :ivar timeout: The desired timeout for the request. Default is 30 seconds. - :vartype timeout: ~datetime.timedelta - :ivar auth_resource_id: Applies to custom endpoints that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the vectorization connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _attribute_map = { - "url": {"key": "uri", "type": "str"}, - "http_headers": {"key": "httpHeaders", "type": "{str}"}, - "http_method": {"key": "httpMethod", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "auth_resource_id": {"key": "authResourceId", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - url: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, - http_method: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - auth_resource_id: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword url: The URI of the Web API providing the vectorizer. - :paramtype url: str - :keyword http_headers: The headers required to make the HTTP request. - :paramtype http_headers: dict[str, str] - :keyword http_method: The method for the HTTP request. - :paramtype http_method: str - :keyword timeout: The desired timeout for the request. Default is 30 seconds. - :paramtype timeout: ~datetime.timedelta - :keyword auth_resource_id: Applies to custom endpoints that connect to external code in an - Azure function or some other application that provides the transformations. This value should - be the application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the vectorization connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :paramtype auth_resource_id: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.url = url - self.http_headers = http_headers - self.http_method = http_method - self.timeout = timeout - self.auth_resource_id = auth_resource_id - self.auth_identity = auth_identity - - -class WebKnowledgeSource(KnowledgeSource): - """Knowledge Source targeting web results. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the knowledge base. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar web_parameters: The parameters for the web knowledge source. - :vartype web_parameters: ~azure.search.documents.indexes.models.WebKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "web_parameters": {"key": "webParameters", "type": "WebKnowledgeSourceParameters"}, - } - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - web_parameters: Optional["_models.WebKnowledgeSourceParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the knowledge base. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your knowledge base - definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once - you have encrypted your knowledge base definition, it will always remain encrypted. The search - service will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your knowledge base definition will be - unaffected. Encryption with customer-managed keys is not available for free search services, - and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword web_parameters: The parameters for the web knowledge source. - :paramtype web_parameters: ~azure.search.documents.indexes.models.WebKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "web" - self.web_parameters = web_parameters - - -class WebKnowledgeSourceDomain(_serialization.Model): - """Configuration for web knowledge source domain. - - All required parameters must be populated in order to send to server. - - :ivar address: The address of the domain. Required. - :vartype address: str - :ivar include_subpages: Whether or not to include subpages from this domain. - :vartype include_subpages: bool - """ - - _validation = { - "address": {"required": True}, - } - - _attribute_map = { - "address": {"key": "address", "type": "str"}, - "include_subpages": {"key": "includeSubpages", "type": "bool"}, - } - - def __init__(self, *, address: str, include_subpages: Optional[bool] = None, **kwargs: Any) -> None: - """ - :keyword address: The address of the domain. Required. - :paramtype address: str - :keyword include_subpages: Whether or not to include subpages from this domain. - :paramtype include_subpages: bool - """ - super().__init__(**kwargs) - self.address = address - self.include_subpages = include_subpages - - -class WebKnowledgeSourceDomains(_serialization.Model): - """Domain allow/block configuration for web knowledge source. - - :ivar allowed_domains: Domains that are allowed for web results. - :vartype allowed_domains: list[~azure.search.documents.indexes.models.WebKnowledgeSourceDomain] - :ivar blocked_domains: Domains that are blocked from web results. - :vartype blocked_domains: list[~azure.search.documents.indexes.models.WebKnowledgeSourceDomain] - """ - - _attribute_map = { - "allowed_domains": {"key": "allowedDomains", "type": "[WebKnowledgeSourceDomain]"}, - "blocked_domains": {"key": "blockedDomains", "type": "[WebKnowledgeSourceDomain]"}, - } - - def __init__( - self, - *, - allowed_domains: Optional[list["_models.WebKnowledgeSourceDomain"]] = None, - blocked_domains: Optional[list["_models.WebKnowledgeSourceDomain"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword allowed_domains: Domains that are allowed for web results. - :paramtype allowed_domains: - list[~azure.search.documents.indexes.models.WebKnowledgeSourceDomain] - :keyword blocked_domains: Domains that are blocked from web results. - :paramtype blocked_domains: - list[~azure.search.documents.indexes.models.WebKnowledgeSourceDomain] - """ - super().__init__(**kwargs) - self.allowed_domains = allowed_domains - self.blocked_domains = blocked_domains - - -class WebKnowledgeSourceParameters(_serialization.Model): - """Parameters for web knowledge source. - - :ivar domains: Domain allow/block configuration for web results. - :vartype domains: ~azure.search.documents.indexes.models.WebKnowledgeSourceDomains - """ - - _attribute_map = { - "domains": {"key": "domains", "type": "WebKnowledgeSourceDomains"}, - } - - def __init__(self, *, domains: Optional["_models.WebKnowledgeSourceDomains"] = None, **kwargs: Any) -> None: - """ - :keyword domains: Domain allow/block configuration for web results. - :paramtype domains: ~azure.search.documents.indexes.models.WebKnowledgeSourceDomains - """ - super().__init__(**kwargs) - self.domains = domains - - -class WordDelimiterTokenFilter(TokenFilter): - """Splits words into subwords and performs optional transformations on subword groups. This token - filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar generate_word_parts: A value indicating whether to generate part words. If set, causes - parts of words to be generated; for example "AzureSearch" becomes "Azure" "Search". Default is - true. - :vartype generate_word_parts: bool - :ivar generate_number_parts: A value indicating whether to generate number subwords. Default is - true. - :vartype generate_number_parts: bool - :ivar catenate_words: A value indicating whether maximum runs of word parts will be catenated. - For example, if this is set to true, "Azure-Search" becomes "AzureSearch". Default is false. - :vartype catenate_words: bool - :ivar catenate_numbers: A value indicating whether maximum runs of number parts will be - catenated. For example, if this is set to true, "1-2" becomes "12". Default is false. - :vartype catenate_numbers: bool - :ivar catenate_all: A value indicating whether all subword parts will be catenated. For - example, if this is set to true, "Azure-Search-1" becomes "AzureSearch1". Default is false. - :vartype catenate_all: bool - :ivar split_on_case_change: A value indicating whether to split words on caseChange. For - example, if this is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. - :vartype split_on_case_change: bool - :ivar preserve_original: A value indicating whether original words will be preserved and added - to the subword list. Default is false. - :vartype preserve_original: bool - :ivar split_on_numerics: A value indicating whether to split on numbers. For example, if this - is set to true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. - :vartype split_on_numerics: bool - :ivar stem_english_possessive: A value indicating whether to remove trailing "'s" for each - subword. Default is true. - :vartype stem_english_possessive: bool - :ivar protected_words: A list of tokens to protect from being delimited. - :vartype protected_words: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "generate_word_parts": {"key": "generateWordParts", "type": "bool"}, - "generate_number_parts": {"key": "generateNumberParts", "type": "bool"}, - "catenate_words": {"key": "catenateWords", "type": "bool"}, - "catenate_numbers": {"key": "catenateNumbers", "type": "bool"}, - "catenate_all": {"key": "catenateAll", "type": "bool"}, - "split_on_case_change": {"key": "splitOnCaseChange", "type": "bool"}, - "preserve_original": {"key": "preserveOriginal", "type": "bool"}, - "split_on_numerics": {"key": "splitOnNumerics", "type": "bool"}, - "stem_english_possessive": {"key": "stemEnglishPossessive", "type": "bool"}, - "protected_words": {"key": "protectedWords", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - generate_word_parts: bool = True, - generate_number_parts: bool = True, - catenate_words: bool = False, - catenate_numbers: bool = False, - catenate_all: bool = False, - split_on_case_change: bool = True, - preserve_original: bool = False, - split_on_numerics: bool = True, - stem_english_possessive: bool = True, - protected_words: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword generate_word_parts: A value indicating whether to generate part words. If set, causes - parts of words to be generated; for example "AzureSearch" becomes "Azure" "Search". Default is - true. - :paramtype generate_word_parts: bool - :keyword generate_number_parts: A value indicating whether to generate number subwords. Default - is true. - :paramtype generate_number_parts: bool - :keyword catenate_words: A value indicating whether maximum runs of word parts will be - catenated. For example, if this is set to true, "Azure-Search" becomes "AzureSearch". Default - is false. - :paramtype catenate_words: bool - :keyword catenate_numbers: A value indicating whether maximum runs of number parts will be - catenated. For example, if this is set to true, "1-2" becomes "12". Default is false. - :paramtype catenate_numbers: bool - :keyword catenate_all: A value indicating whether all subword parts will be catenated. For - example, if this is set to true, "Azure-Search-1" becomes "AzureSearch1". Default is false. - :paramtype catenate_all: bool - :keyword split_on_case_change: A value indicating whether to split words on caseChange. For - example, if this is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. - :paramtype split_on_case_change: bool - :keyword preserve_original: A value indicating whether original words will be preserved and - added to the subword list. Default is false. - :paramtype preserve_original: bool - :keyword split_on_numerics: A value indicating whether to split on numbers. For example, if - this is set to true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. - :paramtype split_on_numerics: bool - :keyword stem_english_possessive: A value indicating whether to remove trailing "'s" for each - subword. Default is true. - :paramtype stem_english_possessive: bool - :keyword protected_words: A list of tokens to protect from being delimited. - :paramtype protected_words: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.WordDelimiterTokenFilter" - self.generate_word_parts = generate_word_parts - self.generate_number_parts = generate_number_parts - self.catenate_words = catenate_words - self.catenate_numbers = catenate_numbers - self.catenate_all = catenate_all - self.split_on_case_change = split_on_case_change - self.preserve_original = preserve_original - self.split_on_numerics = split_on_numerics - self.stem_english_possessive = stem_english_possessive - self.protected_words = protected_words diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py deleted file mode 100644 index 83f75c712c54..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_bases_operations import KnowledgeBasesOperations # type: ignore -from ._knowledge_sources_operations import KnowledgeSourcesOperations # type: ignore -from ._data_sources_operations import DataSourcesOperations # type: ignore -from ._indexers_operations import IndexersOperations # type: ignore -from ._skillsets_operations import SkillsetsOperations # type: ignore -from ._synonym_maps_operations import SynonymMapsOperations # type: ignore -from ._indexes_operations import IndexesOperations # type: ignore -from ._aliases_operations import AliasesOperations # type: ignore -from ._search_service_client_operations import _SearchServiceClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBasesOperations", - "KnowledgeSourcesOperations", - "DataSourcesOperations", - "IndexersOperations", - "SkillsetsOperations", - "SynonymMapsOperations", - "IndexesOperations", - "AliasesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py deleted file mode 100644 index d11a50479c03..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py +++ /dev/null @@ -1,770 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - alias_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases('{aliasName}')") - path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - alias_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases('{aliasName}')") - path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(alias_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases('{aliasName}')") - path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class AliasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`aliases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create( - self, - alias: _models.SearchAlias, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - alias: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - alias: Union[_models.SearchAlias, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Is either a SearchAlias type or a - IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.SearchAlias"]: - """Lists all aliases available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Aliases - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchAlias or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListAliasesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListAliasesResult", pipeline_response) - list_of_elem = deserialized.aliases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: _models.SearchAlias, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: Union[_models.SearchAlias, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Is either a SearchAlias type or - a IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_or_update_request( - alias_name=alias_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - alias_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Alias - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, alias_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchAlias: - """Retrieves an alias definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Alias - - :param alias_name: The name of the alias to retrieve. Required. - :type alias_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py deleted file mode 100644 index 05684a56756c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py +++ /dev/null @@ -1,764 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - data_source_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources('{dataSourceName}')") - path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - data_source_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources('{dataSourceName}')") - path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - data_source_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources('{dataSourceName}')") - path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class DataSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`data_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: _models.SearchIndexerDataSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_or_update_request( - data_source_name=data_source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - data_source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Data-Source - - :param data_source_name: The name of the datasource to delete. Required. - :type data_source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, data_source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Retrieves a datasource definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Data-Source - - :param data_source_name: The name of the datasource to retrieve. Required. - :type data_source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListDataSourcesResult: - """Lists all datasources available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Data-Sources - - :param select: Selects which top-level properties of the data sources to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListDataSourcesResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListDataSourcesResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListDataSourcesResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - data_source: _models.SearchIndexerDataSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - data_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py deleted file mode 100644 index d1244a9da49a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py +++ /dev/null @@ -1,1424 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_reset_request( - indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.reset") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_reset_docs_request( - indexer_name: str, *, overwrite: bool = False, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.resetdocs") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if overwrite is not None: - _params["overwrite"] = _SERIALIZER.query("overwrite", overwrite, "bool") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resync_request( - indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.resync") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_run_request(indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.run") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - indexer_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - if disable_cache_reprocessing_change_detection is not None: - _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( - "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" - ) - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - indexer_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_status_request( - indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.status") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class IndexersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`indexers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def reset( # pylint: disable=inconsistent-return-statements - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Resets the change tracking state associated with an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Reset-Indexer - - :param indexer_name: The name of the indexer to reset. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_reset_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[_models.DocumentKeysOrIds] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def reset_docs( # pylint: disable=inconsistent-return-statements - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[Union[_models.DocumentKeysOrIds, IO[bytes]]] = None, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Is either a DocumentKeysOrIds type or a IO[bytes] type. Default value is - None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if keys_or_ids else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" if keys_or_ids else None - _json = None - _content = None - if isinstance(keys_or_ids, (IOBase, bytes)): - _content = keys_or_ids - else: - if keys_or_ids is not None: - _json = self._serialize.body(keys_or_ids, "DocumentKeysOrIds") - else: - _json = None - - _request = build_reset_docs_request( - indexer_name=indexer_name, - overwrite=overwrite, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def resync( - self, - indexer_name: str, - indexer_resync: _models.IndexerResyncBody, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def resync( - self, - indexer_name: str, - indexer_resync: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def resync( # pylint: disable=inconsistent-return-statements - self, - indexer_name: str, - indexer_resync: Union[_models.IndexerResyncBody, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Is either a IndexerResyncBody type or a IO[bytes] type. Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer_resync, (IOBase, bytes)): - _content = indexer_resync - else: - _json = self._serialize.body(indexer_resync, "IndexerResyncBody") - - _request = build_resync_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def run( # pylint: disable=inconsistent-return-statements - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Runs an indexer on-demand. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Run-Indexer - - :param indexer_name: The name of the indexer to run. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_run_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: _models.SearchIndexer, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: Union[_models.SearchIndexer, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Is either a SearchIndexer - type or a IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_or_update_request( - indexer_name=indexer_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - indexer_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Indexer - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexer: - """Retrieves an indexer definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer - - :param indexer_name: The name of the indexer to retrieve. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListIndexersResult: - """Lists all indexers available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexers - - :param select: Selects which top-level properties of the indexers to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListIndexersResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexersResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListIndexersResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - indexer: _models.SearchIndexer, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - indexer: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - indexer: Union[_models.SearchIndexer, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Is either a SearchIndexer type or a - IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_status( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerStatus: - """Returns the current status and execution history of an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer-Status - - :param indexer_name: The name of the indexer for which to retrieve status. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerStatus or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerStatus] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_status_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py deleted file mode 100644 index da86d3b8d39c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py +++ /dev/null @@ -1,1079 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - index_name: str, - *, - prefer: Union[str, _models.Enum0], - allow_index_downtime: Optional[bool] = None, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if allow_index_downtime is not None: - _params["allowIndexDowntime"] = _SERIALIZER.query("allow_index_downtime", allow_index_downtime, "bool") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - index_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(index_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_statistics_request( - index_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')/search.stats") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_analyze_request( - index_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')/search.analyze") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`indexes` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create( - self, - index: _models.SearchIndex, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - index: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - index: Union[_models.SearchIndex, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Is either a SearchIndex type or a - IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.SearchIndex"]: - """Lists all indexes available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexes - - :param select: Selects which top-level properties of the index definitions to retrieve. - Specified as a comma-separated list of JSON property names, or '*' for all properties. The - default is all properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchIndex or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexesResult", pipeline_response) - list_of_elem = deserialized.indexes - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: _models.SearchIndex, - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: IO[bytes], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: Union[_models.SearchIndex, IO[bytes]], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Is either a SearchIndex type or - a IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_or_update_request( - index_name=index_name, - prefer=prefer, - allow_index_downtime=allow_index_downtime, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - index_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. This operation is permanent, with no - recovery option. Make sure you have a master copy of your index definition, data ingestion - code, and a backup of the primary data source in case you need to re-build the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Index - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndex: - """Retrieves an index definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index - - :param index_name: The name of the index to retrieve. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_statistics( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.GetIndexStatisticsResult: - """Returns statistics for the given index, including a document count and storage usage. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index-Statistics - - :param index_name: The name of the index for which to retrieve statistics. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: GetIndexStatisticsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GetIndexStatisticsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_statistics_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("GetIndexStatisticsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def analyze( - self, - index_name: str, - request: _models.AnalyzeRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def analyze( - self, - index_name: str, - request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def analyze( - self, - index_name: str, - request: Union[_models.AnalyzeRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Is either a - AnalyzeRequest type or a IO[bytes] type. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AnalyzeResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(request, (IOBase, bytes)): - _content = request - else: - _json = self._serialize.body(request, "AnalyzeRequest") - - _request = build_analyze_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AnalyzeResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_bases_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_bases_operations.py deleted file mode 100644 index 6ec7039362ad..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_bases_operations.py +++ /dev/null @@ -1,744 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - knowledge_base_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgebases('{knowledgeBaseName}')") - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - knowledge_base_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgebases('{knowledgeBaseName}')") - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - knowledge_base_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgebases('{knowledgeBaseName}')") - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgebases") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgebases") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class KnowledgeBasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`knowledge_bases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - knowledge_base_name: str, - prefer: Union[str, _models.Enum0], - knowledge_base: _models.KnowledgeBase, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base or updates an knowledge base if it already exists. - - :param knowledge_base_name: The name of the knowledge base to create or update. Required. - :type knowledge_base_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_base: The definition of the knowledge base to create or update. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - knowledge_base_name: str, - prefer: Union[str, _models.Enum0], - knowledge_base: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base or updates an knowledge base if it already exists. - - :param knowledge_base_name: The name of the knowledge base to create or update. Required. - :type knowledge_base_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_base: The definition of the knowledge base to create or update. Required. - :type knowledge_base: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - knowledge_base_name: str, - prefer: Union[str, _models.Enum0], - knowledge_base: Union[_models.KnowledgeBase, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base or updates an knowledge base if it already exists. - - :param knowledge_base_name: The name of the knowledge base to create or update. Required. - :type knowledge_base_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_base: The definition of the knowledge base to create or update. Is either a - KnowledgeBase type or a IO[bytes] type. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_base, (IOBase, bytes)): - _content = knowledge_base - else: - _json = self._serialize.body(knowledge_base, "KnowledgeBase") - - _request = build_create_or_update_request( - knowledge_base_name=knowledge_base_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBase", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - knowledge_base_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge base. - - :param knowledge_base_name: The name of the knowledge base to delete. Required. - :type knowledge_base_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - knowledge_base_name=knowledge_base_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, knowledge_base_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeBase: - """Retrieves an knowledge base definition. - - :param knowledge_base_name: The name of the knowledge base to retrieve. Required. - :type knowledge_base_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - knowledge_base_name=knowledge_base_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBase", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.KnowledgeBase"]: - """Lists all knowledge bases available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeBase or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeBasesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeBasesResult", pipeline_response) - list_of_elem = deserialized.knowledge_bases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create( - self, - knowledge_base: _models.KnowledgeBase, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The definition of the knowledge base to create. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - knowledge_base: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The definition of the knowledge base to create. Required. - :type knowledge_base: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - knowledge_base: Union[_models.KnowledgeBase, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The definition of the knowledge base to create. Is either a - KnowledgeBase type or a IO[bytes] type. Required. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeBase or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_base, (IOBase, bytes)): - _content = knowledge_base - else: - _json = self._serialize.body(knowledge_base, "KnowledgeBase") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBase", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py deleted file mode 100644 index df41b5184714..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py +++ /dev/null @@ -1,836 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - source_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - source_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(source_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_status_request( - source_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')/status") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class KnowledgeSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`knowledge_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: _models.KnowledgeSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Is either - a KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_or_update_request( - source_name=source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeSource: - """Retrieves a knowledge source definition. - - :param source_name: The name of the knowledge source to retrieve. Required. - :type source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.KnowledgeSource"]: - """Lists all knowledge sources available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeSource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeSourcesResult", pipeline_response) - list_of_elem = deserialized.knowledge_sources - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create( - self, - knowledge_source: _models.KnowledgeSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - knowledge_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Is either a - KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_status( - self, source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeSourceStatus: - """Returns the current status and synchronization history of a knowledge source. - - :param source_name: The name of the knowledge source for which to retrieve status. Required. - :type source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSourceStatus or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSourceStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeSourceStatus] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_status_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSourceStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py deleted file mode 100644 index e5df723a945b..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py +++ /dev/null @@ -1,244 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_service_statistics_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/servicestats") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_index_stats_summary_request( - *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexstats") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class _SearchServiceClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchServiceClientConfiguration] -): - - @distributed_trace - def get_service_statistics( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchServiceStatistics: - """Gets service level statistics for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchServiceStatistics or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchServiceStatistics] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_service_statistics_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchServiceStatistics", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_index_stats_summary( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.IndexStatisticsSummary"]: - """Retrieves a summary of statistics for all indexes in the search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either IndexStatisticsSummary or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexStatsSummary] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_index_stats_summary_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexStatsSummary", pipeline_response) - list_of_elem = deserialized.indexes_statistics - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py deleted file mode 100644 index f70f1dcda9a8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py +++ /dev/null @@ -1,958 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - skillset_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - if disable_cache_reprocessing_change_detection is not None: - _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( - "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" - ) - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - skillset_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - skillset_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_reset_skills_request( - skillset_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')/search.resetskills") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class SkillsetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`skillsets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: _models.SearchIndexerSkillset, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Is either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_or_update_request( - skillset_name=skillset_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - skillset_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/delete-skillset - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, skillset_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Retrieves a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/get-skillset - - :param skillset_name: The name of the skillset to retrieve. Required. - :type skillset_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSkillsetsResult: - """List all skillsets in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/list-skillset - - :param select: Selects which top-level properties of the skillsets to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSkillsetsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSkillsetsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSkillsetsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - skillset: _models.SearchIndexerSkillset, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - skillset: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. Is - either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def reset_skills( - self, - skillset_name: str, - skill_names: _models.SkillNames, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def reset_skills( - self, - skillset_name: str, - skill_names: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def reset_skills( # pylint: disable=inconsistent-return-statements - self, - skillset_name: str, - skill_names: Union[_models.SkillNames, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Is either a SkillNames type or a IO[bytes] - type. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skill_names, (IOBase, bytes)): - _content = skill_names - else: - _json = self._serialize.body(skill_names, "SkillNames") - - _request = build_reset_skills_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py deleted file mode 100644 index d573a54ae765..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py +++ /dev/null @@ -1,746 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - synonym_map_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps('{synonymMapName}')") - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - synonym_map_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps('{synonymMapName}')") - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - synonym_map_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps('{synonymMapName}')") - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class SynonymMapsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`synonym_maps` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: _models.SynonymMap, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: Union[_models.SynonymMap, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Is either a - SynonymMap type or a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_or_update_request( - synonym_map_name=synonym_map_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - synonym_map_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Synonym-Map - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, synonym_map_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SynonymMap: - """Retrieves a synonym map definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Synonym-Map - - :param synonym_map_name: The name of the synonym map to retrieve. Required. - :type synonym_map_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSynonymMapsResult: - """Lists all synonym maps available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Synonym-Maps - - :param select: Selects which top-level properties of the synonym maps to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSynonymMapsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSynonymMapsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSynonymMapsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - synonym_map: _models.SynonymMap, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - synonym_map: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - synonym_map: Union[_models.SynonymMap, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Is either a SynonymMap type or - a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py new file mode 100644 index 000000000000..baa9bb7fd3fa --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _SearchIndexerClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py new file mode 100644 index 000000000000..fe1ec10a1fb3 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -0,0 +1,6106 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import MatchConditions, PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceModifiedError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1 +from ... import models as _models2 +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Serializer +from ..._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match +from ...knowledgebases import models as _knowledgebases_models3 +from .._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_search_index_create_or_update_synonym_map_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/synonymmaps('{synonymMapName}')" + path_format_arguments = { + "synonymMapName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_delete_synonym_map_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/synonymmaps('{synonymMapName}')" + path_format_arguments = { + "synonymMapName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_synonym_map_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/synonymmaps('{synonymMapName}')" + path_format_arguments = { + "synonymMapName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_synonym_maps_request( # pylint: disable=name-too-long + *, select: Optional[list[str]] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/synonymmaps" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_synonym_map_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/synonymmaps" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_or_update_index_request( # pylint: disable=name-too-long + name: str, + *, + allow_index_downtime: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes('{indexName}')" + path_format_arguments = { + "indexName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if allow_index_downtime is not None: + _params["allowIndexDowntime"] = _SERIALIZER.query("allow_index_downtime", allow_index_downtime, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_delete_index_request( + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes('{indexName}')" + path_format_arguments = { + "indexName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_index_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes('{indexName}')" + path_format_arguments = { + "indexName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_list_indexes_request(*, select: Optional[list[str]] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_index_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_index_statistics_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes('{indexName}')/search.stats" + path_format_arguments = { + "indexName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_analyze_text_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexes('{indexName}')/search.analyze" + path_format_arguments = { + "indexName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_or_update_alias_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_delete_alias_request( + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_alias_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_list_aliases_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/aliases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_alias_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/aliases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_or_update_knowledge_base_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgebases('{knowledgeBaseName}')" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_delete_knowledge_base_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgebases('{knowledgeBaseName}')" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_knowledge_base_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgebases('{knowledgeBaseName}')" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_list_knowledge_bases_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgebases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_knowledge_base_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgebases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_or_update_knowledge_source_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgesources('{sourceName}')" + path_format_arguments = { + "sourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_delete_knowledge_source_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgesources('{sourceName}')" + path_format_arguments = { + "sourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_knowledge_source_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgesources('{sourceName}')" + path_format_arguments = { + "sourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_list_knowledge_sources_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgesources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_knowledge_source_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgesources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_knowledge_source_status_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/knowledgesources('{sourceName}')/status" + path_format_arguments = { + "sourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_service_statistics_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/servicestats" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_list_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexstats" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_create_or_update_data_source_connection_request( # pylint: disable=name-too-long + name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/datasources('{dataSourceName}')" + path_format_arguments = { + "dataSourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_delete_data_source_connection_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/datasources('{dataSourceName}')" + path_format_arguments = { + "dataSourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_data_source_connection_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/datasources('{dataSourceName}')" + path_format_arguments = { + "dataSourceName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_data_source_connections_request( # pylint: disable=name-too-long + *, select: Optional[list[str]] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/datasources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_create_data_source_connection_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/datasources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_reset_indexer_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')/search.reset" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_resync_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')/search.resync" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_reset_documents_request( # pylint: disable=name-too-long + name: str, *, overwrite: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')/search.resetdocs" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if overwrite is not None: + _params["overwrite"] = _SERIALIZER.query("overwrite", overwrite, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_run_indexer_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')/search.run" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_create_or_update_indexer_request( # pylint: disable=name-too-long + name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + if disable_cache_reprocessing_change_detection is not None: + _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( + "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_delete_indexer_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_indexer_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_indexers_request( # pylint: disable=name-too-long + *, select: Optional[list[str]] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_create_indexer_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_indexer_status_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/indexers('{indexerName}')/search.status" + path_format_arguments = { + "indexerName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_create_or_update_skillset_request( # pylint: disable=name-too-long + name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + if disable_cache_reprocessing_change_detection is not None: + _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( + "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_delete_skillset_request( # pylint: disable=name-too-long + name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_skillset_request(name: str, **kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_skillsets_request( # pylint: disable=name-too-long + *, select: Optional[list[str]] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/skillsets" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_create_skillset_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/skillsets" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_reset_skills_request(name: str, **kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") + + # Construct URL + _url = "/skillsets('{skillsetName}')/search.resetskills" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class _SearchIndexClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchIndexClientConfiguration] +): + + @overload + def _create_or_update_synonym_map( + self, + name: str, + synonym_map: _models1.SynonymMap, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SynonymMap: ... + @overload + def _create_or_update_synonym_map( + self, + name: str, + synonym_map: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SynonymMap: ... + @overload + def _create_or_update_synonym_map( + self, + name: str, + synonym_map: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SynonymMap: ... + + @distributed_trace + def _create_or_update_synonym_map( + self, + name: str, + synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param name: The name of the synonym map. Required. + :type name: str + :param synonym_map: The definition of the synonym map to create or update. Is one of the + following types: SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_synonym_map_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_synonym_map( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a synonym map. + + :param name: The name of the synonym map. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_synonym_map_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_synonym_map(self, name: str, **kwargs: Any) -> _models1.SynonymMap: + """Retrieves a synonym map definition. + + :param name: The name of the synonym map. Required. + :type name: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + + _request = build_search_index_get_synonym_map_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _get_synonym_maps( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models1._models.ListSynonymMapsResult: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSynonymMapsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.ListSynonymMapsResult] = kwargs.pop("cls", None) + + _request = build_search_index_get_synonym_maps_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListSynonymMapsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_synonym_map( + self, synonym_map: _models1.SynonymMap, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_synonym_map( + self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_synonym_map( + self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_synonym_map( + self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Is one of the following types: + SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_synonym_map_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _create_or_update_index( + self, + name: str, + index: _models1.SearchIndex, + *, + allow_index_downtime: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: ... + @overload + def _create_or_update_index( + self, + name: str, + index: JSON, + *, + allow_index_downtime: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: ... + @overload + def _create_or_update_index( + self, + name: str, + index: IO[bytes], + *, + allow_index_downtime: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: ... + + @distributed_trace + def _create_or_update_index( + self, + name: str, + index: Union[_models1.SearchIndex, JSON, IO[bytes]], + *, + allow_index_downtime: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param name: The name of the index. Required. + :type name: str + :param index: The definition of the index to create or update. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_index_request( + name=name, + allow_index_downtime=allow_index_downtime, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_index( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a search index and all the documents it contains. This operation is permanent, with no + recovery option. Make sure you have a master copy of your index definition, data ingestion + code, and a backup of the primary data source in case you need to re-build the index. + + :param name: The name of the index. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_index_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_index(self, name: str, **kwargs: Any) -> _models1.SearchIndex: + """Retrieves an index definition. + + :param name: The name of the index. Required. + :type name: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + _request = build_search_index_get_index_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_indexes(self, *, select: Optional[list[str]] = None, **kwargs: Any) -> ItemPaged["_models1.SearchIndex"]: + """Lists all indexes available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: An iterator like instance of SearchIndex + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchIndex]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_indexes_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchIndex], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_index( + self, index: _models1.SearchIndex, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_index( + self, index: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_index( + self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_index(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_index_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _get_index_statistics(self, name: str, **kwargs: Any) -> _models1.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. + + :param name: The name of the index. Required. + :type name: str + :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.GetIndexStatisticsResult] = kwargs.pop("cls", None) + + _request = build_search_index_get_index_statistics_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.GetIndexStatisticsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _analyze_text( + self, name: str, request: _models1.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.AnalyzeResult: ... + @overload + def _analyze_text( + self, name: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.AnalyzeResult: ... + @overload + def _analyze_text( + self, name: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.AnalyzeResult: ... + + @distributed_trace + def _analyze_text( + self, name: str, request: Union[_models1.AnalyzeTextOptions, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param name: The name of the index. Required. + :type name: str + :param request: The text and analyzer or analysis components to test. Is one of the following + types: AnalyzeTextOptions, JSON, IO[bytes] Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeTextOptions or JSON or IO[bytes] + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.AnalyzeResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_analyze_text_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.AnalyzeResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _create_or_update_alias( + self, + name: str, + alias: _models1.SearchAlias, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchAlias: ... + @overload + def _create_or_update_alias( + self, + name: str, + alias: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchAlias: ... + @overload + def _create_or_update_alias( + self, + name: str, + alias: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchAlias: ... + + @distributed_trace + def _create_or_update_alias( + self, + name: str, + alias: Union[_models1.SearchAlias, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param name: The name of the alias. Required. + :type name: str + :param alias: The definition of the alias to create or update. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_alias_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_alias( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. + + :param name: The name of the alias. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_alias_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_alias(self, name: str, **kwargs: Any) -> _models1.SearchAlias: + """Retrieves an alias definition. + + :param name: The name of the alias. Required. + :type name: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + + _request = build_search_index_get_alias_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_aliases(self, **kwargs: Any) -> ItemPaged["_models1.SearchAlias"]: + """Lists all aliases available for a search service. + + :return: An iterator like instance of SearchAlias + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchAlias]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_aliases_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchAlias], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_alias( + self, alias: _models1.SearchAlias, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_alias( + self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_alias( + self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_alias(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_alias_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: _models1.KnowledgeBase, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeBase: ... + @overload + def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeBase: ... + @overload + def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeBase: ... + + @distributed_trace + def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: Union[_models1.KnowledgeBase, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. + + :param name: The name of the knowledge base. Required. + :type name: str + :param knowledge_base: The definition of the knowledge base to create or update. Is one of the + following types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeBase] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base + else: + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_knowledge_base_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_knowledge_base( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a knowledge base. + + :param name: The name of the knowledge base. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_knowledge_base_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_knowledge_base(self, name: str, **kwargs: Any) -> _models1.KnowledgeBase: + """Retrieves a knowledge base definition. + + :param name: The name of the knowledge base. Required. + :type name: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.KnowledgeBase] = kwargs.pop("cls", None) + + _request = build_search_index_get_knowledge_base_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_knowledge_bases(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeBase"]: + """Lists all knowledge bases available for a search service. + + :return: An iterator like instance of KnowledgeBase + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.KnowledgeBase]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_knowledge_bases_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.KnowledgeBase], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_knowledge_base( + self, knowledge_base: _models1.KnowledgeBase, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_knowledge_base( + self, knowledge_base: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_knowledge_base( + self, knowledge_base: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_knowledge_base( + self, knowledge_base: Union[_models1.KnowledgeBase, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Is one of the following + types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeBase] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base + else: + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_knowledge_base_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: _models1.KnowledgeSource, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeSource: ... + @overload + def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeSource: ... + @overload + def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeSource: ... + + @distributed_trace + def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param name: The name of the knowledge source. Required. + :type name: str + :param knowledge_source: The definition of the knowledge source to create or update. Is one of + the following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_knowledge_source_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_knowledge_source( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes an existing knowledge source. + + :param name: The name of the knowledge source. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_knowledge_source_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_knowledge_source(self, name: str, **kwargs: Any) -> _models1.KnowledgeSource: + """Retrieves a knowledge source definition. + + :param name: The name of the knowledge source. Required. + :type name: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + + _request = build_search_index_get_knowledge_source_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_knowledge_sources(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeSource"]: + """Lists all knowledge sources available for a search service. + + :return: An iterator like instance of KnowledgeSource + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.KnowledgeSource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_knowledge_sources_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.KnowledgeSource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_knowledge_source( + self, knowledge_source: _models1.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_knowledge_source( + self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_knowledge_source( + self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_knowledge_source( + self, knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Is one of the + following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_knowledge_source_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_knowledge_source_status(self, name: str, **kwargs: Any) -> _knowledgebases_models3.KnowledgeSourceStatus: + """Retrieves the status of a knowledge source. + + :param name: The name of the knowledge source. Required. + :type name: str + :return: KnowledgeSourceStatus. The KnowledgeSourceStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeSourceStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_knowledgebases_models3.KnowledgeSourceStatus] = kwargs.pop("cls", None) + + _request = build_search_index_get_knowledge_source_status_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_knowledgebases_models3.KnowledgeSourceStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatistics: + """Gets service level statistics for a search service. + + :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchServiceStatistics] = kwargs.pop("cls", None) + + _request = build_search_index_get_service_statistics_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchServiceStatistics, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: + """Retrieves a summary of statistics for all indexes in the search service. + + :return: An iterator like instance of IndexStatisticsSummary + :rtype: + ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.IndexStatisticsSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_index_stats_summary_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.IndexStatisticsSummary], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class _SearchIndexerClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchIndexerClientConfiguration] +): + + @overload + def _create_or_update_data_source_connection( + self, + name: str, + data_source: _models1.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: ... + @overload + def _create_or_update_data_source_connection( + self, + name: str, + data_source: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: ... + @overload + def _create_or_update_data_source_connection( + self, + name: str, + data_source: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: ... + + @distributed_trace + def _create_or_update_data_source_connection( + self, + name: str, + data_source: Union[_models1.SearchIndexerDataSourceConnection, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. + + :param name: The name of the datasource. Required. + :type name: str + :param data_source: The definition of the datasource to create or update. Is one of the + following types: SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or + JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source, (IOBase, bytes)): + _content = data_source + else: + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_or_update_data_source_connection_request( + name=name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerDataSourceConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_data_source_connection( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a datasource. + + :param name: The name of the datasource. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_delete_data_source_connection_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_data_source_connection(self, name: str, **kwargs: Any) -> _models1.SearchIndexerDataSourceConnection: + """Retrieves a datasource definition. + + :param name: The name of the datasource. Required. + :type name: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_data_source_connection_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerDataSourceConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _get_data_source_connections( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models1._models.ListDataSourcesResult: + """Lists all datasources available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListDataSourcesResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.ListDataSourcesResult] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_data_source_connections_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListDataSourcesResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_data_source_connection( + self, + data_source_connection: _models1.SearchIndexerDataSourceConnection, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Required. + :type data_source_connection: + ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_data_source_connection( + self, data_source_connection: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Required. + :type data_source_connection: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_data_source_connection( + self, data_source_connection: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Required. + :type data_source_connection: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_data_source_connection( + self, data_source_connection: Union[_models1.SearchIndexerDataSourceConnection, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Is one of the + following types: SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source_connection: + ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or JSON or IO[bytes] + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source_connection, (IOBase, bytes)): + _content = data_source_connection + else: + _content = json.dumps(data_source_connection, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_data_source_connection_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerDataSourceConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def reset_indexer(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Resets the change tracking state associated with an indexer. + + :param name: The name of the indexer. Required. + :type name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_reset_indexer_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def _resync( + self, + name: str, + indexer_resync: _models1.IndexerResyncBody, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: ... + @overload + def _resync( + self, name: str, indexer_resync: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + @overload + def _resync( + self, name: str, indexer_resync: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + + @distributed_trace + def _resync( # pylint: disable=inconsistent-return-statements + self, name: str, indexer_resync: Union[_models1.IndexerResyncBody, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Resync selective options from the datasource to be re-ingested by the indexer.". + + :param name: The name of the indexer. Required. + :type name: str + :param indexer_resync: The definition of the indexer resync options. Is one of the following + types: IndexerResyncBody, JSON, IO[bytes] Required. + :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody or JSON or + IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer_resync, (IOBase, bytes)): + _content = indexer_resync + else: + _content = json.dumps(indexer_resync, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_resync_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def _reset_documents( + self, + name: str, + keys_or_ids: Optional[_models1.DocumentKeysOrIds] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: ... + @overload + def _reset_documents( + self, + name: str, + keys_or_ids: Optional[JSON] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: ... + @overload + def _reset_documents( + self, + name: str, + keys_or_ids: Optional[IO[bytes]] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: ... + + @distributed_trace + def _reset_documents( # pylint: disable=inconsistent-return-statements + self, + name: str, + keys_or_ids: Optional[Union[_models1.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + *, + overwrite: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param name: The name of the indexer. Required. + :type name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, + IO[bytes] Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or + IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if keys_or_ids else None + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if keys_or_ids else None + _content = None + if isinstance(keys_or_ids, (IOBase, bytes)): + _content = keys_or_ids + else: + if keys_or_ids is not None: + _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + else: + _content = None + + _request = build_search_indexer_reset_documents_request( + name=name, + overwrite=overwrite, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def run_indexer(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Runs an indexer on-demand. + + :param name: The name of the indexer. Required. + :type name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_run_indexer_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def _create_or_update_indexer( + self, + name: str, + indexer: _models1.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexer: ... + @overload + def _create_or_update_indexer( + self, + name: str, + indexer: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexer: ... + @overload + def _create_or_update_indexer( + self, + name: str, + indexer: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexer: ... + + @distributed_trace + def _create_or_update_indexer( + self, + name: str, + indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param name: The name of the indexer. Required. + :type name: str + :param indexer: The definition of the indexer to create or update. Is one of the following + types: SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_or_update_indexer_request( + name=name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_indexer( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes an indexer. + + :param name: The name of the indexer. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_delete_indexer_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_indexer(self, name: str, **kwargs: Any) -> _models1.SearchIndexer: + """Retrieves an indexer definition. + + :param name: The name of the indexer. Required. + :type name: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_indexer_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _get_indexers( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models1._models.ListIndexersResult: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListIndexersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.ListIndexersResult] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_indexers_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListIndexersResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_indexer( + self, indexer: _models1.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_indexer( + self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_indexer( + self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_indexer( + self, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Is one of the following types: + SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_indexer_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_indexer_status(self, name: str, **kwargs: Any) -> _models1.SearchIndexerStatus: + """Returns the current status and execution history of an indexer. + + :param name: The name of the indexer. Required. + :type name: str + :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerStatus] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_indexer_status_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _create_or_update_skillset( + self, + name: str, + skillset: _models1.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: ... + @overload + def _create_or_update_skillset( + self, + name: str, + skillset: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: ... + @overload + def _create_or_update_skillset( + self, + name: str, + skillset: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: ... + + @distributed_trace + def _create_or_update_skillset( + self, + name: str, + skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param name: The name of the skillset. Required. + :type name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_or_update_skillset_request( + name=name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _delete_skillset( # pylint: disable=inconsistent-return-statements + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a skillset in a search service. + + :param name: The name of the skillset. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_delete_skillset_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_skillset(self, name: str, **kwargs: Any) -> _models1.SearchIndexerSkillset: + """Retrieves a skillset in a search service. + + :param name: The name of the skillset. Required. + :type name: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_skillset_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _get_skillsets( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models1._models.ListSkillsetsResult: + """List all skillsets in a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSkillsetsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.ListSkillsetsResult] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_skillsets_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListSkillsetsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_skillset( + self, skillset: _models1.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_skillset( + self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_skillset( + self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_skillset( + self, skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. Is + one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_skillset_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def _reset_skills( + self, name: str, skill_names: _models1.SkillNames, *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + @overload + def _reset_skills( + self, name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + @overload + def _reset_skills( + self, name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + + @distributed_trace + def _reset_skills( # pylint: disable=inconsistent-return-statements + self, name: str, skill_names: Union[_models1.SkillNames, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param name: The name of the skillset. Required. + :type name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skill_names, (IOBase, bytes)): + _content = skill_names + else: + _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_reset_skills_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py new file mode 100644 index 000000000000..d721de4dbe5b --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -0,0 +1,850 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, cast, List, Sequence, Union, Optional, TYPE_CHECKING + +from azure.core import MatchConditions +from azure.core.paging import ItemPaged +from azure.core.tracing.decorator import distributed_trace + +from .. import models as _models +from ._operations import ( + _SearchIndexClientOperationsMixin as _SearchIndexClientOperationsMixinGenerated, + _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, +) + +if TYPE_CHECKING: + import azure.search.documents + + +class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexClient.""" + + @distributed_trace + def delete_synonym_map( + self, + synonym_map: Union[str, _models.SynonymMap], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a synonym map. + + :param synonym_map: The name of the synonym map to delete or a SynonymMap object. Required. + :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = synonym_map.name # type: ignore + return self._delete_synonym_map( + name=name, + match_condition=match_condition, + etag=synonym_map.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = synonym_map # type: ignore + return self._delete_synonym_map( + name=name, + **kwargs, + ) + + @distributed_trace + def create_or_update_synonym_map( + self, + synonym_map: _models.SynonymMap, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SynonymMap: + return self._create_or_update_synonym_map( + name=synonym_map.name, + synonym_map=synonym_map, + prefer="return=representation", + etag=synonym_map.e_tag, + match_condition=match_condition, + **kwargs, + ) + + @distributed_trace + def delete_index( + self, + index: Union[str, _models.SearchIndex], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. + + :param index: The name of the index to delete or a SearchIndex object. Required. + :type index: str or ~azure.search.documents.indexes.models.SearchIndex + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = index.name # type: ignore + return self._delete_index( + name=name, + match_condition=match_condition, + etag=index.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = index # type: ignore + return self._delete_index( + name=name, + **kwargs, + ) + + @distributed_trace + def create_or_update_index( + self, + index: _models.SearchIndex, + allow_index_downtime: Optional[bool] = None, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index: The SearchIndex object to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :type allow_index_downtime: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_index( + name=index.name, + index=index, + prefer="return=representation", + allow_index_downtime=allow_index_downtime, + etag=index.e_tag, + match_condition=match_condition, + **kwargs, + ) + + @distributed_trace + def create_or_update_alias( + self, + alias: _models.SearchAlias, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias: The SearchAlias object to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_alias( + name=alias.name, + alias=alias, + prefer="return=representation", + etag=alias.e_tag, + match_condition=match_condition, + **kwargs, + ) + + @distributed_trace + def delete_alias( + self, + alias: Union[str, _models.SearchAlias], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias: The name of the alias to delete or a SearchAlias object. Required. + :type alias: str or ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = alias.name # type: ignore + return self._delete_alias( + name=name, + match_condition=match_condition, + etag=alias.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = alias # type: ignore + return self._delete_alias( + name=name, + **kwargs, + ) + + @distributed_trace + def delete_knowledge_base( + self, + knowledge_base: Union[str, _models.KnowledgeBase], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a knowledge base. + + :param knowledge_base: The name of the knowledge base to delete or a KnowledgeBase object. Required. + :type knowledge_base: str or ~azure.search.documents.indexes.models.KnowledgeBase + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = knowledge_base.name # type: ignore + return self._delete_knowledge_base( + name=name, + match_condition=match_condition, + etag=knowledge_base.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = knowledge_base # type: ignore + return self._delete_knowledge_base( + name=name, + **kwargs, + ) + + @distributed_trace + def create_or_update_knowledge_base( + self, + knowledge_base: _models.KnowledgeBase, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. + + :param knowledge_base: The KnowledgeBase object to create or update. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeBase + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_knowledge_base( + name=knowledge_base.name, + knowledge_base=knowledge_base, + prefer="return=representation", + etag=knowledge_base.e_tag, + match_condition=match_condition, + **kwargs, + ) + + @distributed_trace + def create_or_update_knowledge_source( + self, + knowledge_source: _models.KnowledgeSource, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param knowledge_source: The KnowledgeSource object to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_knowledge_source( + name=knowledge_source.name, + knowledge_source=knowledge_source, + prefer="return=representation", + match_condition=match_condition, + etag=knowledge_source.e_tag, + **kwargs, + ) + + @distributed_trace + def delete_knowledge_source( + self, + knowledge_source: Union[str, _models.KnowledgeSource], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a knowledge source. + + :param knowledge_source: The name of the knowledge source to delete or a KnowledgeSource object. Required. + :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = knowledge_source.name # type: ignore + return self._delete_knowledge_source( + name=name, + match_condition=match_condition, + etag=knowledge_source.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = knowledge_source # type: ignore + return self._delete_knowledge_source( + name=name, + **kwargs, + ) + + @distributed_trace + def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: + """Lists the names of all indexes available for a search service. + + :return: An iterator like instance of index names + :rtype: ~azure.core.paging.ItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(ItemPaged[str], names) + + @distributed_trace + def get_synonym_maps(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[_models.SynonymMap]: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties of the synonym maps to retrieve. Specified + as a comma-separated list of JSON property names, or '*' for all properties. The default is + all properties. Default value is None. + :paramtype select: list[str] + :return: List of synonym maps + :rtype: list[~azure.search.documents.indexes.models.SynonymMap] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self._get_synonym_maps(select=select, **kwargs) + assert result.synonym_maps is not None # Hint for mypy + # typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + typed_result = result.synonym_maps + return typed_result + + @distributed_trace + def get_synonym_map_names(self, **kwargs: Any) -> List[str]: + """Lists the names of all synonym maps available for a search service. + + :return: List of synonym maps + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self.get_synonym_maps(**kwargs) + return [x.name for x in result] + + @distributed_trace + def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: + """List the alias names in an Azure Search service. + + :return: List of alias names + :rtype: ~azure.core.paging.ItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. + + """ + names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(ItemPaged[str], names) + + @distributed_trace + def analyze_text( + self, + index_name: str, + analyze_request: _models.AnalyzeTextOptions, + **kwargs: Any, + ) -> _models.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index to test an analyzer on. Required. + :type index_name: str + :param analyze_request: The text and analyzer or analysis components to test. Required. + :type analyze_request: ~azure.search.documents.indexes.models.AnalyzeTextOptions + :return: AnalyzeResult + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._analyze_text( + name=index_name, + request=analyze_request, + **kwargs, + ) + + @distributed_trace + def get_index_statistics( + self, + index_name: str, + **kwargs: Any, + ) -> _models.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. + + :param index_name: The name of the index to retrieve statistics for. Required. + :type index_name: str + :return: GetIndexStatisticsResult + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._get_index_statistics( + name=index_name, + **kwargs, + ) + + def get_search_client(self, index_name: str, **kwargs: Any) -> "azure.search.documents.SearchClient": + """Return a client to perform operations on Search. + + :param index_name: The name of the index. Required. + :type index_name: str + :return: A SearchClient for operations on the named index. + :rtype: ~azure.search.documents.SearchClient + """ + # pylint: disable=import-outside-toplevel + from ... import SearchClient + + return SearchClient( + endpoint=self._config.endpoint, + index_name=index_name, + credential=self._config.credential, + **kwargs, + ) + + +class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexerClient.""" + + @distributed_trace + def delete_data_source_connection( + self, + data_source_connection: Union[str, _models.SearchIndexerDataSourceConnection], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a data source connection. + + :param data_source_connection: The name of the data source connection to delete or a SearchIndexerDataSourceConnection object. Required. + :type data_source_connection: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = data_source_connection.name # type: ignore + return self._delete_data_source_connection( + name=name, + match_condition=match_condition, + etag=data_source_connection.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = data_source_connection # type: ignore + return self._delete_data_source_connection( + name=name, + **kwargs, + ) + + @distributed_trace + def create_or_update_data_source_connection( + self, + data_source_connection: _models.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source_connection: The SearchIndexerDataSourceConnection object to create or update. Required. + :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_data_source_connection( + name=data_source_connection.name, + data_source=data_source_connection, + prefer="return=representation", + etag=data_source_connection.e_tag, + match_condition=match_condition, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + **kwargs, + ) + + @distributed_trace + def delete_indexer( + self, + indexer: Union[str, _models.SearchIndexer], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes an indexer. + + :param indexer: The name of the indexer to delete or a SearchIndexer object. Required. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = indexer.name # type: ignore + return self._delete_indexer( + name=name, + match_condition=match_condition, + etag=indexer.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = indexer # type: ignore + return self._delete_indexer( + name=name, + **kwargs, + ) + + @distributed_trace + def create_or_update_indexer( + self, + indexer: _models.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer: The SearchIndexer object to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_indexer( + name=indexer.name, + indexer=indexer, + prefer="return=representation", + etag=indexer.e_tag, + match_condition=match_condition, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs, + ) + + @distributed_trace + def delete_skillset( + self, + skillset: Union[str, _models.SearchIndexerSkillset], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a skillset. + + :param skillset: The name of the skillset to delete or a SearchIndexerSkillset object. Required. + :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = skillset.name # type: ignore + return self._delete_skillset( + name=name, + match_condition=match_condition, + etag=skillset.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = skillset # type: ignore + return self._delete_skillset( + name=name, + **kwargs, + ) + + @distributed_trace + def create_or_update_skillset( + self, + skillset: _models.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset: The SearchIndexerSkillset object to create or update. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._create_or_update_skillset( + name=skillset.name, + skillset=skillset, + prefer="return=representation", + etag=skillset.e_tag, + match_condition=match_condition, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs, + ) + + @distributed_trace + def get_skillsets( + self, *, select: Optional[List[str]] = None, **kwargs: Any + ) -> List[_models.SearchIndexerSkillset]: + """Lists all skillsets available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: List of all the SearchIndexerSkillsets. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self._get_skillsets(select=select, **kwargs) + assert result.skillsets is not None # Hint for mypy + # typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + typed_result = result.skillsets + return typed_result + + @distributed_trace + def get_indexers(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[_models.SearchIndexer]: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: List of all the SearchIndexers. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self._get_indexers(select=select, **kwargs) + assert result.indexers is not None # Hint for mypy + # typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + typed_result = result.indexers + return typed_result + + @distributed_trace + def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: + """Lists all indexer names available for a search service. + + :return: List of all the SearchIndexers. + :rtype: list[str] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_indexer_crud.py + :start-after: [START list_indexers] + :end-before: [END list_indexers] + :language: python + :dedent: 4 + :caption: List all the SearchIndexers + """ + result = self.get_indexers(**kwargs) + return [x.name for x in result] + + @distributed_trace + def get_data_source_connections( + self, *, select: Optional[List[str]] = None, **kwargs: Any + ) -> List[_models.SearchIndexerDataSourceConnection]: + """Lists all data source connections available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: List of all the data source connections. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self._get_data_source_connections(select=select, **kwargs) + assert result.data_sources is not None # Hint for mypy + # typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + typed_result = result.data_sources + return typed_result + + @distributed_trace + def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: + """Lists all data source connection names available for a search service. + + :return: List of all the data source connection names. + :rtype: list[str] + + """ + result = self.get_data_source_connections(**kwargs) + return [x.name for x in result] + + @distributed_trace + def get_skillset_names(self, **kwargs: Any) -> List[str]: + """List the SearchIndexerSkillset names in an Azure Search service. + + :return: List of SearchIndexerSkillset names + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. + + """ + result = self.get_skillsets(**kwargs) + return [x.name for x in result] + + @distributed_trace + def reset_documents( + self, + indexer: Union[str, _models.SearchIndexer], + keys_or_ids: _models.DocumentKeysOrIds, + *, + overwrite: bool = False, + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer: The indexer to reset documents for. Can be the indexer name or a SearchIndexer object. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer + :param keys_or_ids: The document keys or ids to reset. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is False. + :paramtype overwrite: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = indexer.name # type: ignore + except AttributeError: + name = indexer # type: ignore + return self._reset_documents( + name=name, + keys_or_ids=keys_or_ids, + overwrite=overwrite, + **kwargs, + ) + + @distributed_trace + def reset_skills( + self, + skillset: Union[str, _models.SearchIndexerSkillset], + skill_names: List[str], + **kwargs: Any, + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset: The skillset to reset skills for. Can be the skillset name or a SearchIndexerSkillset object. + :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset + :param skill_names: The names of the skills to reset. + :type skill_names: list[str] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = skillset.name # type: ignore + except AttributeError: + name = skillset # type: ignore + return self._reset_skills( + name=name, + skill_names=_models.SkillNames(skill_names=skill_names), + **kwargs, + ) + + @distributed_trace + def resync( + self, + indexer: Union[str, _models.SearchIndexer], + indexer_resync_options: List[Union[str, _models.IndexerResyncOption]], + **kwargs: Any, + ) -> None: + """Resync selective options from the datasource to be re-ingested by the indexer. + + :param indexer: The indexer to resync. Can be the indexer name or a SearchIndexer object. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer + :param indexer_resync_options: Re-sync options that have been pre-defined from data source. + :type indexer_resync_options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = indexer.name # type: ignore + except AttributeError: + name = indexer # type: ignore + indexer_resync = _models.IndexerResyncBody(options=indexer_resync_options) + return self._resync( + name=name, + indexer_resync=indexer_resync, + **kwargs, + ) + + +__all__: list[str] = [ + "_SearchIndexClientOperationsMixin", + "_SearchIndexerClientOperationsMixin", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py deleted file mode 100644 index e8f8dec5cbb0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py +++ /dev/null @@ -1,868 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, List, Union, Optional, MutableMapping, cast - -from azure.core.rest import HttpRequest, HttpResponse -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from azure.core.paging import ItemPaged - -from .._api_versions import DEFAULT_VERSION -from ._generated import SearchServiceClient as _SearchServiceClient -from ._utils import ( - get_access_conditions, - normalize_endpoint, -) -from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy -from .._version import SDK_MONIKER -from .._search_client import SearchClient -from .models import ( - SearchIndex, - SynonymMap, - SearchAlias, - AnalyzeTextOptions, - AnalyzeResult, - IndexStatisticsSummary, - KnowledgeBase, - KnowledgeSource, - KnowledgeSourceStatus, -) - - -class SearchIndexClient(HeadersMixin): # pylint:disable=too-many-public-methods - """A client to interact with Azure search service index. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) - self._credential = credential - self._audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=self._audience) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __enter__(self): - self._client.__enter__() - return self - - def __exit__(self, *args): - return self._client.__exit__(*args) - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - def get_search_client(self, index_name: str, **kwargs: Any) -> SearchClient: - """Return a client to perform operations on Search - - :param index_name: The name of the Search Index - :type index_name: str - :return: SearchClient object - :rtype: ~azure.search.documents.SearchClient - - """ - return SearchClient( - self._endpoint, - index_name, - self._credential, - audience=self._audience, - api_version=self._api_version, - **kwargs - ) - - @distributed_trace - def list_indexes(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> ItemPaged[SearchIndex]: - """List the indexes in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of indexes - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - indexes = self._client.indexes.list(cls=lambda objs: [SearchIndex._from_generated(x) for x in objs], **kwargs) - return cast(ItemPaged[SearchIndex], indexes) - - @distributed_trace - def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: - """List the index names in an Azure Search service. - - :return: List of index names - :rtype: ~azure.core.paging.ItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.indexes.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(ItemPaged[str], names) - - @distributed_trace - def get_index(self, name: str, **kwargs: Any) -> SearchIndex: - """Retrieve a named index in an Azure Search service - - :param name: The name of the index to retrieve. - :type name: str - :return: SearchIndex object - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud.py - :start-after: [START get_index] - :end-before: [END get_index] - :language: python - :dedent: 4 - :caption: Get an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexes.get(name, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_index_statistics(self, index_name: str, **kwargs: Any) -> MutableMapping[str, Any]: - """Returns statistics for the given index, including a document count - and storage usage. - - :param index_name: The name of the index to retrieve. - :type index_name: str - :return: Statistics for the given index, including a document count and storage usage. - :rtype: Dict - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexes.get_statistics(index_name, **kwargs) - return result.as_dict() - - @distributed_trace - def delete_index( - self, - index: Union[str, SearchIndex], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. The model must be - provided instead of the name to use the access conditions. - - :param index: The index name or object to delete. - :type index: str or ~azure.search.documents.indexes.models.SearchIndex - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud.py - :start-after: [START delete_index] - :end-before: [END delete_index] - :language: python - :dedent: 4 - :caption: Delete an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - try: - index_name = index.name # type: ignore - except AttributeError: - index_name = index - self._client.indexes.delete(index_name=index_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_index(self, index: SearchIndex, **kwargs: Any) -> SearchIndex: - """Creates a new search index. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :return: The index created - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud.py - :start-after: [START create_index] - :end-before: [END create_index] - :language: python - :dedent: 4 - :caption: Creating a new index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_index = index._to_generated() # pylint:disable=protected-access - result = self._client.indexes.create(patched_index, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def create_or_update_index( - self, - index: SearchIndex, - allow_index_downtime: Optional[bool] = None, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. - :type allow_index_downtime: bool - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud.py - :start-after: [START update_index] - :end-before: [END update_index] - :language: python - :dedent: 4 - :caption: Update an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - patched_index = index._to_generated() # pylint:disable=protected-access - result = self._client.indexes.create_or_update( - index_name=index.name, - index=patched_index, - allow_index_downtime=allow_index_downtime, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def analyze_text(self, index_name: str, analyze_request: AnalyzeTextOptions, **kwargs: Any) -> AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index for which to test an analyzer. - :type index_name: str - :param analyze_request: The text and analyzer or analysis components to test. - :type analyze_request: ~azure.search.documents.indexes.models.AnalyzeTextOptions - :return: AnalyzeResult - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_analyze_text.py - :start-after: [START simple_analyze_text] - :end-before: [END simple_analyze_text] - :language: python - :dedent: 4 - :caption: Analyze text - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexes.analyze( - index_name=index_name, - request=analyze_request._to_analyze_request(), # pylint:disable=protected-access - **kwargs - ) - return result - - @distributed_trace - def get_synonym_maps(self, *, select: Optional[List[str]] = None, **kwargs) -> List[SynonymMap]: - """List the Synonym Maps in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of synonym maps - :rtype: list[~azure.search.documents.indexes.models.SynonymMap] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_synonym_map_crud.py - :start-after: [START get_synonym_maps] - :end-before: [END get_synonym_maps] - :language: python - :dedent: 4 - :caption: List Synonym Maps - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SynonymMap, SynonymMap._from_generated(x)) for x in result.synonym_maps] - - @distributed_trace - def get_synonym_map_names(self, **kwargs: Any) -> List[str]: - """List the Synonym Map names in an Azure Search service. - - :return: List of synonym maps - :rtype: list[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - return [x.name for x in result.synonym_maps] - - @distributed_trace - def get_synonym_map(self, name: str, **kwargs: Any) -> SynonymMap: - """Retrieve a named Synonym Map in an Azure Search service - - :param name: The name of the Synonym Map to get - :type name: str - :return: The retrieved Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.ResourceNotFoundError: If the Synonym Map doesn't exist. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_synonym_map_crud.py - :start-after: [START get_synonym_map] - :end-before: [END get_synonym_map] - :language: python - :dedent: 4 - :caption: Get a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.synonym_maps.get(name, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def delete_synonym_map( - self, - synonym_map: Union[str, SynonymMap], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named Synonym Map in an Azure Search service. To use access conditions, - the SynonymMap model must be provided instead of the name. It is enough to provide - the name of the synonym map to delete unconditionally. - - :param synonym_map: The synonym map name or object to delete - :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_synonym_map_crud.py - :start-after: [START delete_synonym_map] - :end-before: [END delete_synonym_map] - :language: python - :dedent: 4 - :caption: Delete a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - try: - name = synonym_map.name # type: ignore - except AttributeError: - name = synonym_map - self._client.synonym_maps.delete(synonym_map_name=name, error_map=error_map, **kwargs) - - @distributed_trace - def create_synonym_map(self, synonym_map: SynonymMap, **kwargs: Any) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :return: The created Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_synonym_map_crud.py - :start-after: [START create_synonym_map] - :end-before: [END create_synonym_map] - :language: python - :dedent: 4 - :caption: Create a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = self._client.synonym_maps.create(patched_synonym_map, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def create_or_update_synonym_map( - self, - synonym_map: SynonymMap, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service, or update an - existing one. - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The created or updated Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = self._client.synonym_maps.create_or_update( - synonym_map_name=synonym_map.name, - synonym_map=patched_synonym_map, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_service_statistics(self, **kwargs: Any) -> MutableMapping[str, Any]: - """Get service level statistics for a search service. - - :return: Service statistics result. - :rtype: dict - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.get_service_statistics(**kwargs) - return result.as_dict() - - @distributed_trace - def list_index_stats_summary(self, **kwargs: Any) -> ItemPaged[IndexStatisticsSummary]: - """Get index level statistics for a search service. - - :return: Index statistics result. - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - result = self._client.get_index_stats_summary(**kwargs) - return cast(ItemPaged[IndexStatisticsSummary], result) - - @distributed_trace - def list_aliases(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> ItemPaged[SearchAlias]: - """List the aliases in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of Aliases - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - return cast(ItemPaged[SearchAlias], self._client.aliases.list(**kwargs)) - - @distributed_trace - def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: - """List the alias names in an Azure Search service. - - :return: List of alias names - :rtype: ~azure.core.paging.ItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.aliases.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(ItemPaged[str], names) - - @distributed_trace - def get_alias(self, name: str, **kwargs: Any) -> SearchAlias: - """ - - :param name: The name of the alias to retrieve. - :type name: str - :return: SearchAlias object - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.aliases.get(name, **kwargs) - return result - - @distributed_trace - def delete_alias( - self, - alias: Union[str, SearchAlias], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation - - :param alias: The alias name or object to delete. - :type alias: str or ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_alias_crud.py - :start-after: [START delete_alias] - :end-before: [END delete_alias] - :language: python - :dedent: 4 - :caption: Deleting an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - try: - alias_name = alias.name # type: ignore - except AttributeError: - alias_name = alias - self._client.aliases.delete(alias_name=alias_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: - """Creates a new search alias. - - :param alias: The alias object. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :return: The alias created - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_alias_crud.py - :start-after: [START create_alias] - :end-before: [END create_alias] - :language: python - :dedent: 4 - :caption: Creating a new alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.aliases.create(alias, **kwargs) - return result # pylint:disable=protected-access - - @distributed_trace - def create_or_update_alias( - self, alias: SearchAlias, *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any - ) -> SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias: The definition of the alias to create or update. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the alias has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the alias hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the alias already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_alias_crud.py - :start-after: [START update_alias] - :end-before: [END update_alias] - :language: python - :dedent: 4 - :caption: Updating an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - result = self._client.aliases.create_or_update( - alias_name=alias.name, alias=alias, prefer="return=representation", error_map=error_map, **kwargs - ) - return result # pylint:disable=protected-access - - @distributed_trace - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> HttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access - - @distributed_trace - def delete_knowledge_base( - self, - knowledge_base: Union[str, KnowledgeBase], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge base. - - :param knowledge_base: The knowledge base name or object to delete. - :type knowledge_base: str or ~azure.search.documents.indexes.models.KnowledgeBase - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_base, match_condition) - kwargs.update(access_condition) - try: - knowledge_base_name = knowledge_base.name # type: ignore - except AttributeError: - knowledge_base_name = knowledge_base - self._client.knowledge_bases.delete( - knowledge_base_name=knowledge_base_name, error_map=error_map, **kwargs - ) - - @distributed_trace - def create_knowledge_base(self, knowledge_base: KnowledgeBase, **kwargs: Any) -> KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The knowledge base object. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :return: The knowledge base created - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_bases.create(knowledge_base, **kwargs) - return result - - @distributed_trace - def create_or_update_knowledge_base( - self, - knowledge_base: KnowledgeBase, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeBase: - """Creates a new knowledge base or updates one if it already exists. - - :param knowledge_base: The knowledge base object. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The knowledge base created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.ResourceNotFoundError: If the knowledge base doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the knowledge base has been modified on the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the knowledge base hasn't been - modified on the server. - :raises ~azure.core.exceptions.ResourceExistsError: If the knowledge base already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_base, match_condition) - kwargs.update(access_condition) - result = self._client.knowledge_bases.create_or_update( - knowledge_base_name=knowledge_base.name, - knowledge_base=knowledge_base, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return result - - @distributed_trace - def get_knowledge_base(self, name: str, **kwargs: Any) -> KnowledgeBase: - """Gets a knowledge base definition. - - :param name: The name of the knowledge base to retrieve. - :type name: str - :return: KnowledgeBase object - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_bases.get(knowledge_base_name=name, **kwargs) - return result - - @distributed_trace - def list_knowledge_bases(self, **kwargs: Any) -> ItemPaged[KnowledgeBase]: - """List the knowledge bases in an Azure Search service. - - :return: List of knowledge bases - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(ItemPaged[KnowledgeBase], self._client.knowledge_bases.list(**kwargs)) - - @distributed_trace - def delete_knowledge_source( - self, - knowledge_source: Union[str, KnowledgeSource], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param knowledge_source: The knowledge source name or object to delete. - :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - try: - source_name = knowledge_source.name # type: ignore - except AttributeError: - source_name = knowledge_source - self._client.knowledge_sources.delete(source_name=source_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: Any) -> KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :return: The knowledge source created - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_sources.create(knowledge_source, **kwargs) - return result - - @distributed_trace - def create_or_update_knowledge_source( - self, - knowledge_source: KnowledgeSource, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeSource: - """Creates a new knowledge source or updates an existing one. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The knowledge source created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - result = self._client.knowledge_sources.create_or_update( - source_name=knowledge_source.name, - knowledge_source=knowledge_source, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return result - - @distributed_trace - def get_knowledge_source(self, name: str, **kwargs: Any) -> KnowledgeSource: - """ - - :param name: The name of the knowledge source to retrieve. - :type name: str - :return: KnowledgeSource object - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_sources.get(name, **kwargs) - return result - - @distributed_trace - def get_knowledge_source_status(self, name: str, **kwargs: Any) -> KnowledgeSourceStatus: - """Returns the current status and synchronization history of a knowledge source. - - :param name: The name of the knowledge source for which to retrieve status. - :type name: str - :return: KnowledgeSourceStatus object - :rtype: ~azure.search.documents.indexes.models.KnowledgeSourceStatus - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_sources.get_status(source_name=name, **kwargs) - return result - - @distributed_trace - def list_knowledge_sources(self, **kwargs: Any) -> ItemPaged[KnowledgeSource]: - """List the knowledge sources in an Azure Search service. - - :return: List of Knowledge Sources - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(ItemPaged[KnowledgeSource], self._client.knowledge_sources.list(**kwargs)) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py deleted file mode 100644 index f3e79eae4898..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py +++ /dev/null @@ -1,741 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Optional, Sequence, Union, List, cast - -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace - -from ._generated import SearchServiceClient as _SearchServiceClient -from ._generated.models import ( - SkillNames, - SearchIndexerStatus, - DocumentKeysOrIds, - IndexerResyncOption, - IndexerResyncBody, -) -from ._utils import ( - get_access_conditions, - normalize_endpoint, -) -from .models import ( - SearchIndexer, - SearchIndexerSkillset, - EntityRecognitionSkillVersion, - SearchIndexerDataSourceConnection, - SentimentSkillVersion, -) -from .._api_versions import DEFAULT_VERSION -from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy -from .._version import SDK_MONIKER - - -class SearchIndexerClient(HeadersMixin): # pylint: disable=R0904 - """A client to interact with Azure search service Indexers. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __enter__(self) -> "SearchIndexerClient": - self._client.__enter__() - return self - - def __exit__(self, *args) -> None: - return self._client.__exit__(*args) - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - @distributed_trace - def create_indexer(self, indexer: SearchIndexer, **kwargs: Any) -> SearchIndexer: - """Creates a new SearchIndexer. - - :param indexer: The definition of the indexer to create. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START create_indexer] - :end-before: [END create_indexer] - :language: python - :dedent: 4 - :caption: Create a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = self._client.indexers.create(patched_indexer, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def create_or_update_indexer( - self, - indexer: SearchIndexer, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer: The definition of the indexer to create or update. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - name = indexer.name - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = self._client.indexers.create_or_update( - indexer_name=name, - indexer=patched_indexer, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_indexer(self, name: str, **kwargs: Any) -> SearchIndexer: - """Retrieves an indexer definition. - - :param name: The name of the indexer to retrieve. - :type name: str - :return: The SearchIndexer that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START get_indexer] - :end-before: [END get_indexer] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexers.get(name, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_indexers(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> Sequence[SearchIndexer]: - """Lists all indexers available for a search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of all the SearchIndexers. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START list_indexers] - :end-before: [END list_indexers] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SearchIndexer, SearchIndexer._from_generated(index)) for index in result.indexers] - - @distributed_trace - def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: - """Lists all indexer names available for a search service. - - :return: List of all the SearchIndexers. - :rtype: list[str] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START list_indexers] - :end-before: [END list_indexers] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - return [x.name for x in result.indexers] - - @distributed_trace - def delete_indexer( - self, - indexer: Union[str, SearchIndexer], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an indexer. To use access conditions, the SearchIndexer model - must be provided instead of the name. It is enough to provide - the name of the indexer to delete unconditionally. - - :param indexer: The indexer to delete. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START delete_indexer] - :end-before: [END delete_indexer] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - self._client.indexers.delete(name, error_map=error_map, **kwargs) - - @distributed_trace - def run_indexer(self, name: str, **kwargs: Any) -> None: - """Run an indexer. - - :param name: The name of the indexer to run. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START run_indexer] - :end-before: [END run_indexer] - :language: python - :dedent: 4 - :caption: Run a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - self._client.indexers.run(name, **kwargs) - - @distributed_trace - def reset_indexer(self, name: str, **kwargs: Any) -> None: - """Resets the change tracking state associated with an indexer. - - :param name: The name of the indexer to reset. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START reset_indexer] - :end-before: [END reset_indexer] - :language: python - :dedent: 4 - :caption: Reset a SearchIndexer's change tracking state - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - self._client.indexers.reset(name, **kwargs) - - @distributed_trace - def reset_documents( - self, - indexer: Union[str, SearchIndexer], - keys_or_ids: DocumentKeysOrIds, - *, - overwrite: bool = False, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - :param indexer: The indexer to reset documents for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param keys_or_ids: - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :return: None, or the result of cls(response) - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. The default is false. - :paramtype overwrite: bool - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["keys_or_ids"] = keys_or_ids - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - return self._client.indexers.reset_docs(name, overwrite=overwrite, **kwargs) - - @distributed_trace - def resync( - self, - indexer: Union[str, SearchIndexer], - indexer_resync_options: List[Union[str, IndexerResyncOption]], - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - :param indexer: The indexer to resync for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param indexer_resync_options: Required. - :type indexer_resync_options: list[str or - ~azure.search.documents.indexes.models.IndexerResyncOption] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - - # Create IndexerResyncBody from the list of options - resync_body = IndexerResyncBody(options=indexer_resync_options) - self._client.indexers.resync(name, resync_body, **kwargs) - - @distributed_trace - def get_indexer_status(self, name: str, **kwargs: Any) -> SearchIndexerStatus: - """Get the status of the indexer. - - :param name: The name of the indexer to fetch the status. - :type name: str - - :return: SearchIndexerStatus - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_crud.py - :start-after: [START get_indexer_status] - :end-before: [END get_indexer_status] - :language: python - :dedent: 4 - :caption: Get a SearchIndexer's status - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return self._client.indexers.get_status(name, **kwargs) - - @distributed_trace - def create_data_source_connection( - self, data_source_connection: SearchIndexerDataSourceConnection, **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection. - - :param data_source_connection: The definition of the data source connection to create. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_datasource_crud.py - :start-after: [START create_data_source_connection] - :end-before: [END create_data_source_connection] - :language: python - :dedent: 4 - :caption: Create a Data Source - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - packed_data_source = data_source_connection._to_generated() - result = self._client.data_sources.create(packed_data_source, **kwargs) - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace - def create_or_update_data_source_connection( - self, - data_source_connection: SearchIndexerDataSourceConnection, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_connection: The definition of the data source connection to create or update. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - """ - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(data_source_connection, match_condition) - kwargs.update(access_condition) - name = data_source_connection.name - packed_data_source = data_source_connection._to_generated() # pylint:disable=protected-access - result = self._client.data_sources.create_or_update( - data_source_name=name, - data_source=packed_data_source, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - **kwargs - ) - # pylint:disable=protected-access - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace - def get_data_source_connection(self, name: str, **kwargs: Any) -> SearchIndexerDataSourceConnection: - """Retrieves a data source connection definition. - - :param name: The name of the data source connection to retrieve. - :type name: str - :return: The SearchIndexerDataSourceConnection that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_datasource_crud.py - :start-after: [START get_data_source_connection] - :end-before: [END get_data_source_connection] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.data_sources.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace - def get_data_source_connections( - self, *, select: Optional[List[str]] = None, **kwargs: Any - ) -> Sequence[SearchIndexerDataSourceConnection]: - """Lists all data source connections available for a search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of all the data source connections. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_datasource_crud.py - :start-after: [START list_data_source_connections] - :end-before: [END list_data_source_connections] - :language: python - :dedent: 4 - :caption: List all the SearchIndexerDataSourceConnections - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - # pylint:disable=protected-access - return [ - cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(x)) - for x in result.data_sources - ] - - @distributed_trace - def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: - """Lists all data source connection names available for a search service. - - :return: List of all the data source connection names. - :rtype: list[str] - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - return [x.name for x in result.data_sources] - - @distributed_trace - def delete_data_source_connection( - self, - data_source_connection: Union[str, SearchIndexerDataSourceConnection], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a data source connection. To use access conditions, the SearchIndexerDataSourceConnection - model must be provided instead of the name. It is enough to provide the name of the data source connection - to delete unconditionally - - :param data_source_connection: The data source connection to delete. - :type data_source_connection: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexer_datasource_crud.py - :start-after: [START delete_data_source_connection] - :end-before: [END delete_data_source_connection] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(data_source_connection, match_condition) - kwargs.update(access_condition) - try: - name = data_source_connection.name # type: ignore - except AttributeError: - name = data_source_connection - self._client.data_sources.delete(data_source_name=name, error_map=error_map, **kwargs) - - @distributed_trace - def get_skillsets(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[SearchIndexerSkillset]: - # pylint:disable=protected-access - """List the SearchIndexerSkillsets in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of SearchIndexerSkillsets - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [ - cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(skillset)) - for skillset in result.skillsets - ] - - @distributed_trace - def get_skillset_names(self, **kwargs: Any) -> List[str]: - """List the SearchIndexerSkillset names in an Azure Search service. - - :return: List of SearchIndexerSkillset names - :rtype: list[str] - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [x.name for x in result.skillsets] - - @distributed_trace - def get_skillset(self, name: str, **kwargs: Any) -> SearchIndexerSkillset: - """Retrieve a named SearchIndexerSkillset in an Azure Search service - - :param name: The name of the SearchIndexerSkillset to get - :type name: str - :return: The retrieved SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.ResourceNotFoundError: If the skillset cannot be found. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.skillsets.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace - def delete_skillset( - self, - skillset: Union[str, SearchIndexerSkillset], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named SearchIndexerSkillset in an Azure Search service. To use access conditions, - the SearchIndexerSkillset model must be provided instead of the name. It is enough to provide - the name of the skillset to delete unconditionally - - :param skillset: The SearchIndexerSkillset to delete - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - self._client.skillsets.delete(name, error_map=error_map, **kwargs) - - @distributed_trace - def create_skillset(self, skillset: SearchIndexerSkillset, **kwargs: Any) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service - - :param skillset: The SearchIndexerSkillset object to create - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :return: The created SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - _validate_skillset(skillset) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - - result = self._client.skillsets.create(skillset_gen, **kwargs) # type: ignore - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace - def create_or_update_skillset( - self, - skillset: SearchIndexerSkillset, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service, or update an - existing one. - - :param skillset: The SearchIndexerSkillset object to create or update - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created or updated SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - _validate_skillset(skillset) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - - result = self._client.skillsets.create_or_update( - skillset_name=skillset.name, - skillset=skillset_gen, # type: ignore - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace - def reset_skills(self, skillset: Union[str, SearchIndexerSkillset], skill_names: List[str], **kwargs: Any) -> None: - """Reset an existing skillset in a search service. - - :param skillset: The SearchIndexerSkillset to reset - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param skill_names: the names of skills to be reset. - :type skill_names: List[str] - :return: None, or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - names = SkillNames(skill_names=skill_names) - return self._client.skillsets.reset_skills(skillset_name=name, skill_names=names, **kwargs) - - -def _validate_skillset(skillset: SearchIndexerSkillset): - """Validates any multi-version skills in the skillset to verify that unsupported - parameters are not supplied by the user. - - :param skillset: The skillset to validate - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - """ - skills = getattr(skillset, "skills", None) - if not skills: - return - - error_strings = [] - for skill in skills: - try: - skill_version = skill.get("skill_version") - except AttributeError: - skill_version = getattr(skill, "skill_version", None) - if not skill_version: - continue - if skill_version == SentimentSkillVersion.V3: - unsupported = [] - elif skill_version == EntityRecognitionSkillVersion.V3: - unsupported = ["include_typeless_entities"] - - errors = [] - for item in unsupported: - try: - if skill.get(item, None): - errors.append(item) - except AttributeError: - if skill.__dict__.get(item, None): - errors.append(item) - if errors: - error_strings.append( - "Unsupported parameters for skill version {}: {}".format(skill_version, ", ".join(errors)) - ) - if error_strings: - raise ValueError("\n".join(error_strings)) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py deleted file mode 100644 index bfe9a82a8357..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py +++ /dev/null @@ -1,80 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -from typing import Optional, Any, Tuple, Dict -from azure.core import MatchConditions -from azure.core.exceptions import ( - ClientAuthenticationError, - ResourceExistsError, - ResourceNotFoundError, - ResourceModifiedError, - ResourceNotModifiedError, -) - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: MatchConditions) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: str, match_condition: MatchConditions) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None - - -def get_access_conditions( - model: Any, match_condition: MatchConditions = MatchConditions.Unconditionally -) -> Tuple[Dict[int, Any], Dict[str, Optional[str]]]: - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError} - - if isinstance(model, str): - if match_condition is not MatchConditions.Unconditionally: - raise ValueError("A model must be passed to use access conditions") - return error_map, {} - - try: - if_match = prep_if_match(model.e_tag, match_condition) - if_none_match = prep_if_none_match(model.e_tag, match_condition) - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - if match_condition == MatchConditions.IfModified: - error_map[304] = ResourceNotModifiedError - error_map[412] = ResourceNotModifiedError - if match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - if match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError - return error_map, {"if_match": if_match, "if_none_match": if_none_match} - except AttributeError as ex: - raise ValueError("Unable to get e_tag from the model") from ex - - -def normalize_endpoint(endpoint): - try: - if not endpoint.lower().startswith("http"): - endpoint = "https://" + endpoint - elif not endpoint.lower().startswith("https"): - raise ValueError("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.") - return endpoint - except AttributeError as ex: - raise ValueError("Endpoint must be a string.") from ex diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/__init__.py similarity index 52% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/__init__.py index 4473821c4ebe..8026245c2abc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/__init__.py @@ -1,4 +1,6 @@ # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py new file mode 100644 index 000000000000..c402af2afc63 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py @@ -0,0 +1,1337 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/serialization.py similarity index 98% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_utils/serialization.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/serialization.py index 9b8154c91dc2..81ec1de5922b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_utils/serialization.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/serialization.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -819,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1755,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1781,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py index be7617562446..7e8a8679322d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py @@ -1,33 +1,31 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._search_index_client import SearchIndexClient -from ._search_indexer_client import SearchIndexerClient +from typing import TYPE_CHECKING -__all__ = ( +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchIndexClient # type: ignore +from ._client import SearchIndexerClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ "SearchIndexClient", "SearchIndexerClient", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py new file mode 100644 index 000000000000..8827716ecdcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py @@ -0,0 +1,189 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING, Union +from typing_extensions import Self + +from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from ..._utils.serialization import Deserializer, Serializer +from ._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration +from ._operations import _SearchIndexClientOperationsMixin, _SearchIndexerClientOperationsMixin + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class SearchIndexClient(_SearchIndexClientOperationsMixin): + """SearchIndexClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = SearchIndexClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) + + +class SearchIndexerClient(_SearchIndexerClientOperationsMixin): + """SearchIndexerClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = SearchIndexerClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py new file mode 100644 index 000000000000..c50be6dff29a --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py @@ -0,0 +1,131 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from ..._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) + + +class SearchIndexerClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexerClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py new file mode 100644 index 000000000000..baa9bb7fd3fa --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _SearchIndexerClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py new file mode 100644 index 000000000000..94160d3a5405 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -0,0 +1,4746 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import AsyncPipelineClient, MatchConditions +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceModifiedError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2 +from .... import models as _models3 +from ...._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ...._utils.utils import ClientMixinABC +from ....knowledgebases import models as _knowledgebases_models4 +from ..._operations._operations import ( + build_search_index_analyze_text_request, + build_search_index_create_alias_request, + build_search_index_create_index_request, + build_search_index_create_knowledge_base_request, + build_search_index_create_knowledge_source_request, + build_search_index_create_or_update_alias_request, + build_search_index_create_or_update_index_request, + build_search_index_create_or_update_knowledge_base_request, + build_search_index_create_or_update_knowledge_source_request, + build_search_index_create_or_update_synonym_map_request, + build_search_index_create_synonym_map_request, + build_search_index_delete_alias_request, + build_search_index_delete_index_request, + build_search_index_delete_knowledge_base_request, + build_search_index_delete_knowledge_source_request, + build_search_index_delete_synonym_map_request, + build_search_index_get_alias_request, + build_search_index_get_index_request, + build_search_index_get_index_statistics_request, + build_search_index_get_knowledge_base_request, + build_search_index_get_knowledge_source_request, + build_search_index_get_knowledge_source_status_request, + build_search_index_get_service_statistics_request, + build_search_index_get_synonym_map_request, + build_search_index_get_synonym_maps_request, + build_search_index_list_aliases_request, + build_search_index_list_index_stats_summary_request, + build_search_index_list_indexes_request, + build_search_index_list_knowledge_bases_request, + build_search_index_list_knowledge_sources_request, + build_search_indexer_create_data_source_connection_request, + build_search_indexer_create_indexer_request, + build_search_indexer_create_or_update_data_source_connection_request, + build_search_indexer_create_or_update_indexer_request, + build_search_indexer_create_or_update_skillset_request, + build_search_indexer_create_skillset_request, + build_search_indexer_delete_data_source_connection_request, + build_search_indexer_delete_indexer_request, + build_search_indexer_delete_skillset_request, + build_search_indexer_get_data_source_connection_request, + build_search_indexer_get_data_source_connections_request, + build_search_indexer_get_indexer_request, + build_search_indexer_get_indexer_status_request, + build_search_indexer_get_indexers_request, + build_search_indexer_get_skillset_request, + build_search_indexer_get_skillsets_request, + build_search_indexer_reset_documents_request, + build_search_indexer_reset_indexer_request, + build_search_indexer_reset_skills_request, + build_search_indexer_resync_request, + build_search_indexer_run_indexer_request, +) +from .._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class _SearchIndexClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchIndexClientConfiguration] +): + + @overload + async def _create_or_update_synonym_map( + self, + name: str, + synonym_map: _models2.SynonymMap, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: ... + @overload + async def _create_or_update_synonym_map( + self, + name: str, + synonym_map: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: ... + @overload + async def _create_or_update_synonym_map( + self, + name: str, + synonym_map: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: ... + + @distributed_trace_async + async def _create_or_update_synonym_map( + self, + name: str, + synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param name: The name of the synonym map. Required. + :type name: str + :param synonym_map: The definition of the synonym map to create or update. Is one of the + following types: SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_synonym_map_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_synonym_map( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a synonym map. + + :param name: The name of the synonym map. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_synonym_map_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_synonym_map(self, name: str, **kwargs: Any) -> _models2.SynonymMap: + """Retrieves a synonym map definition. + + :param name: The name of the synonym map. Required. + :type name: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + + _request = build_search_index_get_synonym_map_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _get_synonym_maps( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models2._models.ListSynonymMapsResult: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSynonymMapsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.ListSynonymMapsResult] = kwargs.pop("cls", None) + + _request = build_search_index_get_synonym_maps_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListSynonymMapsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_synonym_map( + self, synonym_map: _models2.SynonymMap, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_synonym_map( + self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_synonym_map( + self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_synonym_map( + self, synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Is one of the following types: + SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_synonym_map_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _create_or_update_index( + self, + name: str, + index: _models2.SearchIndex, + *, + allow_index_downtime: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: ... + @overload + async def _create_or_update_index( + self, + name: str, + index: JSON, + *, + allow_index_downtime: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: ... + @overload + async def _create_or_update_index( + self, + name: str, + index: IO[bytes], + *, + allow_index_downtime: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: ... + + @distributed_trace_async + async def _create_or_update_index( + self, + name: str, + index: Union[_models2.SearchIndex, JSON, IO[bytes]], + *, + allow_index_downtime: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param name: The name of the index. Required. + :type name: str + :param index: The definition of the index to create or update. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_index_request( + name=name, + allow_index_downtime=allow_index_downtime, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_index( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a search index and all the documents it contains. This operation is permanent, with no + recovery option. Make sure you have a master copy of your index definition, data ingestion + code, and a backup of the primary data source in case you need to re-build the index. + + :param name: The name of the index. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_index_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_index(self, name: str, **kwargs: Any) -> _models2.SearchIndex: + """Retrieves an index definition. + + :param name: The name of the index. Required. + :type name: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + _request = build_search_index_get_index_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_indexes( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> AsyncItemPaged["_models2.SearchIndex"]: + """Lists all indexes available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: An iterator like instance of SearchIndex + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchIndex]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_indexes_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchIndex], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_index( + self, index: _models2.SearchIndex, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_index( + self, index: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_index( + self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_index( + self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_index_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _get_index_statistics(self, name: str, **kwargs: Any) -> _models2.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. + + :param name: The name of the index. Required. + :type name: str + :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.GetIndexStatisticsResult] = kwargs.pop("cls", None) + + _request = build_search_index_get_index_statistics_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.GetIndexStatisticsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _analyze_text( + self, name: str, request: _models2.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.AnalyzeResult: ... + @overload + async def _analyze_text( + self, name: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.AnalyzeResult: ... + @overload + async def _analyze_text( + self, name: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.AnalyzeResult: ... + + @distributed_trace_async + async def _analyze_text( + self, name: str, request: Union[_models2.AnalyzeTextOptions, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param name: The name of the index. Required. + :type name: str + :param request: The text and analyzer or analysis components to test. Is one of the following + types: AnalyzeTextOptions, JSON, IO[bytes] Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeTextOptions or JSON or IO[bytes] + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.AnalyzeResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_analyze_text_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.AnalyzeResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _create_or_update_alias( + self, + name: str, + alias: _models2.SearchAlias, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: ... + @overload + async def _create_or_update_alias( + self, + name: str, + alias: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: ... + @overload + async def _create_or_update_alias( + self, + name: str, + alias: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: ... + + @distributed_trace_async + async def _create_or_update_alias( + self, + name: str, + alias: Union[_models2.SearchAlias, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param name: The name of the alias. Required. + :type name: str + :param alias: The definition of the alias to create or update. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_alias_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_alias( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. + + :param name: The name of the alias. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_alias_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_alias(self, name: str, **kwargs: Any) -> _models2.SearchAlias: + """Retrieves an alias definition. + + :param name: The name of the alias. Required. + :type name: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + + _request = build_search_index_get_alias_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_aliases(self, **kwargs: Any) -> AsyncItemPaged["_models2.SearchAlias"]: + """Lists all aliases available for a search service. + + :return: An iterator like instance of SearchAlias + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchAlias]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_aliases_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchAlias], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_alias( + self, alias: _models2.SearchAlias, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_alias( + self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_alias( + self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_alias( + self, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_alias_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: _models2.KnowledgeBase, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeBase: ... + @overload + async def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeBase: ... + @overload + async def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeBase: ... + + @distributed_trace_async + async def _create_or_update_knowledge_base( + self, + name: str, + knowledge_base: Union[_models2.KnowledgeBase, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. + + :param name: The name of the knowledge base. Required. + :type name: str + :param knowledge_base: The definition of the knowledge base to create or update. Is one of the + following types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeBase] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base + else: + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_knowledge_base_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_knowledge_base( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a knowledge base. + + :param name: The name of the knowledge base. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_knowledge_base_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_knowledge_base(self, name: str, **kwargs: Any) -> _models2.KnowledgeBase: + """Retrieves a knowledge base definition. + + :param name: The name of the knowledge base. Required. + :type name: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.KnowledgeBase] = kwargs.pop("cls", None) + + _request = build_search_index_get_knowledge_base_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_knowledge_bases(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeBase"]: + """Lists all knowledge bases available for a search service. + + :return: An iterator like instance of KnowledgeBase + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.KnowledgeBase]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_knowledge_bases_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.KnowledgeBase], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_knowledge_base( + self, knowledge_base: _models2.KnowledgeBase, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_knowledge_base( + self, knowledge_base: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_knowledge_base( + self, knowledge_base: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_knowledge_base( + self, knowledge_base: Union[_models2.KnowledgeBase, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Is one of the following + types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeBase] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base + else: + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_knowledge_base_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: _models2.KnowledgeSource, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: ... + @overload + async def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: ... + @overload + async def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: ... + + @distributed_trace_async + async def _create_or_update_knowledge_source( + self, + name: str, + knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param name: The name of the knowledge source. Required. + :type name: str + :param knowledge_source: The definition of the knowledge source to create or update. Is one of + the following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_knowledge_source_request( + name=name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_knowledge_source( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes an existing knowledge source. + + :param name: The name of the knowledge source. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_knowledge_source_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_knowledge_source(self, name: str, **kwargs: Any) -> _models2.KnowledgeSource: + """Retrieves a knowledge source definition. + + :param name: The name of the knowledge source. Required. + :type name: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + + _request = build_search_index_get_knowledge_source_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_knowledge_sources(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeSource"]: + """Lists all knowledge sources available for a search service. + + :return: An iterator like instance of KnowledgeSource + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.KnowledgeSource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_knowledge_sources_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.KnowledgeSource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_knowledge_source( + self, knowledge_source: _models2.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_knowledge_source( + self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_knowledge_source( + self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_knowledge_source( + self, knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Is one of the + following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_knowledge_source_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_knowledge_source_status( + self, name: str, **kwargs: Any + ) -> _knowledgebases_models4.KnowledgeSourceStatus: + """Retrieves the status of a knowledge source. + + :param name: The name of the knowledge source. Required. + :type name: str + :return: KnowledgeSourceStatus. The KnowledgeSourceStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeSourceStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_knowledgebases_models4.KnowledgeSourceStatus] = kwargs.pop("cls", None) + + _request = build_search_index_get_knowledge_source_status_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_knowledgebases_models4.KnowledgeSourceStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceStatistics: + """Gets service level statistics for a search service. + + :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchServiceStatistics] = kwargs.pop("cls", None) + + _request = build_search_index_get_service_statistics_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchServiceStatistics, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: + """Retrieves a summary of statistics for all indexes in the search service. + + :return: An iterator like instance of IndexStatisticsSummary + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.IndexStatisticsSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_index_stats_summary_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.IndexStatisticsSummary], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class _SearchIndexerClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchIndexerClientConfiguration] +): + + @overload + async def _create_or_update_data_source_connection( + self, + name: str, + data_source: _models2.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: ... + @overload + async def _create_or_update_data_source_connection( + self, + name: str, + data_source: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: ... + @overload + async def _create_or_update_data_source_connection( + self, + name: str, + data_source: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: ... + + @distributed_trace_async + async def _create_or_update_data_source_connection( + self, + name: str, + data_source: Union[_models2.SearchIndexerDataSourceConnection, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. + + :param name: The name of the datasource. Required. + :type name: str + :param data_source: The definition of the datasource to create or update. Is one of the + following types: SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or + JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source, (IOBase, bytes)): + _content = data_source + else: + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_or_update_data_source_connection_request( + name=name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerDataSourceConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_data_source_connection( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a datasource. + + :param name: The name of the datasource. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_delete_data_source_connection_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_data_source_connection(self, name: str, **kwargs: Any) -> _models2.SearchIndexerDataSourceConnection: + """Retrieves a datasource definition. + + :param name: The name of the datasource. Required. + :type name: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_data_source_connection_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerDataSourceConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _get_data_source_connections( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models2._models.ListDataSourcesResult: + """Lists all datasources available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListDataSourcesResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.ListDataSourcesResult] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_data_source_connections_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListDataSourcesResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_data_source_connection( + self, + data_source_connection: _models2.SearchIndexerDataSourceConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Required. + :type data_source_connection: + ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_data_source_connection( + self, data_source_connection: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Required. + :type data_source_connection: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_data_source_connection( + self, data_source_connection: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Required. + :type data_source_connection: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_data_source_connection( + self, data_source_connection: Union[_models2.SearchIndexerDataSourceConnection, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source_connection: The definition of the datasource to create. Is one of the + following types: SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source_connection: + ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or JSON or IO[bytes] + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source_connection, (IOBase, bytes)): + _content = data_source_connection + else: + _content = json.dumps(data_source_connection, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_data_source_connection_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerDataSourceConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def reset_indexer(self, name: str, **kwargs: Any) -> None: + """Resets the change tracking state associated with an indexer. + + :param name: The name of the indexer. Required. + :type name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_reset_indexer_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def _resync( + self, + name: str, + indexer_resync: _models2.IndexerResyncBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: ... + @overload + async def _resync( + self, name: str, indexer_resync: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + @overload + async def _resync( + self, name: str, indexer_resync: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def _resync( + self, name: str, indexer_resync: Union[_models2.IndexerResyncBody, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Resync selective options from the datasource to be re-ingested by the indexer.". + + :param name: The name of the indexer. Required. + :type name: str + :param indexer_resync: The definition of the indexer resync options. Is one of the following + types: IndexerResyncBody, JSON, IO[bytes] Required. + :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody or JSON or + IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer_resync, (IOBase, bytes)): + _content = indexer_resync + else: + _content = json.dumps(indexer_resync, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_resync_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def _reset_documents( + self, + name: str, + keys_or_ids: Optional[_models2.DocumentKeysOrIds] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: ... + @overload + async def _reset_documents( + self, + name: str, + keys_or_ids: Optional[JSON] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: ... + @overload + async def _reset_documents( + self, + name: str, + keys_or_ids: Optional[IO[bytes]] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def _reset_documents( + self, + name: str, + keys_or_ids: Optional[Union[_models2.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + *, + overwrite: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param name: The name of the indexer. Required. + :type name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, + IO[bytes] Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or + IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if keys_or_ids else None + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if keys_or_ids else None + _content = None + if isinstance(keys_or_ids, (IOBase, bytes)): + _content = keys_or_ids + else: + if keys_or_ids is not None: + _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + else: + _content = None + + _request = build_search_indexer_reset_documents_request( + name=name, + overwrite=overwrite, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def run_indexer(self, name: str, **kwargs: Any) -> None: + """Runs an indexer on-demand. + + :param name: The name of the indexer. Required. + :type name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_run_indexer_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def _create_or_update_indexer( + self, + name: str, + indexer: _models2.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: ... + @overload + async def _create_or_update_indexer( + self, + name: str, + indexer: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: ... + @overload + async def _create_or_update_indexer( + self, + name: str, + indexer: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: ... + + @distributed_trace_async + async def _create_or_update_indexer( + self, + name: str, + indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param name: The name of the indexer. Required. + :type name: str + :param indexer: The definition of the indexer to create or update. Is one of the following + types: SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_or_update_indexer_request( + name=name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_indexer( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes an indexer. + + :param name: The name of the indexer. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_delete_indexer_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_indexer(self, name: str, **kwargs: Any) -> _models2.SearchIndexer: + """Retrieves an indexer definition. + + :param name: The name of the indexer. Required. + :type name: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_indexer_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _get_indexers( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models2._models.ListIndexersResult: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListIndexersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.ListIndexersResult] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_indexers_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListIndexersResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_indexer( + self, indexer: _models2.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_indexer( + self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_indexer( + self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_indexer( + self, indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Is one of the following types: + SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_indexer_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_indexer_status(self, name: str, **kwargs: Any) -> _models2.SearchIndexerStatus: + """Returns the current status and execution history of an indexer. + + :param name: The name of the indexer. Required. + :type name: str + :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerStatus] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_indexer_status_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _create_or_update_skillset( + self, + name: str, + skillset: _models2.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: ... + @overload + async def _create_or_update_skillset( + self, + name: str, + skillset: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: ... + @overload + async def _create_or_update_skillset( + self, + name: str, + skillset: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: ... + + @distributed_trace_async + async def _create_or_update_skillset( + self, + name: str, + skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param name: The name of the skillset. Required. + :type name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_or_update_skillset_request( + name=name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _delete_skillset( + self, name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any + ) -> None: + """Deletes a skillset in a search service. + + :param name: The name of the skillset. Required. + :type name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_delete_skillset_request( + name=name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_skillset(self, name: str, **kwargs: Any) -> _models2.SearchIndexerSkillset: + """Retrieves a skillset in a search service. + + :param name: The name of the skillset. Required. + :type name: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_skillset_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def _get_skillsets( + self, *, select: Optional[list[str]] = None, **kwargs: Any + ) -> _models2._models.ListSkillsetsResult: + """List all skillsets in a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSkillsetsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.ListSkillsetsResult] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_skillsets_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListSkillsetsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_skillset( + self, skillset: _models2.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_skillset( + self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_skillset( + self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_skillset( + self, skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. Is + one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_skillset_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _reset_skills( + self, name: str, skill_names: _models2.SkillNames, *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + @overload + async def _reset_skills( + self, name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + @overload + async def _reset_skills( + self, name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def _reset_skills( + self, name: str, skill_names: Union[_models2.SkillNames, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param name: The name of the skillset. Required. + :type name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skill_names, (IOBase, bytes)): + _content = skill_names + else: + _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_reset_skills_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py new file mode 100644 index 000000000000..1a698a3a7a36 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -0,0 +1,851 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, cast, List, Sequence, Union, Optional, TYPE_CHECKING + +from azure.core import MatchConditions +from azure.core.async_paging import AsyncItemPaged +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async + +from ... import models as _models +from ._operations import ( + _SearchIndexClientOperationsMixin as _SearchIndexClientOperationsMixinGenerated, + _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, +) + +if TYPE_CHECKING: + import azure.search.documents.aio + + +class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexClient (async).""" + + @distributed_trace_async + async def delete_synonym_map( + self, + synonym_map: Union[str, _models.SynonymMap], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a synonym map. + + :param synonym_map: The name of the synonym map to delete or a SynonymMap object. Required. + :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = synonym_map.name # type: ignore + return await self._delete_synonym_map( + name=name, + match_condition=match_condition, + etag=synonym_map.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = synonym_map # type: ignore + return await self._delete_synonym_map( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_synonym_map( + self, + synonym_map: _models.SynonymMap, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map: The SynonymMap object to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_synonym_map( + name=synonym_map.name, + synonym_map=synonym_map, + prefer="return=representation", + match_condition=match_condition, + etag=synonym_map.e_tag, + **kwargs, + ) + + @distributed_trace_async + async def delete_index( + self, + index: Union[str, _models.SearchIndex], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. + + :param index: The name of the index to delete or a SearchIndex object. Required. + :type index: str or ~azure.search.documents.indexes.models.SearchIndex + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = index.name # type: ignore + return await self._delete_index( + name=name, + match_condition=match_condition, + etag=index.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = index # type: ignore + return await self._delete_index( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_index( + self, + index: _models.SearchIndex, + allow_index_downtime: Optional[bool] = None, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index: The SearchIndex object to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :type allow_index_downtime: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_index( + name=index.name, + index=index, + prefer="return=representation", + allow_index_downtime=allow_index_downtime, + match_condition=match_condition, + etag=index.e_tag, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_alias( + self, + alias: _models.SearchAlias, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias: The SearchAlias object to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_alias( + name=alias.name, + alias=alias, + prefer="return=representation", + match_condition=match_condition, + etag=alias.e_tag, + **kwargs, + ) + + @distributed_trace_async + async def delete_alias( + self, + alias: Union[str, _models.SearchAlias], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias: The name of the alias to delete or a SearchAlias object. Required. + :type alias: str or ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = alias.name # type: ignore + return await self._delete_alias( + name=name, + match_condition=match_condition, + etag=alias.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = alias # type: ignore + return await self._delete_alias( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def delete_knowledge_base( + self, + knowledge_base: Union[str, _models.KnowledgeBase], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a knowledge base. + + :param knowledge_base: The name of the knowledge base to delete or a KnowledgeBase object. Required. + :type knowledge_base: str or ~azure.search.documents.indexes.models.KnowledgeBase + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = knowledge_base.name # type: ignore + return await self._delete_knowledge_base( + name=name, + match_condition=match_condition, + etag=knowledge_base.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = knowledge_base # type: ignore + return await self._delete_knowledge_base( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_knowledge_base( + self, + knowledge_base: _models.KnowledgeBase, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. + + :param knowledge_base: The KnowledgeBase object to create or update. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeBase + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_knowledge_base( + name=knowledge_base.name, + knowledge_base=knowledge_base, + prefer="return=representation", + match_condition=match_condition, + etag=knowledge_base.e_tag, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_knowledge_source( + self, + knowledge_source: _models.KnowledgeSource, + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param knowledge_source: The KnowledgeSource object to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_knowledge_source( + name=knowledge_source.name, + knowledge_source=knowledge_source, + prefer="return=representation", + match_condition=match_condition, + etag=knowledge_source.e_tag, + **kwargs, + ) + + @distributed_trace_async + async def delete_knowledge_source( + self, + knowledge_source: Union[str, _models.KnowledgeSource], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a knowledge source. + + :param knowledge_source: The name of the knowledge source to delete or a KnowledgeSource object. Required. + :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = knowledge_source.name # type: ignore + return await self._delete_knowledge_source( + name=name, + match_condition=match_condition, + etag=knowledge_source.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = knowledge_source # type: ignore + return await self._delete_knowledge_source( + name=name, + **kwargs, + ) + + @distributed_trace + def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: + """Lists the names of all indexes available for a search service. + + :return: An async iterator like instance of index names + :rtype: ~azure.core.async_paging.AsyncItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(AsyncItemPaged[str], names) + + @distributed_trace_async + async def get_synonym_maps(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[_models.SynonymMap]: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties of the synonym maps to retrieve. Specified + as a comma-separated list of JSON property names, or '*' for all properties. The default is + all properties. Default value is None. + :paramtype select: list[str] + :return: List of synonym maps + :rtype: list[~azure.search.documents.indexes.models.SynonymMap] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self._get_synonym_maps(select=select, **kwargs) + assert result.synonym_maps is not None # Hint for mypy + # typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + typed_result = result.synonym_maps + return typed_result + + @distributed_trace_async + async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: + """Lists the names of all synonym maps available for a search service. + + :return: List of synonym map names + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self.get_synonym_maps(**kwargs) + return [x.name for x in result] + + @distributed_trace + def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: + """List the alias names in an Azure Search service. + + :return: List of alias names + :rtype: ~azure.core.async_paging.AsyncItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. + """ + names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(AsyncItemPaged[str], names) + + @distributed_trace_async + async def analyze_text( + self, + index_name: str, + analyze_request: _models.AnalyzeTextOptions, + **kwargs: Any, + ) -> _models.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index to test an analyzer on. Required. + :type index_name: str + :param analyze_request: The text and analyzer or analysis components to test. Required. + :type analyze_request: ~azure.search.documents.indexes.models.AnalyzeTextOptions + :return: AnalyzeResult + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._analyze_text( + name=index_name, + request=analyze_request, + **kwargs, + ) + + @distributed_trace_async + async def get_index_statistics( + self, + index_name: str, + **kwargs: Any, + ) -> _models.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. + + :param index_name: The name of the index to retrieve statistics for. Required. + :type index_name: str + :return: GetIndexStatisticsResult + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._get_index_statistics( + name=index_name, + **kwargs, + ) + + def get_search_client(self, index_name: str, **kwargs: Any) -> "azure.search.documents.aio.SearchClient": + """Return a client to perform operations on Search. + + :param index_name: The name of the index. Required. + :type index_name: str + :return: A SearchClient for operations on the named index. + :rtype: ~azure.search.documents.aio.SearchClient + """ + # pylint: disable=import-outside-toplevel + from ....aio import SearchClient + + return SearchClient( + endpoint=self._config.endpoint, + index_name=index_name, + credential=self._config.credential, + **kwargs, + ) + + +class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexerClient (async).""" + + @distributed_trace_async + async def delete_data_source_connection( + self, + data_source_connection: Union[str, _models.SearchIndexerDataSourceConnection], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a data source connection. + + :param data_source_connection: The name of the data source connection to delete or a SearchIndexerDataSourceConnection object. Required. + :type data_source_connection: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = data_source_connection.name # type: ignore + return await self._delete_data_source_connection( + name=name, + match_condition=match_condition, + etag=data_source_connection.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = data_source_connection # type: ignore + return await self._delete_data_source_connection( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_data_source_connection( + self, + data_source_connection: _models.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source_connection: The SearchIndexerDataSourceConnection object to create or update. Required. + :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_data_source_connection( + name=data_source_connection.name, + data_source=data_source_connection, + prefer="return=representation", + match_condition=match_condition, + etag=data_source_connection.e_tag, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + **kwargs, + ) + + @distributed_trace_async + async def delete_indexer( + self, + indexer: Union[str, _models.SearchIndexer], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes an indexer. + + :param indexer: The name of the indexer to delete or a SearchIndexer object. Required. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = indexer.name # type: ignore + return await self._delete_indexer( + name=name, + match_condition=match_condition, + etag=indexer.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = indexer # type: ignore + return await self._delete_indexer( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_indexer( + self, + indexer: _models.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer: The SearchIndexer object to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_indexer( + name=indexer.name, + indexer=indexer, + prefer="return=representation", + match_condition=match_condition, + etag=indexer.e_tag, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs, + ) + + @distributed_trace_async + async def delete_skillset( + self, + skillset: Union[str, _models.SearchIndexerSkillset], + *, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> None: + """Deletes a skillset. + + :param skillset: The name of the skillset to delete or a SearchIndexerSkillset object. Required. + :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = skillset.name # type: ignore + return await self._delete_skillset( + name=name, + match_condition=match_condition, + etag=skillset.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = skillset # type: ignore + return await self._delete_skillset( + name=name, + **kwargs, + ) + + @distributed_trace_async + async def create_or_update_skillset( + self, + skillset: _models.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, + **kwargs: Any, + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset: The SearchIndexerSkillset object to create or update. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._create_or_update_skillset( + name=skillset.name, + skillset=skillset, + prefer="return=representation", + match_condition=match_condition, + etag=skillset.e_tag, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs, + ) + + @distributed_trace_async + async def get_skillsets( + self, *, select: Optional[List[str]] = None, **kwargs: Any + ) -> List[_models.SearchIndexerSkillset]: + """Lists all skillsets available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: List of all the SearchIndexerSkillsets. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self._get_skillsets(select=select, **kwargs) + assert result.skillsets is not None # Hint for mypy + # typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + typed_result = result.skillsets + return typed_result + + @distributed_trace_async + async def get_indexers(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[_models.SearchIndexer]: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: List of all the SearchIndexers. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self._get_indexers(select=select, **kwargs) + assert result.indexers is not None # Hint for mypy + # typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + typed_result = result.indexers + return typed_result + + @distributed_trace_async + async def get_indexer_names(self, **kwargs) -> Sequence[str]: + """Lists all indexer names available for a search service. + + :return: List of all the SearchIndexer names. + :rtype: list[str] + """ + result = await self.get_indexers(**kwargs) + return [x.name for x in result] + + @distributed_trace_async + async def get_data_source_connections( + self, *, select: Optional[List[str]] = None, **kwargs: Any + ) -> List[_models.SearchIndexerDataSourceConnection]: + """Lists all data source connections available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: list[str] + :return: List of all the data source connections. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self._get_data_source_connections(select=select, **kwargs) + assert result.data_sources is not None # Hint for mypy + # typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + typed_result = result.data_sources + return typed_result + + @distributed_trace_async + async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: + """Lists all data source connection names available for a search service. + + :return: List of all the data source connection names. + :rtype: list[str] + + """ + result = await self.get_data_source_connections(**kwargs) + return [x.name for x in result] + + @distributed_trace_async + async def get_skillset_names(self, **kwargs) -> Sequence[str]: + """List the SearchIndexerSkillset names in an Azure Search service. + + :return: List of SearchIndexerSkillset names + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. + + """ + result = await self.get_skillsets(**kwargs) + return [x.name for x in result] + + @distributed_trace_async + async def reset_documents( + self, + indexer: Union[str, _models.SearchIndexer], + keys_or_ids: _models.DocumentKeysOrIds, + *, + overwrite: bool = False, + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer: The indexer to reset documents for. Can be the indexer name or a SearchIndexer object. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer + :param keys_or_ids: The document keys or ids to reset. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is False. + :paramtype overwrite: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = indexer.name # type: ignore + except AttributeError: + name = indexer # type: ignore + return await self._reset_documents( + name=name, + keys_or_ids=keys_or_ids, + overwrite=overwrite, + **kwargs, + ) + + @distributed_trace_async + async def reset_skills( + self, + skillset: Union[str, _models.SearchIndexerSkillset], + skill_names: List[str], + **kwargs: Any, + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset: The skillset to reset skills for. Can be the skillset name or a SearchIndexerSkillset object. + :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset + :param skill_names: The names of the skills to reset. + :type skill_names: list[str] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = skillset.name # type: ignore + except AttributeError: + name = skillset # type: ignore + return await self._reset_skills( + name=name, + skill_names=_models.SkillNames(skill_names=skill_names), + **kwargs, + ) + + @distributed_trace_async + async def resync( + self, + indexer: Union[str, _models.SearchIndexer], + indexer_resync_options: List[Union[str, _models.IndexerResyncOption]], + **kwargs: Any, + ) -> None: + """Resync selective options from the datasource to be re-ingested by the indexer. + + :param indexer: The indexer to resync. Can be the indexer name or a SearchIndexer object. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer + :param indexer_resync_options: Re-sync options that have been pre-defined from data source. + :type indexer_resync_options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + try: + name: str = indexer.name # type: ignore + except AttributeError: + name = indexer # type: ignore + indexer_resync = _models.IndexerResyncBody(options=indexer_resync_options) + return await self._resync( + name=name, + indexer_resync=indexer_resync, + **kwargs, + ) + + +__all__: list[str] = [ + "_SearchIndexClientOperationsMixin", + "_SearchIndexerClientOperationsMixin", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py deleted file mode 100644 index d3ab23909374..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py +++ /dev/null @@ -1,862 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, Any, List, Optional, MutableMapping, cast - -from azure.core.rest import HttpRequest, AsyncHttpResponse -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.async_paging import AsyncItemPaged -from .._generated.aio import SearchServiceClient as _SearchServiceClient -from ...aio._search_client_async import SearchClient -from .._utils import ( - get_access_conditions, - normalize_endpoint, -) -from ..._api_versions import DEFAULT_VERSION -from ..._headers_mixin import HeadersMixin -from ..._utils import get_authentication_policy -from ..._version import SDK_MONIKER -from ..models import ( - SearchIndex, - SynonymMap, - SearchAlias, - AnalyzeResult, - AnalyzeTextOptions, - IndexStatisticsSummary, - KnowledgeBase, - KnowledgeSource, - KnowledgeSourceStatus, -) - - -class SearchIndexClient(HeadersMixin): # pylint:disable=too-many-public-methods - """A client to interact with Azure search service Indexes. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) - self._credential = credential - self._audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=self._audience, is_async=True) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - async def __aenter__(self) -> "SearchIndexClient": - await self._client.__aenter__() # pylint:disable=no-member - return self - - async def __aexit__(self, *args: Any) -> None: - return await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - def get_search_client(self, index_name: str, **kwargs: Any) -> SearchClient: - """Return a client to perform operations on Search. - - :param index_name: The name of the Search Index - :type index_name: str - :return: SearchClient - :rtype: ~azure.search.documents.aio.SearchClient - """ - return SearchClient( - self._endpoint, - index_name, - self._credential, - audience=self._audience, - api_version=self._api_version, - **kwargs - ) - - @distributed_trace - def list_indexes(self, *, select: Optional[List[str]] = None, **kwargs) -> AsyncItemPaged[SearchIndex]: - """List the indexes in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of indexes - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - indexes = self._client.indexes.list(cls=lambda objs: [SearchIndex._from_generated(x) for x in objs], **kwargs) - return cast(AsyncItemPaged[SearchIndex], indexes) - - @distributed_trace - def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: - """List the index names in an Azure Search service. - - :return: List of index names - :rtype: ~azure.core.async_paging.AsyncItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.indexes.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(AsyncItemPaged[str], names) - - @distributed_trace_async - async def get_index(self, name: str, **kwargs: Any) -> SearchIndex: - """Retrieve a named index in an Azure Search service - - :param name: The name of the index to retrieve. - :type name: str - :return: SearchIndex object - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_async.py - :start-after: [START get_index_async] - :end-before: [END get_index_async] - :language: python - :dedent: 4 - :caption: Get an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexes.get(name, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_index_statistics(self, index_name: str, **kwargs: Any) -> MutableMapping[str, Any]: - """Returns statistics for the given index, including a document count - and storage usage. - - :param index_name: The name of the index to retrieve. - :type index_name: str - :return: Statistics for the given index, including a document count and storage usage. - :rtype: Dict - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexes.get_statistics(index_name, **kwargs) - return result.as_dict() - - @distributed_trace_async - async def delete_index( - self, - index: Union[str, SearchIndex], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. The model must be - provided instead of the name to use the access conditions - - :param index: The index name or object to delete. - :type index: str or ~azure.search.documents.indexes.models.SearchIndex - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_async.py - :start-after: [START delete_index_async] - :end-before: [END delete_index_async] - :language: python - :dedent: 4 - :caption: Delete an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - try: - index_name = index.name # type: ignore - except AttributeError: - index_name = index - await self._client.indexes.delete(index_name=index_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_index(self, index: SearchIndex, **kwargs: Any) -> SearchIndex: - """Creates a new search index. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :return: The index created - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_async.py - :start-after: [START create_index_async] - :end-before: [END create_index_async] - :language: python - :dedent: 4 - :caption: Creating a new index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_index = index._to_generated() # pylint:disable=protected-access - result = await self._client.indexes.create(patched_index, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_index( - self, - index: SearchIndex, - allow_index_downtime: Optional[bool] = None, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. - :type allow_index_downtime: bool - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index has not been modified. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index is not found. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_async.py - :start-after: [START update_index_async] - :end-before: [END update_index_async] - :language: python - :dedent: 4 - :caption: Update an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - patched_index = index._to_generated() # pylint:disable=protected-access - result = await self._client.indexes.create_or_update( - index_name=index.name, - index=patched_index, - allow_index_downtime=allow_index_downtime, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def analyze_text(self, index_name: str, analyze_request: AnalyzeTextOptions, **kwargs: Any) -> AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index for which to test an analyzer. - :type index_name: str - :param analyze_request: The text and analyzer or analysis components to test. - :type analyze_request: ~azure.search.documents.indexes.models.AnalyzeTextOptions - :return: AnalyzeResult - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_analyze_text_async.py - :start-after: [START simple_analyze_text_async] - :end-before: [END simple_analyze_text_async] - :language: python - :dedent: 4 - :caption: Analyze text - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexes.analyze( - index_name=index_name, - request=analyze_request._to_analyze_request(), # pylint:disable=protected-access - **kwargs - ) - return result - - @distributed_trace_async - async def get_synonym_maps(self, *, select: Optional[List[str]] = None, **kwargs) -> List[SynonymMap]: - """List the Synonym Maps in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: List[str] - :return: List of synonym maps - :rtype: List[~azure.search.documents.indexes.models.SynonymMap] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_synonym_map_crud_async.py - :start-after: [START get_synonym_maps_async] - :end-before: [END get_synonym_maps_async] - :language: python - :dedent: 4 - :caption: List Synonym Maps - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SynonymMap, SynonymMap._from_generated(x)) for x in result.synonym_maps] - - @distributed_trace_async - async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: - """List the Synonym Map names in an Azure Search service. - - :return: List of synonym map names - :rtype: List[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - return [x.name for x in result.synonym_maps] - - @distributed_trace_async - async def get_synonym_map(self, name: str, **kwargs: Any) -> SynonymMap: - """Retrieve a named Synonym Map in an Azure Search service - - :param name: The name of the Synonym Map to get - :type name: str - :return: The retrieved Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.ResourceNotFoundError: If the Synonym Map doesn't exist. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_synonym_map_crud_async.py - :start-after: [START get_synonym_map_async] - :end-before: [END get_synonym_map_async] - :language: python - :dedent: 4 - :caption: Get a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.synonym_maps.get(name, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def delete_synonym_map( - self, - synonym_map: Union[str, SynonymMap], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named Synonym Map in an Azure Search service. To use access conditions, - the SynonymMap model must be provided instead of the name. It is enough to provide - the name of the synonym map to delete unconditionally. - - :param synonym_map: The synonym map name or object to delete - :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_synonym_map_crud_async.py - :start-after: [START delete_synonym_map_async] - :end-before: [END delete_synonym_map_async] - :language: python - :dedent: 4 - :caption: Delete a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - try: - name = synonym_map.name # type: ignore - except AttributeError: - name = synonym_map - await self._client.synonym_maps.delete(synonym_map_name=name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_synonym_map(self, synonym_map: SynonymMap, **kwargs: Any) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :return: The created Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_synonym_map_crud_async.py - :start-after: [START create_synonym_map_async] - :end-before: [END create_synonym_map_async] - :language: python - :dedent: 4 - :caption: Create a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = await self._client.synonym_maps.create(patched_synonym_map, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_synonym_map( - self, - synonym_map: SynonymMap, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service, or update an - existing one. - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The created or updated Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = await self._client.synonym_maps.create_or_update( - synonym_map_name=synonym_map.name, - synonym_map=patched_synonym_map, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_service_statistics(self, **kwargs) -> MutableMapping[str, Any]: - """Get service level statistics for a search service. - - :return: Service statistics result - :rtype: dict - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.get_service_statistics(**kwargs) - return result.as_dict() - - @distributed_trace - def list_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged[IndexStatisticsSummary]: - """Get index level statistics for a search service. - - :return: Index statistics result. - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - result = self._client.get_index_stats_summary(**kwargs) - return cast(AsyncItemPaged[IndexStatisticsSummary], result) - - @distributed_trace - def list_aliases(self, *, select: Optional[List[str]] = None, **kwargs) -> AsyncItemPaged[SearchAlias]: - """List the aliases in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of Aliases - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - return cast(AsyncItemPaged[SearchAlias], self._client.aliases.list(**kwargs)) - - @distributed_trace - def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: - """List the alias names in an Azure Search service. - - :return: List of alias names - :rtype: ~azure.core.async_paging.AsyncItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.aliases.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(AsyncItemPaged[str], names) - - @distributed_trace_async - async def get_alias(self, name: str, **kwargs) -> SearchAlias: - """Retrieve a named alias in an Azure Search service - - :param name: The name of the alias to retrieve. - :type name: str - :return: SearchAlias object - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.aliases.get(name, **kwargs) - return result - - @distributed_trace_async - async def delete_alias( - self, - alias: Union[str, SearchAlias], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. - This operation is permanent, with no recovery option. The mapped index is untouched by this operation - - :param alias: The alias name or object to delete. - :type alias: str or ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_alias_crud_async.py - :start-after: [START delete_alias_async] - :end-before: [END delete_alias_async] - :language: python - :dedent: 4 - :caption: Delete an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - try: - alias_name = alias.name # type: ignore - except AttributeError: - alias_name = alias - await self._client.aliases.delete(alias_name=alias_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: - """Creates a new search alias. - - :param alias: The alias object. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :return: The alias created - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_alias_crud_async.py - :start-after: [START create_alias_async] - :end-before: [END create_alias_async] - :language: python - :dedent: 4 - :caption: Create an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.aliases.create(alias, **kwargs) - return result # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_alias( - self, alias: SearchAlias, *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any - ) -> SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias: The definition of the alias to create or update. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the alias has been modified. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the alias has not been modified. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias is not found. - :raises ~azure.core.exceptions.ResourceExistsError: If the alias already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_alias_crud_async.py - :start-after: [START update_alias_async] - :end-before: [END update_alias_async] - :language: python - :dedent: 4 - :caption: Update an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - result = await self._client.aliases.create_or_update( - alias_name=alias.name, alias=alias, prefer="return=representation", error_map=error_map, **kwargs - ) - return result # pylint:disable=protected-access - - @distributed_trace_async - async def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> AsyncHttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return await self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access - - @distributed_trace_async - async def delete_knowledge_base( - self, - knowledge_base: Union[str, KnowledgeBase], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge base. - - :param knowledge_base: The knowledge base name or object to delete. - :type knowledge_base: str or ~azure.search.documents.indexes.models.KnowledgeBase - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_base, match_condition) - kwargs.update(access_condition) - try: - knowledge_base_name = knowledge_base.name # type: ignore - except AttributeError: - knowledge_base_name = knowledge_base - await self._client.knowledge_bases.delete( - knowledge_base_name=knowledge_base_name, error_map=error_map, **kwargs - ) - - @distributed_trace_async - async def create_knowledge_base(self, knowledge_base: KnowledgeBase, **kwargs: Any) -> KnowledgeBase: - """Creates a new knowledge base. - - :param knowledge_base: The knowledge base object. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :return: The knowledge base created - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_bases.create(knowledge_base, **kwargs) - return result - - @distributed_trace_async - async def create_or_update_knowledge_base( - self, - knowledge_base: KnowledgeBase, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeBase: - """Creates a new knowledge base or updates one if it already exists. - - :param knowledge_base: The knowledge base object. - :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The knowledge base created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.ResourceNotFoundError: If the knowledge base doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the knowledge base has been modified on the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the knowledge base hasn't been - modified on the server. - :raises ~azure.core.exceptions.ResourceExistsError: If the knowledge base already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_base, match_condition) - kwargs.update(access_condition) - result = await self._client.knowledge_bases.create_or_update( - knowledge_base_name=knowledge_base.name, - knowledge_base=knowledge_base, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return result - - @distributed_trace_async - async def get_knowledge_base(self, name: str, **kwargs: Any) -> KnowledgeBase: - """Gets a knowledge base definition. - - :param name: The name of the knowledge base to retrieve. - :type name: str - :return: KnowledgeBase object - :rtype: ~azure.search.documents.indexes.models.KnowledgeBase - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_bases.get(knowledge_base_name=name, **kwargs) - return result - - @distributed_trace - def list_knowledge_bases(self, **kwargs: Any) -> AsyncItemPaged[KnowledgeBase]: - """List the knowledge bases in an Azure Search service. - - :return: List of knowledge bases - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(AsyncItemPaged[KnowledgeBase], self._client.knowledge_bases.list(**kwargs)) - - @distributed_trace_async - async def delete_knowledge_source( - self, - knowledge_source: Union[str, KnowledgeSource], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param knowledge_source: The knowledge source name or object to delete. - :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - try: - source_name = knowledge_source.name # type: ignore - except AttributeError: - source_name = knowledge_source - await self._client.knowledge_sources.delete(source_name=source_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: Any) -> KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :return: The knowledge source created - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_sources.create(knowledge_source, **kwargs) - return result - - @distributed_trace_async - async def create_or_update_knowledge_source( - self, - knowledge_source: KnowledgeSource, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeSource: - """Creates a new knowledge source or updates an existing one. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The knowledge source created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - result = await self._client.knowledge_sources.create_or_update( - source_name=knowledge_source.name, - knowledge_source=knowledge_source, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return result - - @distributed_trace_async - async def get_knowledge_source(self, name: str, **kwargs: Any) -> KnowledgeSource: - """ - - :param name: The name of the knowledge source to retrieve. - :type name: str - :return: KnowledgeSource object - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_sources.get(name, **kwargs) - return result - - @distributed_trace_async - async def get_knowledge_source_status(self, name: str, **kwargs: Any) -> KnowledgeSourceStatus: - """Returns the current status and synchronization history of a knowledge source. - - :param name: The name of the knowledge source for which to retrieve status. - :type name: str - :return: KnowledgeSourceStatus object - :rtype: ~azure.search.documents.indexes.models.KnowledgeSourceStatus - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_sources.get_status(source_name=name, **kwargs) - return result - - @distributed_trace - def list_knowledge_sources(self, **kwargs: Any) -> AsyncItemPaged[KnowledgeSource]: - """List the knowledge sources in an Azure Search service. - - :return: List of Knowledge Sources - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(AsyncItemPaged[KnowledgeSource], self._client.knowledge_sources.list(**kwargs)) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py deleted file mode 100644 index b984ba1c8ce8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py +++ /dev/null @@ -1,691 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, Any, Optional, Sequence, List, cast - -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator_async import distributed_trace_async - -from .._generated.aio import SearchServiceClient as _SearchServiceClient -from .._generated.models import ( - SkillNames, - SearchIndexerStatus, - DocumentKeysOrIds, - IndexerResyncOption, - IndexerResyncBody, -) -from ..models import SearchIndexer, SearchIndexerSkillset, SearchIndexerDataSourceConnection -from .._utils import ( - get_access_conditions, - normalize_endpoint, -) -from ..._api_versions import DEFAULT_VERSION -from ..._headers_mixin import HeadersMixin -from ..._utils import get_authentication_policy -from ..._version import SDK_MONIKER - - -class SearchIndexerClient(HeadersMixin): # pylint: disable=R0904 - """A client to interact with Azure search service Indexers. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) # type: str - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - async def __aenter__(self) -> "SearchIndexerClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *args) -> None: - return await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - @distributed_trace_async - async def create_indexer(self, indexer: SearchIndexer, **kwargs: Any) -> SearchIndexer: - """Creates a new SearchIndexer. - - :param indexer: The definition of the indexer to create. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START create_indexer_async] - :end-before: [END create_indexer_async] - :language: python - :dedent: 4 - :caption: Create a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = await self._client.indexers.create(patched_indexer, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_indexer( - self, - indexer: SearchIndexer, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexer: - """Creates a new indexer or updates a indexer if it already exists. - - :param indexer: The definition of the indexer to create or update. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - name = indexer.name - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = await self._client.indexers.create_or_update( - indexer_name=name, - indexer=patched_indexer, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_indexer(self, name: str, **kwargs: Any) -> SearchIndexer: - """Retrieves a indexer definition. - - :param name: The name of the indexer to retrieve. - :type name: str - :return: The SearchIndexer that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START get_indexer_async] - :end-before: [END get_indexer_async] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexers.get(name, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_indexers(self, *, select: Optional[List[str]] = None, **kwargs) -> Sequence[SearchIndexer]: - """Lists all indexers available for a search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of all the SearchIndexers. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START list_indexers_async] - :end-before: [END list_indexers_async] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SearchIndexer, SearchIndexer._from_generated(index)) for index in result.indexers] - - @distributed_trace_async - async def get_indexer_names(self, **kwargs) -> Sequence[str]: - """Lists all indexer names available for a search service. - - :return: List of all the SearchIndexer names. - :rtype: list[str] - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - return [x.name for x in result.indexers] - - @distributed_trace_async - async def delete_indexer( - self, - indexer: Union[str, SearchIndexer], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an indexer. To use access conditions, the SearchIndexer model - must be provided instead of the name. It is enough to provide - the name of the indexer to delete unconditionally. - - :param indexer: The name or the indexer object to delete. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START delete_indexer_async] - :end-before: [END delete_indexer_async] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - await self._client.indexers.delete(name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def run_indexer(self, name: str, **kwargs: Any) -> None: - """Run an indexer. - - :param name: The name of the indexer to run. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START run_indexer_async] - :end-before: [END run_indexer_async] - :language: python - :dedent: 4 - :caption: Run a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - await self._client.indexers.run(name, **kwargs) - - @distributed_trace_async - async def reset_indexer(self, name: str, **kwargs: Any) -> None: - """Resets the change tracking state associated with an indexer. - - :param name: The name of the indexer to reset. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START reset_indexer_async] - :end-before: [END reset_indexer_async] - :language: python - :dedent: 4 - :caption: Reset a SearchIndexer's change tracking state - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - await self._client.indexers.reset(name, **kwargs) - - @distributed_trace_async - async def reset_documents( - self, - indexer: Union[str, SearchIndexer], - keys_or_ids: DocumentKeysOrIds, - *, - overwrite: bool = False, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - :param indexer: The indexer to reset documents for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param keys_or_ids: - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :return: None, or the result of cls(response) - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. The default is false. - :paramtype overwrite: bool - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["keys_or_ids"] = keys_or_ids - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - await self._client.indexers.reset_docs(name, overwrite=overwrite, **kwargs) - return - - @distributed_trace_async - async def resync( - self, - indexer: Union[str, SearchIndexer], - indexer_resync_options: List[Union[str, IndexerResyncOption]], - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - :param indexer: The indexer to resync for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param indexer_resync_options: Required. - :type indexer_resync_options: list[str or - ~azure.search.documents.indexes.models.IndexerResyncOption] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - - # Create IndexerResyncBody from the list of options - resync_body = IndexerResyncBody(options=indexer_resync_options) - await self._client.indexers.resync(name, resync_body, **kwargs) - return - - @distributed_trace_async - async def get_indexer_status(self, name: str, **kwargs: Any) -> SearchIndexerStatus: - """Get the status of the indexer. - - :param name: The name of the indexer to fetch the status. - :type name: str - - :return: SearchIndexerStatus - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_crud_async.py - :start-after: [START get_indexer_status_async] - :end-before: [END get_indexer_status_async] - :language: python - :dedent: 4 - :caption: Get a SearchIndexer's status - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return await self._client.indexers.get_status(name, **kwargs) - - @distributed_trace_async - async def create_data_source_connection( - self, data_source_connection: SearchIndexerDataSourceConnection, **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection. - - :param data_source_connection: The definition of the data source connection to create. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_datasource_crud_async.py - :start-after: [START create_data_source_connection_async] - :end-before: [END create_data_source_connection_async] - :language: python - :dedent: 4 - :caption: Create a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - packed_data_source = data_source_connection._to_generated() - result = await self._client.data_sources.create(packed_data_source, **kwargs) - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace_async - async def create_or_update_data_source_connection( - self, - data_source_connection: SearchIndexerDataSourceConnection, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_connection: The definition of the data source connection to create or update. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions( - data_source_connection, - match_condition, - ) - kwargs.update(access_condition) - name = data_source_connection.name - # pylint:disable=protected-access - packed_data_source = data_source_connection._to_generated() - result = await self._client.data_sources.create_or_update( - data_source_name=name, - data_source=packed_data_source, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - **kwargs - ) - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace_async - async def delete_data_source_connection( - self, - data_source_connection: Union[str, SearchIndexerDataSourceConnection], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a data source connection. To use access conditions, the - SearchIndexerDataSourceConnection model must be provided instead of the name. - It is enough to provide the name of the data source connection to delete unconditionally - - :param data_source_connection: The data source connection to delete. - :type data_source_connection: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_datasource_crud_async.py - :start-after: [START delete_data_source_connection_async] - :end-before: [END delete_data_source_connection_async] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions( - data_source_connection, - match_condition, - ) - kwargs.update(access_condition) - try: - name = data_source_connection.name # type: ignore - except AttributeError: - name = data_source_connection - await self._client.data_sources.delete(data_source_name=name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def get_data_source_connection( - self, name: str, *, select: Optional[List[str]] = None, **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Retrieves a data source connection definition. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :param name: The name of the data source connection to retrieve. - :type name: str - :return: The SearchIndexerDataSourceConnection that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_datasource_crud_async.py - :start-after: [START get_data_source_connection_async] - :end-before: [END get_data_source_connection_async] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.data_sources.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace_async - async def get_data_source_connections(self, **kwargs: Any) -> Sequence[SearchIndexerDataSourceConnection]: - """Lists all data source connections available for a search service. - - :return: List of all the data source connections. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexer_datasource_crud_async.py - :start-after: [START list_data_source_connections_async] - :end-before: [END list_data_source_connections_async] - :language: python - :dedent: 4 - :caption: List all SearchIndexerDataSourceConnections - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - # pylint:disable=protected-access - return [ - cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(x)) - for x in result.data_sources - ] - - @distributed_trace_async - async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: - """Lists all data source connection names available for a search service. - - :return: List of all the data source connection names. - :rtype: list[str] - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - return [x.name for x in result.data_sources] - - @distributed_trace_async - async def get_skillsets(self, *, select: Optional[List[str]] = None, **kwargs) -> List[SearchIndexerSkillset]: - # pylint:disable=protected-access - """List the SearchIndexerSkillsets in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of SearchIndexerSkillsets - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [ - cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(skillset)) - for skillset in result.skillsets - ] - - @distributed_trace_async - async def get_skillset_names(self, **kwargs) -> List[str]: - """List the SearchIndexerSkillset names in an Azure Search service. - - :return: List of SearchIndexerSkillset names - :rtype: list[str] - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [x.name for x in result.skillsets] - - @distributed_trace_async - async def get_skillset(self, name: str, **kwargs) -> SearchIndexerSkillset: - """Retrieve a named SearchIndexerSkillset in an Azure Search service - - :param name: The name of the SearchIndexerSkillset to get - :type name: str - :return: The retrieved SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.ResourceNotFoundError: If the skillset doesn't exist. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.skillsets.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace_async - async def delete_skillset( - self, - skillset: Union[str, SearchIndexerSkillset], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named SearchIndexerSkillset in an Azure Search service. To use access conditions, - the SearchIndexerSkillset model must be provided instead of the name. It is enough to provide - the name of the skillset to delete unconditionally - - :param skillset: The SearchIndexerSkillset to delete - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - await self._client.skillsets.delete(name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_skillset(self, skillset: SearchIndexerSkillset, **kwargs: Any) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service - - :param skillset: The SearchIndexerSkillset object to create - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :return: The created SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - result = await self._client.skillsets.create(skillset_gen, **kwargs) # type: ignore - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace_async - async def create_or_update_skillset( - self, - skillset: SearchIndexerSkillset, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service, or update an - existing one. - - :param skillset: The SearchIndexerSkillset object to create or update - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created or updated SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - - result = await self._client.skillsets.create_or_update( - skillset_name=skillset.name, - skillset=skillset_gen, # type: ignore - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace_async - async def reset_skills(self, skillset: Union[str, SearchIndexerSkillset], skill_names: List[str], **kwargs) -> None: - """Reset an existing skillset in a search service. - - :param skillset: The SearchIndexerSkillset to reset - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param skill_names: the names of skills to be reset. - :type skill_names: List[str] - :return: None, or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - names = SkillNames(skill_names=skill_names) - await self._client.skillsets.reset_skills(skillset_name=name, skill_names=names, **kwargs) - return diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py index 0b979e44658b..bebb2d41130c 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py @@ -1,92 +1,60 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._index import ( - ComplexField, - SearchField, - SearchableField, - SimpleField, - SearchIndex, -) -from . import _edm -from ..._generated.models import SuggestOptions -from .._generated.models import ( - SearchAlias, - AIServices, +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore AIServicesAccountIdentity, AIServicesAccountKey, AIServicesVisionParameters, AIServicesVisionVectorizer, - AIFoundryModelCatalogName, - AzureMachineLearningParameters, - AzureMachineLearningSkill, - AzureMachineLearningVectorizer, AnalyzeResult, + AnalyzeTextOptions, AnalyzedTokenInfo, AsciiFoldingTokenFilter, + AzureActiveDirectoryApplicationCredentials, AzureBlobKnowledgeSource, AzureBlobKnowledgeSourceParameters, + AzureMachineLearningParameters, + AzureMachineLearningSkill, + AzureMachineLearningVectorizer, AzureOpenAIEmbeddingSkill, AzureOpenAITokenizerParameters, - AzureOpenAIModelName, - AzureOpenAIVectorizerParameters, AzureOpenAIVectorizer, - BinaryQuantizationCompression, - BlobIndexerDataToExtract, - BlobIndexerImageAction, - BlobIndexerParsingMode, - BlobIndexerPDFTextRotationAlgorithm, + AzureOpenAIVectorizerParameters, BM25SimilarityAlgorithm, + BinaryQuantizationCompression, CharFilter, - CharFilterName, - ChatCompletionExtraParametersBehavior, + ChatCompletionCommonModelParameters, ChatCompletionResponseFormat, - ChatCompletionResponseFormatJsonSchemaProperties, - ChatCompletionResponseFormatType, ChatCompletionSchema, + ChatCompletionSchemaProperties, ChatCompletionSkill, CjkBigramTokenFilter, - CjkBigramTokenFilterScripts, - ContentUnderstandingSkillChunkingUnit, - ContentUnderstandingSkillExtractionOptions, ClassicSimilarityAlgorithm, ClassicTokenizer, CognitiveServicesAccount, CognitiveServicesAccountKey, CommonGramTokenFilter, - CommonModelParameters, - CompletedSynchronizationState, ConditionalSkill, ContentUnderstandingSkill, ContentUnderstandingSkillChunkingProperties, CorsOptions, + CreatedResources, + CustomAnalyzer, CustomEntity, CustomEntityAlias, CustomEntityLookupSkill, - CustomEntityLookupSkillLanguage, CustomNormalizer, DataChangeDetectionPolicy, DataDeletionDetectionPolicy, @@ -98,19 +66,13 @@ DocumentExtractionSkill, DocumentIntelligenceLayoutSkill, DocumentIntelligenceLayoutSkillChunkingProperties, - DocumentIntelligenceLayoutSkillChunkingUnit, - DocumentIntelligenceLayoutSkillExtractionOptions, - DocumentIntelligenceLayoutSkillMarkdownHeaderDepth, - DocumentIntelligenceLayoutSkillOutputFormat, - DocumentIntelligenceLayoutSkillOutputMode, DocumentKeysOrIds, EdgeNGramTokenFilter, + EdgeNGramTokenFilterV2, EdgeNGramTokenizer, - EdgeNGramTokenFilterSide, ElisionTokenFilter, - EntityCategory, EntityLinkingSkill, - EntityRecognitionSkillLanguage, + EntityRecognitionSkillV3, ExhaustiveKnnAlgorithmConfiguration, ExhaustiveKnnParameters, FieldMapping, @@ -119,116 +81,82 @@ FreshnessScoringParameters, GetIndexStatisticsResult, HighWaterMarkChangeDetectionPolicy, - HnswParameters, HnswAlgorithmConfiguration, + HnswParameters, ImageAnalysisSkill, - ImageAnalysisSkillLanguage, - ImageDetail, + IndexStatisticsSummary, + IndexedOneLakeKnowledgeSource, + IndexedOneLakeKnowledgeSourceParameters, + IndexedSharePointKnowledgeSource, + IndexedSharePointKnowledgeSourceParameters, IndexerCurrentState, - IndexerExecutionEnvironment, IndexerExecutionResult, IndexerResyncBody, IndexerRuntime, - IndexerExecutionStatus, - IndexerPermissionOption, - IndexerResyncOption, - IndexerStatus, - IndexingMode, IndexingParameters, IndexingParametersConfiguration, IndexingSchedule, - IndexProjectionMode, - IndexedSharePointContainerName, - IndexStatisticsSummary, - IndexedOneLakeKnowledgeSource, - IndexedOneLakeKnowledgeSourceParameters, - IndexedSharePointKnowledgeSource, - IndexedSharePointKnowledgeSourceParameters, InputFieldMappingEntry, KeepTokenFilter, KeyPhraseExtractionSkill, - KeyPhraseExtractionSkillLanguage, KeywordMarkerTokenFilter, + KeywordTokenizer, KeywordTokenizerV2, KnowledgeBase, KnowledgeBaseAzureOpenAIModel, KnowledgeBaseModel, - KnowledgeBaseModelKind, - KnowledgeRetrievalLowReasoningEffort, - KnowledgeRetrievalMediumReasoningEffort, - KnowledgeRetrievalMinimalReasoningEffort, - KnowledgeRetrievalReasoningEffort, - KnowledgeRetrievalOutputMode, - KnowledgeRetrievalReasoningEffortKind, KnowledgeSource, - KnowledgeSourceAzureOpenAIVectorizer, - KnowledgeSourceIngestionParameters, - KnowledgeSourceContentExtractionMode, - KnowledgeSourceIngestionPermissionOption, - KnowledgeSourceKind, KnowledgeSourceReference, - KnowledgeSourceStatistics, - KnowledgeSourceStatus, - KnowledgeSourceSynchronizationStatus, - KnowledgeSourceVectorizer, LanguageDetectionSkill, LengthTokenFilter, LexicalAnalyzer, LexicalNormalizer, - LexicalNormalizerName, - LexicalAnalyzerName, LexicalTokenizer, - LexicalTokenizerName, LimitTokenFilter, LuceneStandardAnalyzer, LuceneStandardTokenizer, + LuceneStandardTokenizerV2, MagnitudeScoringFunction, MagnitudeScoringParameters, - MarkdownHeaderDepth, - MarkdownParsingSubmode, MappingCharFilter, MergeSkill, MicrosoftLanguageStemmingTokenizer, MicrosoftLanguageTokenizer, - MicrosoftStemmingTokenizerLanguage, - MicrosoftTokenizerLanguage, - NativeBlobSoftDeleteDeletionDetectionPolicy, NGramTokenFilter, + NGramTokenFilterV2, NGramTokenizer, - OcrLineEnding, + NativeBlobSoftDeleteDeletionDetectionPolicy, OcrSkill, - OcrSkillLanguage, OutputFieldMappingEntry, + PIIDetectionSkill, PathHierarchyTokenizerV2, + PatternAnalyzer, PatternCaptureTokenFilter, PatternReplaceCharFilter, PatternReplaceTokenFilter, - PhoneticEncoder, + PatternTokenizer, PhoneticTokenFilter, RemoteSharePointKnowledgeSource, RemoteSharePointKnowledgeSourceParameters, - PIIDetectionSkill, - PIIDetectionSkillMaskingMode, - PermissionFilter, - RankingOrder, - RegexFlags, RescoringOptions, ResourceCounter, ScalarQuantizationCompression, ScalarQuantizationParameters, ScoringFunction, - ScoringFunctionAggregation, - ScoringFunctionInterpolation, ScoringProfile, + SearchAlias, + SearchField, + SearchIndex, SearchIndexFieldReference, SearchIndexKnowledgeSource, SearchIndexKnowledgeSourceParameters, + SearchIndexer, SearchIndexerCache, SearchIndexerDataContainer, SearchIndexerDataIdentity, SearchIndexerDataNoneIdentity, + SearchIndexerDataSourceConnection, SearchIndexerDataUserAssignedIdentity, - SearchIndexerDataSourceType, SearchIndexerError, SearchIndexerIndexProjection, SearchIndexerIndexProjectionSelector, @@ -237,14 +165,16 @@ SearchIndexerKnowledgeStoreBlobProjectionSelector, SearchIndexerKnowledgeStoreFileProjectionSelector, SearchIndexerKnowledgeStoreObjectProjectionSelector, + SearchIndexerKnowledgeStoreParameters, SearchIndexerKnowledgeStoreProjection, SearchIndexerKnowledgeStoreProjectionSelector, SearchIndexerKnowledgeStoreTableProjectionSelector, SearchIndexerLimits, SearchIndexerSkill, + SearchIndexerSkillset, SearchIndexerStatus, SearchIndexerWarning, - SearchIndexPermissionFilterOption, + SearchResourceEncryptionKey, SearchServiceCounters, SearchServiceLimits, SearchServiceStatistics, @@ -253,54 +183,37 @@ SemanticField, SemanticPrioritizedFields, SemanticSearch, - SentimentSkillLanguage, + SentimentSkillV3, ServiceIndexersRuntime, ShaperSkill, ShingleTokenFilter, SimilarityAlgorithm, SkillNames, SnowballTokenFilter, - SnowballTokenFilterLanguage, SoftDeleteColumnDeletionDetectionPolicy, - SplitSkillEncoderModelName, SplitSkill, - SplitSkillLanguage, - SplitSkillUnit, SqlIntegratedChangeTrackingPolicy, StemmerOverrideTokenFilter, StemmerTokenFilter, - StemmerTokenFilterLanguage, StopAnalyzer, - StopwordsList, StopwordsTokenFilter, - SynchronizationState, + SynonymMap, SynonymTokenFilter, TagScoringFunction, TagScoringParameters, - TextSplitMode, TextTranslationSkill, - TextTranslationSkillLanguage, TextWeights, - TokenCharacterKind, TokenFilter, - TokenFilterName, TruncateTokenFilter, UaxUrlEmailTokenizer, UniqueTokenFilter, - VectorEncodingFormat, VectorSearch, VectorSearchAlgorithmConfiguration, - VectorSearchAlgorithmKind, - VectorSearchAlgorithmMetric, VectorSearchCompression, - VectorSearchCompressionKind, - VectorSearchCompressionRescoreStorageMethod, - VectorSearchCompressionTarget, VectorSearchProfile, VectorSearchVectorizer, - VectorSearchVectorizerKind, - VisualFeature, VisionVectorizeSkill, + WebApiHttpHeaders, WebApiSkill, WebApiVectorizer, WebApiVectorizerParameters, @@ -310,91 +223,128 @@ WebKnowledgeSourceParameters, WordDelimiterTokenFilter, ) -from ._models import ( - AnalyzeTextOptions, - CustomAnalyzer, - EntityRecognitionSkill, - EntityRecognitionSkillVersion, - PatternAnalyzer, - PatternTokenizer, - SearchIndexer, - SearchIndexerDataSourceConnection, - SearchIndexerSkillset, - SearchResourceEncryptionKey, - SentimentSkill, - SentimentSkillVersion, - SynonymMap, -) - -SearchFieldDataType = _edm - - -class KeywordTokenizer(KeywordTokenizerV2): - pass - - -class PathHierarchyTokenizer(PathHierarchyTokenizerV2): - pass +from ._enums import ( # type: ignore + AIFoundryModelCatalogName, + AzureOpenAIModelName, + BlobIndexerDataToExtract, + BlobIndexerImageAction, + BlobIndexerPDFTextRotationAlgorithm, + BlobIndexerParsingMode, + CharFilterName, + ChatCompletionExtraParametersBehavior, + ChatCompletionResponseFormatType, + CjkBigramTokenFilterScripts, + ContentUnderstandingSkillChunkingUnit, + ContentUnderstandingSkillExtractionOptions, + CustomEntityLookupSkillLanguage, + DocumentIntelligenceLayoutSkillChunkingUnit, + DocumentIntelligenceLayoutSkillExtractionOptions, + DocumentIntelligenceLayoutSkillMarkdownHeaderDepth, + DocumentIntelligenceLayoutSkillOutputFormat, + DocumentIntelligenceLayoutSkillOutputMode, + EdgeNGramTokenFilterSide, + ImageAnalysisSkillLanguage, + ImageDetail, + IndexProjectionMode, + IndexedSharePointContainerName, + IndexerExecutionEnvironment, + IndexerExecutionStatus, + IndexerExecutionStatusDetail, + IndexerPermissionOption, + IndexerResyncOption, + IndexerStatus, + IndexingMode, + KeyPhraseExtractionSkillLanguage, + KnowledgeBaseModelKind, + KnowledgeSourceContentExtractionMode, + KnowledgeSourceIngestionPermissionOption, + KnowledgeSourceKind, + KnowledgeSourceSynchronizationStatus, + LexicalAnalyzerName, + LexicalNormalizerName, + LexicalTokenizerName, + MarkdownHeaderDepth, + MarkdownParsingSubmode, + MicrosoftStemmingTokenizerLanguage, + MicrosoftTokenizerLanguage, + OcrLineEnding, + OcrSkillLanguage, + PIIDetectionSkillMaskingMode, + PermissionFilter, + PhoneticEncoder, + RankingOrder, + RegexFlags, + ScoringFunctionAggregation, + ScoringFunctionInterpolation, + SearchFieldDataType, + SearchIndexPermissionFilterOption, + SearchIndexerDataSourceType, + SnowballTokenFilterLanguage, + SplitSkillEncoderModelName, + SplitSkillLanguage, + SplitSkillUnit, + StemmerTokenFilterLanguage, + StopwordsList, + TextSplitMode, + TextTranslationSkillLanguage, + TokenCharacterKind, + TokenFilterName, + VectorEncodingFormat, + VectorSearchAlgorithmKind, + VectorSearchAlgorithmMetric, + VectorSearchCompressionKind, + VectorSearchCompressionRescoreStorageMethod, + VectorSearchCompressionTarget, + VectorSearchVectorizerKind, + VisualFeature, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk -__all__ = ( - "AIServices", +__all__ = [ "AIServicesAccountIdentity", "AIServicesAccountKey", "AIServicesVisionParameters", "AIServicesVisionVectorizer", - "AIFoundryModelCatalogName", - "AnalyzeTextOptions", "AnalyzeResult", + "AnalyzeTextOptions", "AnalyzedTokenInfo", "AsciiFoldingTokenFilter", - "AzureOpenAIEmbeddingSkill", - "AzureOpenAITokenizerParameters", - "AzureOpenAIModelName", - "AzureOpenAIVectorizerParameters", - "AzureOpenAIVectorizer", + "AzureActiveDirectoryApplicationCredentials", "AzureBlobKnowledgeSource", "AzureBlobKnowledgeSourceParameters", "AzureMachineLearningParameters", "AzureMachineLearningSkill", "AzureMachineLearningVectorizer", - "BinaryQuantizationCompression", - "BlobIndexerDataToExtract", - "BlobIndexerImageAction", - "BlobIndexerParsingMode", - "BlobIndexerPDFTextRotationAlgorithm", + "AzureOpenAIEmbeddingSkill", + "AzureOpenAITokenizerParameters", + "AzureOpenAIVectorizer", + "AzureOpenAIVectorizerParameters", "BM25SimilarityAlgorithm", + "BinaryQuantizationCompression", "CharFilter", - "CharFilterName", - "ChatCompletionExtraParametersBehavior", + "ChatCompletionCommonModelParameters", "ChatCompletionResponseFormat", - "ChatCompletionResponseFormatType", - "ChatCompletionResponseFormatJsonSchemaProperties", "ChatCompletionSchema", + "ChatCompletionSchemaProperties", "ChatCompletionSkill", "CjkBigramTokenFilter", - "CjkBigramTokenFilterScripts", "ClassicSimilarityAlgorithm", "ClassicTokenizer", "CognitiveServicesAccount", "CognitiveServicesAccountKey", "CommonGramTokenFilter", - "CommonModelParameters", - "CompletedSynchronizationState", - "ComplexField", "ConditionalSkill", "ContentUnderstandingSkill", "ContentUnderstandingSkillChunkingProperties", - "ContentUnderstandingSkillChunkingUnit", - "ContentUnderstandingSkillExtractionOptions", "CorsOptions", + "CreatedResources", "CustomAnalyzer", "CustomEntity", "CustomEntityAlias", "CustomEntityLookupSkill", - "WebApiVectorizer", - "WebApiVectorizerParameters", - "CustomEntityLookupSkillLanguage", "CustomNormalizer", "DataChangeDetectionPolicy", "DataDeletionDetectionPolicy", @@ -406,21 +356,13 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "DocumentExtractionSkill", "DocumentIntelligenceLayoutSkill", "DocumentIntelligenceLayoutSkillChunkingProperties", - "DocumentIntelligenceLayoutSkillChunkingUnit", - "DocumentIntelligenceLayoutSkillExtractionOptions", - "DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", - "DocumentIntelligenceLayoutSkillOutputFormat", - "DocumentIntelligenceLayoutSkillOutputMode", "DocumentKeysOrIds", "EdgeNGramTokenFilter", + "EdgeNGramTokenFilterV2", "EdgeNGramTokenizer", "ElisionTokenFilter", - "EdgeNGramTokenFilterSide", - "EntityCategory", "EntityLinkingSkill", - "EntityRecognitionSkill", - "EntityRecognitionSkillLanguage", - "EntityRecognitionSkillVersion", + "EntityRecognitionSkillV3", "ExhaustiveKnnAlgorithmConfiguration", "ExhaustiveKnnParameters", "FieldMapping", @@ -429,111 +371,70 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "FreshnessScoringParameters", "GetIndexStatisticsResult", "HighWaterMarkChangeDetectionPolicy", - "HnswParameters", "HnswAlgorithmConfiguration", + "HnswParameters", "ImageAnalysisSkill", - "ImageAnalysisSkillLanguage", - "ImageDetail", + "IndexStatisticsSummary", + "IndexedOneLakeKnowledgeSource", + "IndexedOneLakeKnowledgeSourceParameters", + "IndexedSharePointKnowledgeSource", + "IndexedSharePointKnowledgeSourceParameters", "IndexerCurrentState", - "IndexerExecutionEnvironment", "IndexerExecutionResult", "IndexerResyncBody", - "IndexerExecutionStatus", - "IndexerPermissionOption", - "IndexerResyncOption", - "IndexerStatus", - "IndexingMode", + "IndexerRuntime", "IndexingParameters", "IndexingParametersConfiguration", "IndexingSchedule", - "IndexProjectionMode", - "IndexedOneLakeKnowledgeSource", - "IndexedOneLakeKnowledgeSourceParameters", - "IndexedSharePointKnowledgeSource", - "IndexedSharePointKnowledgeSourceParameters", - "IndexedSharePointContainerName", - "IndexerRuntime", "InputFieldMappingEntry", "KeepTokenFilter", "KeyPhraseExtractionSkill", - "KeyPhraseExtractionSkillLanguage", "KeywordMarkerTokenFilter", "KeywordTokenizer", - "LanguageDetectionSkill", + "KeywordTokenizerV2", "KnowledgeBase", "KnowledgeBaseAzureOpenAIModel", "KnowledgeBaseModel", - "KnowledgeBaseModelKind", - "KnowledgeRetrievalLowReasoningEffort", - "KnowledgeRetrievalMediumReasoningEffort", - "KnowledgeRetrievalMinimalReasoningEffort", - "KnowledgeRetrievalReasoningEffort", - "KnowledgeRetrievalOutputMode", - "KnowledgeRetrievalReasoningEffortKind", "KnowledgeSource", - "KnowledgeSourceAzureOpenAIVectorizer", - "KnowledgeSourceContentExtractionMode", - "KnowledgeSourceIngestionParameters", - "KnowledgeSourceIngestionPermissionOption", - "KnowledgeSourceKind", "KnowledgeSourceReference", - "KnowledgeSourceStatistics", - "KnowledgeSourceStatus", - "KnowledgeSourceSynchronizationStatus", - "KnowledgeSourceVectorizer", + "LanguageDetectionSkill", "LengthTokenFilter", "LexicalAnalyzer", - "LexicalAnalyzerName", "LexicalNormalizer", - "LexicalNormalizerName", "LexicalTokenizer", - "LexicalTokenizerName", "LimitTokenFilter", - "IndexStatisticsSummary", "LuceneStandardAnalyzer", "LuceneStandardTokenizer", + "LuceneStandardTokenizerV2", "MagnitudeScoringFunction", "MagnitudeScoringParameters", - "MarkdownHeaderDepth", - "MarkdownParsingSubmode", "MappingCharFilter", "MergeSkill", "MicrosoftLanguageStemmingTokenizer", "MicrosoftLanguageTokenizer", - "MicrosoftStemmingTokenizerLanguage", - "MicrosoftTokenizerLanguage", - "NativeBlobSoftDeleteDeletionDetectionPolicy", "NGramTokenFilter", + "NGramTokenFilterV2", "NGramTokenizer", - "OcrLineEnding", + "NativeBlobSoftDeleteDeletionDetectionPolicy", "OcrSkill", - "OcrSkillLanguage", "OutputFieldMappingEntry", - "PathHierarchyTokenizer", + "PIIDetectionSkill", + "PathHierarchyTokenizerV2", "PatternAnalyzer", "PatternCaptureTokenFilter", "PatternReplaceCharFilter", "PatternReplaceTokenFilter", "PatternTokenizer", - "PermissionFilter", - "PIIDetectionSkill", + "PhoneticTokenFilter", "RemoteSharePointKnowledgeSource", "RemoteSharePointKnowledgeSourceParameters", - "PIIDetectionSkillMaskingMode", - "PhoneticEncoder", - "PhoneticTokenFilter", - "RankingOrder", - "RegexFlags", "RescoringOptions", "ResourceCounter", "ScalarQuantizationCompression", "ScalarQuantizationParameters", "ScoringFunction", - "ScoringFunctionAggregation", - "ScoringFunctionInterpolation", "ScoringProfile", "SearchAlias", - "SearchableField", "SearchField", "SearchIndex", "SearchIndexFieldReference", @@ -544,9 +445,8 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SearchIndexerDataContainer", "SearchIndexerDataIdentity", "SearchIndexerDataNoneIdentity", - "SearchIndexerDataUserAssignedIdentity", "SearchIndexerDataSourceConnection", - "SearchIndexerDataSourceType", + "SearchIndexerDataUserAssignedIdentity", "SearchIndexerError", "SearchIndexerIndexProjection", "SearchIndexerIndexProjectionSelector", @@ -555,6 +455,7 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SearchIndexerKnowledgeStoreBlobProjectionSelector", "SearchIndexerKnowledgeStoreFileProjectionSelector", "SearchIndexerKnowledgeStoreObjectProjectionSelector", + "SearchIndexerKnowledgeStoreParameters", "SearchIndexerKnowledgeStoreProjection", "SearchIndexerKnowledgeStoreProjectionSelector", "SearchIndexerKnowledgeStoreTableProjectionSelector", @@ -563,7 +464,6 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SearchIndexerSkillset", "SearchIndexerStatus", "SearchIndexerWarning", - "SearchIndexPermissionFilterOption", "SearchResourceEncryptionKey", "SearchServiceCounters", "SearchServiceLimits", @@ -573,64 +473,118 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SemanticField", "SemanticPrioritizedFields", "SemanticSearch", - "SentimentSkill", - "SentimentSkillLanguage", + "SentimentSkillV3", "ServiceIndexersRuntime", - "SentimentSkillVersion", "ShaperSkill", "ShingleTokenFilter", - "SimpleField", "SimilarityAlgorithm", "SkillNames", "SnowballTokenFilter", - "SnowballTokenFilterLanguage", - "SplitSkillEncoderModelName", "SoftDeleteColumnDeletionDetectionPolicy", "SplitSkill", - "SplitSkillLanguage", - "SplitSkillUnit", "SqlIntegratedChangeTrackingPolicy", "StemmerOverrideTokenFilter", "StemmerTokenFilter", - "StemmerTokenFilterLanguage", "StopAnalyzer", - "StopwordsList", "StopwordsTokenFilter", - "SuggestOptions", - "SynchronizationState", "SynonymMap", "SynonymTokenFilter", "TagScoringFunction", "TagScoringParameters", - "TextSplitMode", "TextTranslationSkill", - "TextTranslationSkillLanguage", "TextWeights", - "TokenCharacterKind", "TokenFilter", - "TokenFilterName", "TruncateTokenFilter", "UaxUrlEmailTokenizer", "UniqueTokenFilter", - "VectorEncodingFormat", "VectorSearch", "VectorSearchAlgorithmConfiguration", - "VectorSearchAlgorithmKind", - "VectorSearchAlgorithmMetric", "VectorSearchCompression", - "VectorSearchCompressionKind", - "VectorSearchCompressionRescoreStorageMethod", - "VectorSearchCompressionTarget", "VectorSearchProfile", "VectorSearchVectorizer", - "VectorSearchVectorizerKind", - "VisualFeature", "VisionVectorizeSkill", + "WebApiHttpHeaders", "WebApiSkill", + "WebApiVectorizer", + "WebApiVectorizerParameters", "WebKnowledgeSource", "WebKnowledgeSourceDomain", "WebKnowledgeSourceDomains", "WebKnowledgeSourceParameters", "WordDelimiterTokenFilter", + "AIFoundryModelCatalogName", + "AzureOpenAIModelName", + "BlobIndexerDataToExtract", + "BlobIndexerImageAction", + "BlobIndexerPDFTextRotationAlgorithm", + "BlobIndexerParsingMode", + "CharFilterName", + "ChatCompletionExtraParametersBehavior", + "ChatCompletionResponseFormatType", + "CjkBigramTokenFilterScripts", + "ContentUnderstandingSkillChunkingUnit", + "ContentUnderstandingSkillExtractionOptions", + "CustomEntityLookupSkillLanguage", + "DocumentIntelligenceLayoutSkillChunkingUnit", + "DocumentIntelligenceLayoutSkillExtractionOptions", + "DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", + "DocumentIntelligenceLayoutSkillOutputFormat", + "DocumentIntelligenceLayoutSkillOutputMode", + "EdgeNGramTokenFilterSide", + "ImageAnalysisSkillLanguage", + "ImageDetail", + "IndexProjectionMode", + "IndexedSharePointContainerName", + "IndexerExecutionEnvironment", + "IndexerExecutionStatus", + "IndexerExecutionStatusDetail", + "IndexerPermissionOption", + "IndexerResyncOption", + "IndexerStatus", + "IndexingMode", + "KeyPhraseExtractionSkillLanguage", + "KnowledgeBaseModelKind", + "KnowledgeSourceContentExtractionMode", + "KnowledgeSourceIngestionPermissionOption", + "KnowledgeSourceKind", + "KnowledgeSourceSynchronizationStatus", + "LexicalAnalyzerName", + "LexicalNormalizerName", + "LexicalTokenizerName", + "MarkdownHeaderDepth", + "MarkdownParsingSubmode", + "MicrosoftStemmingTokenizerLanguage", + "MicrosoftTokenizerLanguage", + "OcrLineEnding", + "OcrSkillLanguage", + "PIIDetectionSkillMaskingMode", + "PermissionFilter", + "PhoneticEncoder", + "RankingOrder", + "RegexFlags", + "ScoringFunctionAggregation", + "ScoringFunctionInterpolation", "SearchFieldDataType", -) + "SearchIndexPermissionFilterOption", + "SearchIndexerDataSourceType", + "SnowballTokenFilterLanguage", + "SplitSkillEncoderModelName", + "SplitSkillLanguage", + "SplitSkillUnit", + "StemmerTokenFilterLanguage", + "StopwordsList", + "TextSplitMode", + "TextTranslationSkillLanguage", + "TokenCharacterKind", + "TokenFilterName", + "VectorEncodingFormat", + "VectorSearchAlgorithmKind", + "VectorSearchAlgorithmMetric", + "VectorSearchCompressionKind", + "VectorSearchCompressionRescoreStorageMethod", + "VectorSearchCompressionTarget", + "VectorSearchVectorizerKind", + "VisualFeature", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py deleted file mode 100644 index ec5b4f4937eb..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py +++ /dev/null @@ -1,19 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -String = "Edm.String" -Int32 = "Edm.Int32" -Int64 = "Edm.Int64" -Single = "Edm.Single" -Double = "Edm.Double" -Boolean = "Edm.Boolean" -DateTimeOffset = "Edm.DateTimeOffset" -GeographyPoint = "Edm.GeographyPoint" -ComplexType = "Edm.ComplexType" - - -def Collection(typ: str) -> str: - return "Collection({})".format(typ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_search_service_client_enums.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py similarity index 73% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_search_service_client_enums.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py index 00bdf6b7b406..ca874cb2ce88 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_search_service_client_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py @@ -1,7 +1,9 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines,enum-must-be-uppercase # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -12,14 +14,18 @@ class AIFoundryModelCatalogName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The name of the embedding model from the Azure AI Foundry Catalog that will be called.""" - OPEN_AI_CLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 = "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32" - OPEN_AI_CLIP_IMAGE_TEXT_EMBEDDINGS_VI_T_LARGE_PATCH14_336 = ( - "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336" - ) + OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 = "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32" + """OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32.""" + OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VI_T_LARGE_PATCH14336 = "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336" + """OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336.""" FACEBOOK_DINO_V2_IMAGE_EMBEDDINGS_VI_T_BASE = "Facebook-DinoV2-Image-Embeddings-ViT-Base" + """Facebook-DinoV2-Image-Embeddings-ViT-Base.""" FACEBOOK_DINO_V2_IMAGE_EMBEDDINGS_VI_T_GIANT = "Facebook-DinoV2-Image-Embeddings-ViT-Giant" + """Facebook-DinoV2-Image-Embeddings-ViT-Giant.""" COHERE_EMBED_V3_ENGLISH = "Cohere-embed-v3-english" + """Cohere-embed-v3-english.""" COHERE_EMBED_V3_MULTILINGUAL = "Cohere-embed-v3-multilingual" + """Cohere-embed-v3-multilingual.""" COHERE_EMBED_V4 = "Cohere-embed-v4" """Cohere embed v4 model for generating embeddings from both text and images.""" @@ -28,16 +34,27 @@ class AzureOpenAIModelName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The Azure Open AI model name that will be called.""" TEXT_EMBEDDING_ADA002 = "text-embedding-ada-002" + """TextEmbeddingAda002 model.""" TEXT_EMBEDDING3_LARGE = "text-embedding-3-large" + """TextEmbedding3Large model.""" TEXT_EMBEDDING3_SMALL = "text-embedding-3-small" + """TextEmbedding3Small model.""" GPT4_O = "gpt-4o" + """Gpt4o model.""" GPT4_O_MINI = "gpt-4o-mini" + """Gpt4oMini model.""" GPT41 = "gpt-4.1" + """Gpt41 model.""" GPT41_MINI = "gpt-4.1-mini" + """Gpt41Mini model.""" GPT41_NANO = "gpt-4.1-nano" + """Gpt41Nano model.""" GPT5 = "gpt-5" + """Gpt5 model.""" GPT5_MINI = "gpt-5-mini" + """Gpt5Mini model.""" GPT5_NANO = "gpt-5-nano" + """Gpt5Nano model.""" class BlobIndexerDataToExtract(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -114,13 +131,14 @@ class CharFilterName(str, Enum, metaclass=CaseInsensitiveEnumMeta): HTML_STRIP = "html_strip" """A character filter that attempts to strip out HTML constructs. See - https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.html""" + `https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.html + `_.""" class ChatCompletionExtraParametersBehavior(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies how 'extraParameters' should be handled by Azure AI Foundry. Defaults to 'error'.""" - PASS_THROUGH = "passThrough" + PASS_THROUGH = "pass-through" """Passes any extra parameters directly to the model.""" DROP = "drop" """Drops all extra parameters.""" @@ -129,13 +147,14 @@ class ChatCompletionExtraParametersBehavior(str, Enum, metaclass=CaseInsensitive class ChatCompletionResponseFormatType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies how the LLM should format the response. Possible values: 'text' (plain string), - 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). - """ + """Specifies how the LLM should format the response.""" TEXT = "text" + """Plain text response format.""" JSON_OBJECT = "jsonObject" + """Arbitrary JSON object response format.""" JSON_SCHEMA = "jsonSchema" + """JSON schema-adhering response format.""" class CjkBigramTokenFilterScripts(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -158,7 +177,9 @@ class ContentUnderstandingSkillChunkingUnit(str, Enum, metaclass=CaseInsensitive """Specifies chunk by characters.""" -class ContentUnderstandingSkillExtractionOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class ContentUnderstandingSkillExtractionOptions( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """Controls the cardinality of the content extracted from the document by the skill.""" IMAGES = "images" @@ -171,33 +192,37 @@ class CustomEntityLookupSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMe """The language codes supported for input text by CustomEntityLookupSkill.""" DA = "da" - """Danish""" + """Danish.""" DE = "de" - """German""" + """German.""" EN = "en" - """English""" + """English.""" ES = "es" - """Spanish""" + """Spanish.""" FI = "fi" - """Finnish""" + """Finnish.""" FR = "fr" - """French""" + """French.""" IT = "it" - """Italian""" + """Italian.""" KO = "ko" - """Korean""" + """Korean.""" PT = "pt" - """Portuguese""" + """Portuguese.""" -class DocumentIntelligenceLayoutSkillChunkingUnit(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class DocumentIntelligenceLayoutSkillChunkingUnit( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """Controls the cardinality of the chunk unit. Default is 'characters'.""" CHARACTERS = "characters" """Specifies chunk by characters.""" -class DocumentIntelligenceLayoutSkillExtractionOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class DocumentIntelligenceLayoutSkillExtractionOptions( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """Controls the cardinality of the content extracted from the document by the skill.""" IMAGES = "images" @@ -206,7 +231,9 @@ class DocumentIntelligenceLayoutSkillExtractionOptions(str, Enum, metaclass=Case """Specify that location metadata should be extracted from the document.""" -class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """The depth of headers in the markdown output. Default is h6.""" H1 = "h1" @@ -223,7 +250,9 @@ class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth(str, Enum, metaclass=Ca """Header level 6.""" -class DocumentIntelligenceLayoutSkillOutputFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class DocumentIntelligenceLayoutSkillOutputFormat( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """Controls the cardinality of the output format. Default is 'markdown'.""" TEXT = "text" @@ -232,7 +261,9 @@ class DocumentIntelligenceLayoutSkillOutputFormat(str, Enum, metaclass=CaseInsen """Specify the format of the output as markdown.""" -class DocumentIntelligenceLayoutSkillOutputMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class DocumentIntelligenceLayoutSkillOutputMode( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """Controls the cardinality of the output produced by the skill. Default is 'oneToMany'.""" ONE_TO_MANY = "oneToMany" @@ -248,189 +279,113 @@ class EdgeNGramTokenFilterSide(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies that the n-gram should be generated from the back of the input.""" -class EntityCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """A string indicating what entity categories to return.""" - - LOCATION = "location" - """Entities describing a physical location.""" - ORGANIZATION = "organization" - """Entities describing an organization.""" - PERSON = "person" - """Entities describing a person.""" - QUANTITY = "quantity" - """Entities describing a quantity.""" - DATETIME = "datetime" - """Entities describing a date and time.""" - URL = "url" - """Entities describing a URL.""" - EMAIL = "email" - """Entities describing an email address.""" - - -class EntityRecognitionSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Deprecated. The language codes supported for input text by EntityRecognitionSkill.""" - - AR = "ar" - """Arabic""" - CS = "cs" - """Czech""" - ZH_HANS = "zh-Hans" - """Chinese-Simplified""" - ZH_HANT = "zh-Hant" - """Chinese-Traditional""" - DA = "da" - """Danish""" - NL = "nl" - """Dutch""" - EN = "en" - """English""" - FI = "fi" - """Finnish""" - FR = "fr" - """French""" - DE = "de" - """German""" - EL = "el" - """Greek""" - HU = "hu" - """Hungarian""" - IT = "it" - """Italian""" - JA = "ja" - """Japanese""" - KO = "ko" - """Korean""" - NO = "no" - """Norwegian (Bokmaal)""" - PL = "pl" - """Polish""" - PT_PT = "pt-PT" - """Portuguese (Portugal)""" - PT_BR = "pt-BR" - """Portuguese (Brazil)""" - RU = "ru" - """Russian""" - ES = "es" - """Spanish""" - SV = "sv" - """Swedish""" - TR = "tr" - """Turkish""" - - -class Enum0(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum0.""" - - RETURN_REPRESENTATION = "return=representation" - - class ImageAnalysisSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The language codes supported for input by ImageAnalysisSkill.""" AR = "ar" - """Arabic""" + """Arabic.""" AZ = "az" - """Azerbaijani""" + """Azerbaijani.""" BG = "bg" - """Bulgarian""" + """Bulgarian.""" BS = "bs" - """Bosnian Latin""" + """Bosnian Latin.""" CA = "ca" - """Catalan""" + """Catalan.""" CS = "cs" - """Czech""" + """Czech.""" CY = "cy" - """Welsh""" + """Welsh.""" DA = "da" - """Danish""" + """Danish.""" DE = "de" - """German""" + """German.""" EL = "el" - """Greek""" + """Greek.""" EN = "en" - """English""" + """English.""" ES = "es" - """Spanish""" + """Spanish.""" ET = "et" - """Estonian""" + """Estonian.""" EU = "eu" - """Basque""" + """Basque.""" FI = "fi" - """Finnish""" + """Finnish.""" FR = "fr" - """French""" + """French.""" GA = "ga" - """Irish""" + """Irish.""" GL = "gl" - """Galician""" + """Galician.""" HE = "he" - """Hebrew""" + """Hebrew.""" HI = "hi" - """Hindi""" + """Hindi.""" HR = "hr" - """Croatian""" + """Croatian.""" HU = "hu" - """Hungarian""" + """Hungarian.""" ID = "id" - """Indonesian""" + """Indonesian.""" IT = "it" - """Italian""" + """Italian.""" JA = "ja" - """Japanese""" + """Japanese.""" KK = "kk" - """Kazakh""" + """Kazakh.""" KO = "ko" - """Korean""" + """Korean.""" LT = "lt" - """Lithuanian""" + """Lithuanian.""" LV = "lv" - """Latvian""" + """Latvian.""" MK = "mk" - """Macedonian""" + """Macedonian.""" MS = "ms" - """Malay Malaysia""" + """Malay Malaysia.""" NB = "nb" - """Norwegian (Bokmal)""" + """Norwegian (Bokmal).""" NL = "nl" - """Dutch""" + """Dutch.""" PL = "pl" - """Polish""" + """Polish.""" PRS = "prs" - """Dari""" + """Dari.""" PT_BR = "pt-BR" - """Portuguese-Brazil""" + """Portuguese-Brazil.""" PT = "pt" - """Portuguese-Portugal""" + """Portuguese-Portugal.""" PT_PT = "pt-PT" - """Portuguese-Portugal""" + """Portuguese-Portugal.""" RO = "ro" - """Romanian""" + """Romanian.""" RU = "ru" - """Russian""" + """Russian.""" SK = "sk" - """Slovak""" + """Slovak.""" SL = "sl" - """Slovenian""" + """Slovenian.""" SR_CYRL = "sr-Cyrl" - """Serbian - Cyrillic RS""" + """Serbian - Cyrillic RS.""" SR_LATN = "sr-Latn" - """Serbian - Latin RS""" + """Serbian - Latin RS.""" SV = "sv" - """Swedish""" + """Swedish.""" TH = "th" - """Thai""" + """Thai.""" TR = "tr" - """Turkish""" + """Turkish.""" UK = "uk" - """Ukrainian""" + """Ukrainian.""" VI = "vi" - """Vietnamese""" + """Vietnamese.""" ZH = "zh" - """Chinese Simplified""" + """Chinese Simplified.""" ZH_HANS = "zh-Hans" - """Chinese Simplified""" + """Chinese Simplified.""" ZH_HANT = "zh-Hant" - """Chinese Traditional""" + """Chinese Traditional.""" class ImageDetail(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -450,7 +405,7 @@ class IndexedSharePointContainerName(str, Enum, metaclass=CaseInsensitiveEnumMet ALL_SITE_LIBRARIES = "allSiteLibraries" """Index content from every document library in the site.""" USE_QUERY = "useQuery" - """Index only content that matches the query specified in the knowledge source.""" + """Use a query to filter SharePoint content.""" class IndexerExecutionEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -544,37 +499,37 @@ class KeyPhraseExtractionSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumM """The language codes supported for input text by KeyPhraseExtractionSkill.""" DA = "da" - """Danish""" + """Danish.""" NL = "nl" - """Dutch""" + """Dutch.""" EN = "en" - """English""" + """English.""" FI = "fi" - """Finnish""" + """Finnish.""" FR = "fr" - """French""" + """French.""" DE = "de" - """German""" + """German.""" IT = "it" - """Italian""" + """Italian.""" JA = "ja" - """Japanese""" + """Japanese.""" KO = "ko" - """Korean""" + """Korean.""" NO = "no" - """Norwegian (Bokmaal)""" + """Norwegian (Bokmaal).""" PL = "pl" - """Polish""" + """Polish.""" PT_PT = "pt-PT" - """Portuguese (Portugal)""" + """Portuguese (Portugal).""" PT_BR = "pt-BR" - """Portuguese (Brazil)""" + """Portuguese (Brazil).""" RU = "ru" - """Russian""" + """Russian.""" ES = "es" - """Spanish""" + """Spanish.""" SV = "sv" - """Swedish""" + """Swedish.""" class KnowledgeBaseModelKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -584,26 +539,6 @@ class KnowledgeBaseModelKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Use Azure Open AI models for query planning.""" -class KnowledgeRetrievalOutputMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The output configuration for this retrieval.""" - - EXTRACTIVE_DATA = "extractiveData" - """Return data from the knowledge sources directly without generative alteration.""" - ANSWER_SYNTHESIS = "answerSynthesis" - """Synthesize an answer for the response payload.""" - - -class KnowledgeRetrievalReasoningEffortKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The amount of effort to use during retrieval.""" - - MINIMAL = "minimal" - """Does not perform any source selections, query planning, or iterative search.""" - LOW = "low" - """Use low reasoning during retrieval.""" - MEDIUM = "medium" - """Use a moderate amount of reasoning during retrieval.""" - - class KnowledgeSourceContentExtractionMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Optional content extraction mode. Default is 'minimal'.""" @@ -614,7 +549,7 @@ class KnowledgeSourceContentExtractionMode(str, Enum, metaclass=CaseInsensitiveE class KnowledgeSourceIngestionPermissionOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """KnowledgeSourceIngestionPermissionOption.""" + """Permission types to ingest together with document content.""" USER_IDS = "userIds" """Ingest explicit user identifiers alongside document content.""" @@ -628,17 +563,17 @@ class KnowledgeSourceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The kind of the knowledge source.""" SEARCH_INDEX = "searchIndex" - """A knowledge source that retrieves data from a Search Index.""" + """A knowledge source that reads data from a Search Index.""" AZURE_BLOB = "azureBlob" - """A knowledge source that retrieves and ingests data from Azure Blob Storage to a Search Index.""" - WEB = "web" - """A knowledge source that retrieves data from the web.""" - REMOTE_SHARE_POINT = "remoteSharePoint" - """A knowledge source that retrieves data from a remote SharePoint endpoint.""" + """A knowledge source that read and ingest data from Azure Blob Storage to a Search Index.""" INDEXED_SHARE_POINT = "indexedSharePoint" - """A knowledge source that retrieves and ingests data from SharePoint to a Search Index.""" + """A knowledge source that reads data from indexed SharePoint.""" INDEXED_ONE_LAKE = "indexedOneLake" - """A knowledge source that retrieves and ingests data from OneLake to a Search Index.""" + """A knowledge source that reads data from indexed OneLake.""" + WEB = "web" + """A knowledge source that reads data from the web.""" + REMOTE_SHARE_POINT = "remoteSharePoint" + """A knowledge source that reads data from remote SharePoint.""" class KnowledgeSourceSynchronizationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -766,7 +701,7 @@ class LexicalAnalyzerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): MR_MICROSOFT = "mr.microsoft" """Microsoft analyzer for Marathi.""" NB_MICROSOFT = "nb.microsoft" - """Microsoft analyzer for Norwegian (Bokmål).""" + """Microsoft analyzer for Norwegian (BokmÃ¥l).""" NO_LUCENE = "no.lucene" """Lucene analyzer for Norwegian.""" FA_LUCENE = "fa.lucene" @@ -831,23 +766,29 @@ class LexicalAnalyzerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Standard Lucene analyzer.""" STANDARD_ASCII_FOLDING_LUCENE = "standardasciifolding.lucene" """Standard ASCII Folding Lucene analyzer. See - https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#Analyzers""" + `https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#Analyzers + `_.""" KEYWORD = "keyword" """Treats the entire content of a field as a single token. This is useful for data like zip codes, ids, and some product names. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordAnalyzer.html + `_.""" PATTERN = "pattern" """Flexibly separates text into terms via a regular expression pattern. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/PatternAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/PatternAnalyzer.html + `_.""" SIMPLE = "simple" """Divides text at non-letters and converts them to lower case. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/SimpleAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/SimpleAnalyzer.html + `_.""" STOP = "stop" """Divides text at non-letters; Applies the lowercase and stopword token filters. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopAnalyzer.html + `_.""" WHITESPACE = "whitespace" """An analyzer that uses the whitespace tokenizer. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceAnalyzer.html + `_.""" class LexicalNormalizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -857,19 +798,24 @@ class LexicalNormalizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such equivalents exist. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html + `_.""" ELISION = "elision" """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html + `_.""" LOWERCASE = "lowercase" """Normalizes token text to lowercase. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html + `_.""" STANDARD = "standard" """Standard normalizer, which consists of lowercase and asciifolding. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html + `_.""" UPPERCASE = "uppercase" """Normalizes token text to uppercase. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html + `_.""" class LexicalTokenizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -877,42 +823,53 @@ class LexicalTokenizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): CLASSIC = "classic" """Grammar-based tokenizer that is suitable for processing most European-language documents. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicTokenizer.html + `_.""" EDGE_N_GRAM = "edgeNGram" """Tokenizes the input from an edge into n-grams of the given size(s). See - https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenizer.html""" + `https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenizer.html + `_.""" KEYWORD = "keyword_v2" """Emits the entire input as a single token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordTokenizer.html + `_.""" LETTER = "letter" """Divides text at non-letters. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LetterTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LetterTokenizer.html + `_.""" LOWERCASE = "lowercase" """Divides text at non-letters and converts them to lower case. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LowerCaseTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LowerCaseTokenizer.html + `_.""" MICROSOFT_LANGUAGE_TOKENIZER = "microsoft_language_tokenizer" """Divides text using language-specific rules.""" MICROSOFT_LANGUAGE_STEMMING_TOKENIZER = "microsoft_language_stemming_tokenizer" """Divides text using language-specific rules and reduces words to their base forms.""" N_GRAM = "nGram" """Tokenizes the input into n-grams of the given size(s). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenizer.html + `_.""" PATH_HIERARCHY = "path_hierarchy_v2" """Tokenizer for path-like hierarchies. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/path/PathHierarchyTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/path/PathHierarchyTokenizer.html + `_.""" PATTERN = "pattern" """Tokenizer that uses regex pattern matching to construct distinct tokens. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/pattern/PatternTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/pattern/PatternTokenizer.html + `_.""" STANDARD = "standard_v2" """Standard Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop filter. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/StandardTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/StandardTokenizer.html + `_.""" UAX_URL_EMAIL = "uax_url_email" """Tokenizes urls and emails as one token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/UAX29URLEmailTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/UAX29URLEmailTokenizer.html + `_.""" WHITESPACE = "whitespace" """Divides text at whitespace. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceTokenizer.html + `_.""" class MarkdownHeaderDepth(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1006,7 +963,7 @@ class MicrosoftStemmingTokenizerLanguage(str, Enum, metaclass=CaseInsensitiveEnu MARATHI = "marathi" """Selects the Microsoft stemming tokenizer for Marathi.""" NORWEGIAN_BOKMAAL = "norwegianBokmaal" - """Selects the Microsoft stemming tokenizer for Norwegian (Bokmål).""" + """Selects the Microsoft stemming tokenizer for Norwegian (BokmÃ¥l).""" POLISH = "polish" """Selects the Microsoft stemming tokenizer for Polish.""" PORTUGUESE = "portuguese" @@ -1095,7 +1052,7 @@ class MicrosoftTokenizerLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): MARATHI = "marathi" """Selects the Microsoft tokenizer for Marathi.""" NORWEGIAN_BOKMAAL = "norwegianBokmaal" - """Selects the Microsoft tokenizer for Norwegian (Bokmål).""" + """Selects the Microsoft tokenizer for Norwegian (BokmÃ¥l).""" POLISH = "polish" """Selects the Microsoft tokenizer for Polish.""" PORTUGUESE = "portuguese" @@ -1151,347 +1108,345 @@ class OcrSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The language codes supported for input by OcrSkill.""" AF = "af" - """Afrikaans""" + """Afrikaans.""" SQ = "sq" - """Albanian""" + """Albanian.""" ANP = "anp" - """Angika (Devanagiri)""" + """Angika (Devanagiri).""" AR = "ar" - """Arabic""" + """Arabic.""" AST = "ast" - """Asturian""" + """Asturian.""" AWA = "awa" - """Awadhi-Hindi (Devanagiri)""" + """Awadhi-Hindi (Devanagiri).""" AZ = "az" - """Azerbaijani (Latin)""" + """Azerbaijani (Latin).""" BFY = "bfy" - """Bagheli""" + """Bagheli.""" EU = "eu" - """Basque""" + """Basque.""" BE = "be" - """Belarusian (Cyrillic and Latin)""" + """Belarusian (Cyrillic and Latin).""" BE_CYRL = "be-cyrl" - """Belarusian (Cyrillic)""" + """Belarusian (Cyrillic).""" BE_LATN = "be-latn" - """Belarusian (Latin)""" + """Belarusian (Latin).""" BHO = "bho" - """Bhojpuri-Hindi (Devanagiri)""" + """Bhojpuri-Hindi (Devanagiri).""" BI = "bi" - """Bislama""" + """Bislama.""" BRX = "brx" - """Bodo (Devanagiri)""" + """Bodo (Devanagiri).""" BS = "bs" - """Bosnian Latin""" + """Bosnian Latin.""" BRA = "bra" - """Brajbha""" + """Brajbha.""" BR = "br" - """Breton""" + """Breton.""" BG = "bg" - """Bulgarian""" + """Bulgarian.""" BNS = "bns" - """Bundeli""" + """Bundeli.""" BUA = "bua" - """Buryat (Cyrillic)""" + """Buryat (Cyrillic).""" CA = "ca" - """Catalan""" + """Catalan.""" CEB = "ceb" - """Cebuano""" + """Cebuano.""" RAB = "rab" - """Chamling""" + """Chamling.""" CH = "ch" - """Chamorro""" + """Chamorro.""" HNE = "hne" - """Chhattisgarhi (Devanagiri)""" + """Chhattisgarhi (Devanagiri).""" ZH_HANS = "zh-Hans" - """Chinese Simplified""" + """Chinese Simplified.""" ZH_HANT = "zh-Hant" - """Chinese Traditional""" + """Chinese Traditional.""" KW = "kw" - """Cornish""" + """Cornish.""" CO = "co" - """Corsican""" + """Corsican.""" CRH = "crh" - """Crimean Tatar (Latin)""" + """Crimean Tatar (Latin).""" HR = "hr" - """Croatian""" + """Croatian.""" CS = "cs" - """Czech""" + """Czech.""" DA = "da" - """Danish""" + """Danish.""" PRS = "prs" - """Dari""" + """Dari.""" DHI = "dhi" - """Dhimal (Devanagiri)""" + """Dhimal (Devanagiri).""" DOI = "doi" - """Dogri (Devanagiri)""" + """Dogri (Devanagiri).""" NL = "nl" - """Dutch""" + """Dutch.""" EN = "en" - """English""" + """English.""" MYV = "myv" - """Erzya (Cyrillic)""" + """Erzya (Cyrillic).""" ET = "et" - """Estonian""" + """Estonian.""" FO = "fo" - """Faroese""" + """Faroese.""" FJ = "fj" - """Fijian""" + """Fijian.""" FIL = "fil" - """Filipino""" + """Filipino.""" FI = "fi" - """Finnish""" + """Finnish.""" FR = "fr" - """French""" + """French.""" FUR = "fur" - """Frulian""" + """Frulian.""" GAG = "gag" - """Gagauz (Latin)""" + """Gagauz (Latin).""" GL = "gl" - """Galician""" + """Galician.""" DE = "de" - """German""" + """German.""" GIL = "gil" - """Gilbertese""" + """Gilbertese.""" GON = "gon" - """Gondi (Devanagiri)""" + """Gondi (Devanagiri).""" EL = "el" - """Greek""" + """Greek.""" KL = "kl" - """Greenlandic""" + """Greenlandic.""" GVR = "gvr" - """Gurung (Devanagiri)""" + """Gurung (Devanagiri).""" HT = "ht" - """Haitian Creole""" + """Haitian Creole.""" HLB = "hlb" - """Halbi (Devanagiri)""" + """Halbi (Devanagiri).""" HNI = "hni" - """Hani""" + """Hani.""" BGC = "bgc" - """Haryanvi""" + """Haryanvi.""" HAW = "haw" - """Hawaiian""" + """Hawaiian.""" HI = "hi" - """Hindi""" + """Hindi.""" MWW = "mww" - """Hmong Daw (Latin)""" + """Hmong Daw (Latin).""" HOC = "hoc" - """Ho (Devanagiri)""" + """Ho (Devanagiri).""" HU = "hu" - """Hungarian""" - IS = "is" - """Icelandic""" + """Hungarian.""" + ISEnum = "is" + """Icelandic.""" SMN = "smn" - """Inari Sami""" + """Inari Sami.""" ID = "id" - """Indonesian""" + """Indonesian.""" IA = "ia" - """Interlingua""" + """Interlingua.""" IU = "iu" - """Inuktitut (Latin)""" + """Inuktitut (Latin).""" GA = "ga" - """Irish""" + """Irish.""" IT = "it" - """Italian""" + """Italian.""" JA = "ja" - """Japanese""" + """Japanese.""" JNS = "Jns" - """Jaunsari (Devanagiri)""" + """Jaunsari (Devanagiri).""" JV = "jv" - """Javanese""" + """Javanese.""" KEA = "kea" - """Kabuverdianu""" + """Kabuverdianu.""" KAC = "kac" - """Kachin (Latin)""" + """Kachin (Latin).""" XNR = "xnr" - """Kangri (Devanagiri)""" + """Kangri (Devanagiri).""" KRC = "krc" - """Karachay-Balkar""" + """Karachay-Balkar.""" KAA_CYRL = "kaa-cyrl" - """Kara-Kalpak (Cyrillic)""" + """Kara-Kalpak (Cyrillic).""" KAA = "kaa" - """Kara-Kalpak (Latin)""" + """Kara-Kalpak (Latin).""" CSB = "csb" - """Kashubian""" + """Kashubian.""" KK_CYRL = "kk-cyrl" - """Kazakh (Cyrillic)""" + """Kazakh (Cyrillic).""" KK_LATN = "kk-latn" - """Kazakh (Latin)""" + """Kazakh (Latin).""" KLR = "klr" - """Khaling""" + """Khaling.""" KHA = "kha" - """Khasi""" + """Khasi.""" QUC = "quc" - """K'iche'""" + """K'iche'.""" KO = "ko" - """Korean""" + """Korean.""" KFQ = "kfq" - """Korku""" + """Korku.""" KPY = "kpy" - """Koryak""" + """Koryak.""" KOS = "kos" - """Kosraean""" + """Kosraean.""" KUM = "kum" - """Kumyk (Cyrillic)""" + """Kumyk (Cyrillic).""" KU_ARAB = "ku-arab" - """Kurdish (Arabic)""" + """Kurdish (Arabic).""" KU_LATN = "ku-latn" - """Kurdish (Latin)""" + """Kurdish (Latin).""" KRU = "kru" - """Kurukh (Devanagiri)""" + """Kurukh (Devanagiri).""" KY = "ky" - """Kyrgyz (Cyrillic)""" + """Kyrgyz (Cyrillic).""" LKT = "lkt" - """Lakota""" + """Lakota.""" LA = "la" - """Latin""" + """Latin.""" LT = "lt" - """Lithuanian""" + """Lithuanian.""" DSB = "dsb" - """Lower Sorbian""" + """Lower Sorbian.""" SMJ = "smj" - """Lule Sami""" + """Lule Sami.""" LB = "lb" - """Luxembourgish""" + """Luxembourgish.""" BFZ = "bfz" - """Mahasu Pahari (Devanagiri)""" + """Mahasu Pahari (Devanagiri).""" MS = "ms" - """Malay (Latin)""" + """Malay (Latin).""" MT = "mt" - """Maltese""" + """Maltese.""" KMJ = "kmj" - """Malto (Devanagiri)""" + """Malto (Devanagiri).""" GV = "gv" - """Manx""" + """Manx.""" MI = "mi" - """Maori""" + """Maori.""" MR = "mr" - """Marathi""" + """Marathi.""" MN = "mn" - """Mongolian (Cyrillic)""" + """Mongolian (Cyrillic).""" CNR_CYRL = "cnr-cyrl" - """Montenegrin (Cyrillic)""" + """Montenegrin (Cyrillic).""" CNR_LATN = "cnr-latn" - """Montenegrin (Latin)""" + """Montenegrin (Latin).""" NAP = "nap" - """Neapolitan""" + """Neapolitan.""" NE = "ne" - """Nepali""" + """Nepali.""" NIU = "niu" - """Niuean""" + """Niuean.""" NOG = "nog" - """Nogay""" + """Nogay.""" SME = "sme" - """Northern Sami (Latin)""" + """Northern Sami (Latin).""" NB = "nb" - """Norwegian""" + """Norwegian.""" NO = "no" - """Norwegian""" + """Norwegian.""" OC = "oc" - """Occitan""" + """Occitan.""" OS = "os" - """Ossetic""" + """Ossetic.""" PS = "ps" - """Pashto""" + """Pashto.""" FA = "fa" - """Persian""" + """Persian.""" PL = "pl" - """Polish""" + """Polish.""" PT = "pt" - """Portuguese""" + """Portuguese.""" PA = "pa" - """Punjabi (Arabic)""" + """Punjabi (Arabic).""" KSH = "ksh" - """Ripuarian""" + """Ripuarian.""" RO = "ro" - """Romanian""" + """Romanian.""" RM = "rm" - """Romansh""" + """Romansh.""" RU = "ru" - """Russian""" + """Russian.""" SCK = "sck" - """Sadri (Devanagiri)""" + """Sadri (Devanagiri).""" SM = "sm" - """Samoan (Latin)""" + """Samoan (Latin).""" SA = "sa" - """Sanskrit (Devanagiri)""" + """Sanskrit (Devanagiri).""" SAT = "sat" - """Santali (Devanagiri)""" + """Santali (Devanagiri).""" SCO = "sco" - """Scots""" + """Scots.""" GD = "gd" - """Scottish Gaelic""" + """Scottish Gaelic.""" SR = "sr" - """Serbian (Latin)""" + """Serbian (Latin).""" SR_CYRL = "sr-Cyrl" - """Serbian (Cyrillic)""" + """Serbian (Cyrillic).""" SR_LATN = "sr-Latn" - """Serbian (Latin)""" + """Serbian (Latin).""" XSR = "xsr" - """Sherpa (Devanagiri)""" + """Sherpa (Devanagiri).""" SRX = "srx" - """Sirmauri (Devanagiri)""" + """Sirmauri (Devanagiri).""" SMS = "sms" - """Skolt Sami""" + """Skolt Sami.""" SK = "sk" - """Slovak""" + """Slovak.""" SL = "sl" - """Slovenian""" + """Slovenian.""" SO = "so" - """Somali (Arabic)""" + """Somali (Arabic).""" SMA = "sma" - """Southern Sami""" + """Southern Sami.""" ES = "es" - """Spanish""" + """Spanish.""" SW = "sw" - """Swahili (Latin)""" + """Swahili (Latin).""" SV = "sv" - """Swedish""" + """Swedish.""" TG = "tg" - """Tajik (Cyrillic)""" + """Tajik (Cyrillic).""" TT = "tt" - """Tatar (Latin)""" + """Tatar (Latin).""" TET = "tet" - """Tetum""" + """Tetum.""" THF = "thf" - """Thangmi""" + """Thangmi.""" TO = "to" - """Tongan""" + """Tongan.""" TR = "tr" - """Turkish""" + """Turkish.""" TK = "tk" - """Turkmen (Latin)""" + """Turkmen (Latin).""" TYV = "tyv" - """Tuvan""" + """Tuvan.""" HSB = "hsb" - """Upper Sorbian""" + """Upper Sorbian.""" UR = "ur" - """Urdu""" + """Urdu.""" UG = "ug" - """Uyghur (Arabic)""" + """Uyghur (Arabic).""" UZ_ARAB = "uz-arab" - """Uzbek (Arabic)""" + """Uzbek (Arabic).""" UZ_CYRL = "uz-cyrl" - """Uzbek (Cyrillic)""" + """Uzbek (Cyrillic).""" UZ = "uz" - """Uzbek (Latin)""" + """Uzbek (Latin).""" VO = "vo" - """Volapük""" + """Volapük.""" WAE = "wae" - """Walser""" + """Walser.""" CY = "cy" - """Welsh""" + """Welsh.""" FY = "fy" - """Western Frisian""" + """Western Frisian.""" YUA = "yua" - """Yucatec Maya""" + """Yucatec Maya.""" ZA = "za" - """Zhuang""" + """Zhuang.""" ZU = "zu" - """Zulu""" + """Zulu.""" UNK = "unk" - """Unknown (All)""" - IS_ENUM = "is" - """Icelandic""" + """Unknown (All).""" class PermissionFilter(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1549,14 +1504,14 @@ class RankingOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represents score to use for sort order of documents.""" BOOSTED_RERANKER_SCORE = "BoostedRerankerScore" - """Sets sort order as BoostedRerankerScore""" - RE_RANKER_SCORE = "RerankerScore" - """Sets sort order as ReRankerScore""" + """Sets sort order as BoostedRerankerScore.""" + RERANKER_SCORE = "RerankerScore" + """Sets sort order as ReRankerScore.""" class RegexFlags(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Defines flags that can be combined to control how regular expressions are used in the pattern - analyzer and pattern tokenizer. + """Defines a regular expression flag that can be used in the pattern analyzer and pattern + tokenizer. """ CANON_EQ = "CANON_EQ" @@ -1676,42 +1631,9 @@ class SearchIndexPermissionFilterOption(str, Enum, metaclass=CaseInsensitiveEnum """A value indicating whether permission filtering is enabled for the index.""" ENABLED = "enabled" + """enabled.""" DISABLED = "disabled" - - -class SentimentSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Deprecated. The language codes supported for input text by SentimentSkill.""" - - DA = "da" - """Danish""" - NL = "nl" - """Dutch""" - EN = "en" - """English""" - FI = "fi" - """Finnish""" - FR = "fr" - """French""" - DE = "de" - """German""" - EL = "el" - """Greek""" - IT = "it" - """Italian""" - NO = "no" - """Norwegian (Bokmaal)""" - PL = "pl" - """Polish""" - PT_PT = "pt-PT" - """Portuguese (Portugal)""" - RU = "ru" - """Russian""" - ES = "es" - """Spanish""" - SV = "sv" - """Swedish""" - TR = "tr" - """Turkish""" + """disabled.""" class SnowballTokenFilterLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1785,73 +1707,71 @@ class SplitSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The language codes supported for input text by SplitSkill.""" AM = "am" - """Amharic""" + """Amharic.""" BS = "bs" - """Bosnian""" + """Bosnian.""" CS = "cs" - """Czech""" + """Czech.""" DA = "da" - """Danish""" + """Danish.""" DE = "de" - """German""" + """German.""" EN = "en" - """English""" + """English.""" ES = "es" - """Spanish""" + """Spanish.""" ET = "et" - """Estonian""" + """Estonian.""" FI = "fi" - """Finnish""" + """Finnish.""" FR = "fr" - """French""" + """French.""" HE = "he" - """Hebrew""" + """Hebrew.""" HI = "hi" - """Hindi""" + """Hindi.""" HR = "hr" - """Croatian""" + """Croatian.""" HU = "hu" - """Hungarian""" + """Hungarian.""" ID = "id" - """Indonesian""" - IS = "is" - """Icelandic""" + """Indonesian.""" + ISEnum = "is" + """Icelandic.""" IT = "it" - """Italian""" + """Italian.""" JA = "ja" - """Japanese""" + """Japanese.""" KO = "ko" - """Korean""" + """Korean.""" LV = "lv" - """Latvian""" + """Latvian.""" NB = "nb" - """Norwegian""" + """Norwegian.""" NL = "nl" - """Dutch""" + """Dutch.""" PL = "pl" - """Polish""" + """Polish.""" PT = "pt" - """Portuguese (Portugal)""" + """Portuguese (Portugal).""" PT_BR = "pt-br" - """Portuguese (Brazil)""" + """Portuguese (Brazil).""" RU = "ru" - """Russian""" + """Russian.""" SK = "sk" - """Slovak""" + """Slovak.""" SL = "sl" - """Slovenian""" + """Slovenian.""" SR = "sr" - """Serbian""" + """Serbian.""" SV = "sv" - """Swedish""" + """Swedish.""" TR = "tr" - """Turkish""" + """Turkish.""" UR = "ur" - """Urdu""" + """Urdu.""" ZH = "zh" - """Chinese (Simplified)""" - IS_ENUM = "is" - """Icelandic""" + """Chinese (Simplified).""" class SplitSkillUnit(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1942,11 +1862,11 @@ class StemmerTokenFilterLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): LATVIAN = "latvian" """Selects the Lucene stemming tokenizer for Latvian.""" NORWEGIAN = "norwegian" - """Selects the Lucene stemming tokenizer for Norwegian (Bokmål).""" + """Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l).""" LIGHT_NORWEGIAN = "lightNorwegian" - """Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does light stemming.""" + """Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l) that does light stemming.""" MINIMAL_NORWEGIAN = "minimalNorwegian" - """Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does minimal stemming.""" + """Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l) that does minimal stemming.""" LIGHT_NYNORSK = "lightNynorsk" """Selects the Lucene stemming tokenizer for Norwegian (Nynorsk) that does light stemming.""" MINIMAL_NYNORSK = "minimalNynorsk" @@ -2057,151 +1977,149 @@ class TextTranslationSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta) """The language codes supported for input text by TextTranslationSkill.""" AF = "af" - """Afrikaans""" + """Afrikaans.""" AR = "ar" - """Arabic""" + """Arabic.""" BN = "bn" - """Bangla""" + """Bangla.""" BS = "bs" - """Bosnian (Latin)""" + """Bosnian (Latin).""" BG = "bg" - """Bulgarian""" + """Bulgarian.""" YUE = "yue" - """Cantonese (Traditional)""" + """Cantonese (Traditional).""" CA = "ca" - """Catalan""" + """Catalan.""" ZH_HANS = "zh-Hans" - """Chinese Simplified""" + """Chinese Simplified.""" ZH_HANT = "zh-Hant" - """Chinese Traditional""" + """Chinese Traditional.""" HR = "hr" - """Croatian""" + """Croatian.""" CS = "cs" - """Czech""" + """Czech.""" DA = "da" - """Danish""" + """Danish.""" NL = "nl" - """Dutch""" + """Dutch.""" EN = "en" - """English""" + """English.""" ET = "et" - """Estonian""" + """Estonian.""" FJ = "fj" - """Fijian""" + """Fijian.""" FIL = "fil" - """Filipino""" + """Filipino.""" FI = "fi" - """Finnish""" + """Finnish.""" FR = "fr" - """French""" + """French.""" DE = "de" - """German""" + """German.""" EL = "el" - """Greek""" + """Greek.""" HT = "ht" - """Haitian Creole""" + """Haitian Creole.""" HE = "he" - """Hebrew""" + """Hebrew.""" HI = "hi" - """Hindi""" + """Hindi.""" MWW = "mww" - """Hmong Daw""" + """Hmong Daw.""" HU = "hu" - """Hungarian""" - IS = "is" - """Icelandic""" + """Hungarian.""" + ISEnum = "is" + """Icelandic.""" ID = "id" - """Indonesian""" + """Indonesian.""" IT = "it" - """Italian""" + """Italian.""" JA = "ja" - """Japanese""" + """Japanese.""" SW = "sw" - """Kiswahili""" + """Kiswahili.""" TLH = "tlh" - """Klingon""" + """Klingon.""" TLH_LATN = "tlh-Latn" - """Klingon (Latin script)""" + """Klingon (Latin script).""" TLH_PIQD = "tlh-Piqd" - """Klingon (Klingon script)""" + """Klingon (Klingon script).""" KO = "ko" - """Korean""" + """Korean.""" LV = "lv" - """Latvian""" + """Latvian.""" LT = "lt" - """Lithuanian""" + """Lithuanian.""" MG = "mg" - """Malagasy""" + """Malagasy.""" MS = "ms" - """Malay""" + """Malay.""" MT = "mt" - """Maltese""" + """Maltese.""" NB = "nb" - """Norwegian""" + """Norwegian.""" FA = "fa" - """Persian""" + """Persian.""" PL = "pl" - """Polish""" + """Polish.""" PT = "pt" - """Portuguese""" + """Portuguese.""" PT_BR = "pt-br" - """Portuguese (Brazil)""" + """Portuguese (Brazil).""" PT_PT = "pt-PT" - """Portuguese (Portugal)""" + """Portuguese (Portugal).""" OTQ = "otq" - """Queretaro Otomi""" + """Queretaro Otomi.""" RO = "ro" - """Romanian""" + """Romanian.""" RU = "ru" - """Russian""" + """Russian.""" SM = "sm" - """Samoan""" + """Samoan.""" SR_CYRL = "sr-Cyrl" - """Serbian (Cyrillic)""" + """Serbian (Cyrillic).""" SR_LATN = "sr-Latn" - """Serbian (Latin)""" + """Serbian (Latin).""" SK = "sk" - """Slovak""" + """Slovak.""" SL = "sl" - """Slovenian""" + """Slovenian.""" ES = "es" - """Spanish""" + """Spanish.""" SV = "sv" - """Swedish""" + """Swedish.""" TY = "ty" - """Tahitian""" + """Tahitian.""" TA = "ta" - """Tamil""" + """Tamil.""" TE = "te" - """Telugu""" + """Telugu.""" TH = "th" - """Thai""" + """Thai.""" TO = "to" - """Tongan""" + """Tongan.""" TR = "tr" - """Turkish""" + """Turkish.""" UK = "uk" - """Ukrainian""" + """Ukrainian.""" UR = "ur" - """Urdu""" + """Urdu.""" VI = "vi" - """Vietnamese""" + """Vietnamese.""" CY = "cy" - """Welsh""" + """Welsh.""" YUA = "yua" - """Yucatec Maya""" + """Yucatec Maya.""" GA = "ga" - """Irish""" + """Irish.""" KN = "kn" - """Kannada""" + """Kannada.""" MI = "mi" - """Maori""" + """Maori.""" ML = "ml" - """Malayalam""" + """Malayalam.""" PA = "pa" - """Punjabi""" - IS_ENUM = "is" - """Icelandic""" + """Punjabi.""" class TokenCharacterKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -2224,109 +2142,141 @@ class TokenFilterName(str, Enum, metaclass=CaseInsensitiveEnumMeta): ARABIC_NORMALIZATION = "arabic_normalization" """A token filter that applies the Arabic normalizer to normalize the orthography. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html + `_.""" APOSTROPHE = "apostrophe" """Strips all characters after an apostrophe (including the apostrophe itself). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/tr/ApostropheFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/tr/ApostropheFilter.html + `_.""" ASCII_FOLDING = "asciifolding" """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such equivalents exist. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html + `_.""" CJK_BIGRAM = "cjk_bigram" """Forms bigrams of CJK terms that are generated from the standard tokenizer. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html + `_.""" CJK_WIDTH = "cjk_width" - """Normalizes CJK width differences. Folds fullwidth ASCII variants into the equivalent basic + """Normalizes CJK width differences. Folds full-width ASCII variants into the equivalent basic Latin, and half-width Katakana variants into the equivalent Kana. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html + `_.""" CLASSIC = "classic" """Removes English possessives, and dots from acronyms. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicFilter.html + `_.""" COMMON_GRAM = "common_grams" """Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed too, with bigrams overlaid. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html + `_.""" EDGE_N_GRAM = "edgeNGram_v2" """Generates n-grams of the given size(s) starting from the front or the back of an input token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html + `_.""" ELISION = "elision" """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html + `_.""" GERMAN_NORMALIZATION = "german_normalization" """Normalizes German characters according to the heuristics of the German2 snowball algorithm. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html + `_.""" HINDI_NORMALIZATION = "hindi_normalization" """Normalizes text in Hindi to remove some differences in spelling variations. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html + `_.""" INDIC_NORMALIZATION = "indic_normalization" """Normalizes the Unicode representation of text in Indian languages. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html + `_.""" KEYWORD_REPEAT = "keyword_repeat" """Emits each incoming token twice, once as keyword and once as non-keyword. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html + `_.""" K_STEM = "kstem" """A high-performance kstem filter for English. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html + `_.""" LENGTH = "length" """Removes words that are too long or too short. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html + `_.""" LIMIT = "limit" """Limits the number of tokens while indexing. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html + `_.""" LOWERCASE = "lowercase" """Normalizes token text to lower case. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html + `_.""" N_GRAM = "nGram_v2" """Generates n-grams of the given size(s). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html + `_.""" PERSIAN_NORMALIZATION = "persian_normalization" """Applies normalization for Persian. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html + `_.""" PHONETIC = "phonetic" """Create tokens for phonetic matches. See - https://lucene.apache.org/core/4_10_3/analyzers-phonetic/org/apache/lucene/analysis/phonetic/package-tree.html""" + `https://lucene.apache.org/core/4_10_3/analyzers-phonetic/org/apache/lucene/analysis/phonetic/package-tree.html + `_.""" PORTER_STEM = "porter_stem" """Uses the Porter stemming algorithm to transform the token stream. See - http://tartarus.org/~martin/PorterStemmer""" + `http://tartarus.org/~martin/PorterStemmer `_.""" REVERSE = "reverse" """Reverses the token string. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html + `_.""" SCANDINAVIAN_NORMALIZATION = "scandinavian_normalization" """Normalizes use of the interchangeable Scandinavian characters. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html + `_.""" SCANDINAVIAN_FOLDING_NORMALIZATION = "scandinavian_folding" - """Folds Scandinavian characters åÅäæÄÆ->a and öÖøØ->o. It also discriminates against use of - double vowels aa, ae, ao, oe and oo, leaving just the first one. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html""" + """Folds Scandinavian characters åÅäæÄÆ->a and öÖøØ->o. It also discriminates + against use of double vowels aa, ae, ao, oe and oo, leaving just the first one. See + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html + `_.""" SHINGLE = "shingle" """Creates combinations of tokens as a single token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/shingle/ShingleFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/shingle/ShingleFilter.html + `_.""" SNOWBALL = "snowball" """A filter that stems words using a Snowball-generated stemmer. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/snowball/SnowballFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/snowball/SnowballFilter.html + `_.""" SORANI_NORMALIZATION = "sorani_normalization" """Normalizes the Unicode representation of Sorani text. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html + `_.""" STEMMER = "stemmer" """Language specific stemming filter. See - https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters""" + `https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters + `_.""" STOPWORDS = "stopwords" """Removes stop words from a token stream. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html + `_.""" TRIM = "trim" """Trims leading and trailing whitespace from tokens. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html + `_.""" TRUNCATE = "truncate" """Truncates the terms to a specific length. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html + `_.""" UNIQUE = "unique" """Filters out tokens with same text as the previous token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html + `_.""" UPPERCASE = "uppercase" """Normalizes token text to upper case. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html + `_.""" WORD_DELIMITER = "word_delimiter" """Splits words into subwords and performs optional transformations on subword groups.""" @@ -2379,7 +2329,9 @@ class VectorSearchCompressionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): component of a vector using binary values, thereby reducing the overall data size.""" -class VectorSearchCompressionRescoreStorageMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class VectorSearchCompressionRescoreStorageMethod( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): """The storage method for the original full-precision vectors used for rescoring and internal index operations. """ @@ -2398,6 +2350,7 @@ class VectorSearchCompressionTarget(str, Enum, metaclass=CaseInsensitiveEnumMeta """The quantized data type of compressed vector values.""" INT8 = "int8" + """8-bit signed integer.""" class VectorSearchVectorizerKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py deleted file mode 100644 index 140cc95e0d51..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py +++ /dev/null @@ -1,930 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Dict, Union, List, Optional, MutableMapping, Callable, cast -from typing_extensions import Self -from .._generated._utils import serialization as _serialization -from ._edm import Collection, ComplexType, String -from .._generated.models import ( - SearchField as _SearchField, - SearchIndex as _SearchIndex, - PatternTokenizer as _PatternTokenizer, - LexicalAnalyzerName, - VectorEncodingFormat, - SearchFieldDataType, - ScoringProfile, - CorsOptions, - SearchSuggester, - LexicalAnalyzer, - LexicalTokenizer, - TokenFilter, - CharFilter, - LexicalNormalizer, - SimilarityAlgorithm, - SemanticSearch, - VectorSearch, - SearchIndexPermissionFilterOption, - PermissionFilter, -) -from ._models import ( - pack_analyzer, - unpack_analyzer, - PatternTokenizer, - SearchResourceEncryptionKey, -) - - -__all__ = ("ComplexField", "SearchableField", "SimpleField") - - -class SearchField(_serialization.Model): - # pylint: disable=too-many-instance-attributes - """Represents a field in an index definition, which describes the name, data type, and search - behavior of a field. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the field, which must be unique within the fields collection of the - index or parent field. Required. - :vartype name: str - :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", - "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", - "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". - :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType - :ivar key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type Edm.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is false for simple fields and null for complex fields. - :vartype key: bool - :ivar hidden: Convenience property that mirrors the generated ``retrievable`` flag. Set this to - true to prevent the field from being returned in search results. Defaults to false for simple - fields, true for vector fields, and null for complex fields. - :vartype hidden: bool - :ivar stored: An immutable value indicating whether the field will be persisted separately on - disk to be returned in a search result. You can disable this option if you don't plan to return - the field contents in a search response to save on storage overhead. This can only be set - during index creation and only for vector fields. This property cannot be changed for existing - fields or set as false for new fields. If this property is set to false, ``hidden`` must be set - to true. This property must be true or unset for key fields, for new fields, and for - non-vector fields, and it must be null for complex fields. Disabling this property will reduce - index storage requirements. The default is true for vector fields. - :vartype stored: bool - :ivar searchable: A value indicating whether the field is full-text searchable. This means it will - undergo analysis such as word-breaking during indexing. If you set a searchable field to a value - like "sunny day", internally it will be split into the individual tokens "sunny" and "day". - This enables full-text searches for these terms. Fields of type Edm.String or Collection(Edm.String) - are searchable by default. This property must be false for simple fields of other non-string data - types, and it must be null for complex fields. Note: searchable fields consume extra space in your - index to accommodate additional tokenized versions of the field value for full-text searches. If - you want to save space in your index and you don't need a field to be included in searches, set - searchable to false. - :vartype searchable: bool - :ivar filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so - comparisons are for exact matches only. For example, if you set such a field f to "sunny day", - $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property must - be null for complex fields. Default is true for simple fields and null for complex fields. - :vartype filterable: bool - :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default, the search engine sorts results by score, but in many experiences users - will want to sort by fields in the documents. A simple field can be sortable only if it is - single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex collections - are also multi-valued, and therefore cannot be sortable. This is true whether it's an immediate - parent field, or an ancestor field, that's the complex collection. Complex fields cannot be - sortable and the sortable property must be null for such fields. The default for sortable is true - for single-valued simple fields, false for multi-valued simple fields, and null for complex fields. - :vartype sortable: bool - :ivar facetable: A value indicating whether to enable the field to be referenced in facet queries. - Typically used in a presentation of search results that includes hit count by category (for - example, search for digital cameras and see hits by brand, by megapixels, by price, and so on). - This property must be null for complex fields. Fields of type Edm.GeographyPoint or - Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple fields. - :vartype facetable: bool - :ivar permission_filter: A value indicating whether the field should be used as a permission filter. - Known values are: "userIds", "groupIds", and "rbacScope". - :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :ivar sensitivity_label: A value indicating whether the field should be used for sensitivity label - filtering. This enables document-level filtering based on Microsoft Purview sensitivity labels. - :vartype sensitivity_label: bool - :ivar analyzer_name: The name of the analyzer to use for the field. This option can be used only with - searchable fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once - the analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known - values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", - "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar search_analyzer_name: The name of the analyzer used at search time for the field. This option - can be used only with searchable fields. It must be set together with indexAnalyzer and it cannot - be set together with the analyzer option. This property cannot be set to the name of a language - analyzer; use the analyzer property instead if you need a language analyzer. This analyzer can be - updated on an existing field. Must be null for complex fields. Known values are: "ar.microsoft", - "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", - "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", - "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", - "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", - "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", - "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", - "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", - "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", - "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", - "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", - "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", "pt-PT.lucene", "pa.microsoft", - "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", "sr-cyrillic.microsoft", - "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", "es.lucene", - "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", "th.lucene", - "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar index_analyzer_name: The name of the analyzer used at indexing time for the field. This option - can be used only with searchable fields. It must be set together with searchAnalyzer and it cannot - be set together with the analyzer option. This property cannot be set to the name of a language - analyzer; use the analyzer property instead if you need a language analyzer. Once the analyzer is - chosen, it cannot be changed for the field. Must be null for complex fields. Known values are: - "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", - "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", - "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", - "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", - "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", - "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", - "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", - "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", - "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", - "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", - "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar normalizer_name: The name of the normalizer to use for the field. This option can be used only - with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it - cannot be changed for the field. Must be null for complex fields. Known values are: "asciifolding", - "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :ivar vector_search_dimensions: The dimensionality of the vector field. - :vartype vector_search_dimensions: int - :ivar vector_search_profile_name: The name of the vector search profile that specifies the algorithm - and vectorizer to use when searching the vector field. - :vartype vector_search_profile_name: str - :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" - :vartype vector_encoding_format: str or ~azure.search.documents.indexes.models.VectorEncodingFormat - :ivar synonym_map_names: A list of the names of synonym maps to associate with this field. This option - can be used only with searchable fields. Currently only one synonym map per field is supported. - Assigning a synonym map to a field ensures that query terms targeting that field are expanded at - query-time using the rules in the synonym map. This attribute can be changed on existing fields. - Must be null or an empty collection for complex fields. - :vartype synonym_map_names: list[str] - :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or - Collection(Edm.ComplexType). Must be null or empty for simple fields. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - """ - - def __init__( - self, - *, - name: str, - type: Union[str, SearchFieldDataType], - key: Optional[bool] = None, - hidden: Optional[bool] = None, - stored: Optional[bool] = None, - searchable: Optional[bool] = None, - filterable: Optional[bool] = None, - sortable: Optional[bool] = None, - facetable: Optional[bool] = None, - permission_filter: Optional[Union[str, PermissionFilter]] = None, - sensitivity_label: Optional[bool] = None, - analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - synonym_map_names: Optional[List[str]] = None, - fields: Optional[List["SearchField"]] = None, - normalizer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - vector_search_dimensions: Optional[int] = None, - vector_search_profile_name: Optional[str] = None, - vector_encoding_format: Optional[Union[str, VectorEncodingFormat]] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.type = type - self.key = key - self.hidden = hidden - self.stored = stored - self.searchable = searchable - self.filterable = filterable - self.sortable = sortable - self.facetable = facetable - self.permission_filter = permission_filter - self.sensitivity_label = sensitivity_label - self.analyzer_name = analyzer_name - self.search_analyzer_name = search_analyzer_name - self.index_analyzer_name = index_analyzer_name - self.synonym_map_names = synonym_map_names - self.fields = fields - self.normalizer_name = normalizer_name - self.vector_search_dimensions = vector_search_dimensions - self.vector_search_profile_name = vector_search_profile_name - self.vector_encoding_format = vector_encoding_format - - def _to_generated(self) -> _SearchField: - fields = [pack_search_field(x) for x in self.fields] if self.fields else None - retrievable = not self.hidden if self.hidden is not None else None - return _SearchField( - name=self.name, - type=self.type, - key=self.key, - retrievable=retrievable, - stored=self.stored, - searchable=self.searchable, - filterable=self.filterable, - sortable=self.sortable, - facetable=self.facetable, - permission_filter=self.permission_filter, - sensitivity_label=self.sensitivity_label, - analyzer=self.analyzer_name, - search_analyzer=self.search_analyzer_name, - index_analyzer=self.index_analyzer_name, - normalizer=self.normalizer_name, - synonym_maps=self.synonym_map_names, - fields=fields, - vector_search_dimensions=self.vector_search_dimensions, - vector_search_profile_name=self.vector_search_profile_name, - vector_encoding_format=self.vector_encoding_format, - ) - - @classmethod - def _from_generated(cls, search_field) -> Optional[Self]: - if not search_field: - return None - # pylint:disable=protected-access - fields = ( - [cast(SearchField, SearchField._from_generated(x)) for x in search_field.fields] - if search_field.fields - else None - ) - hidden = not search_field.retrievable if search_field.retrievable is not None else None - try: - normalizer = search_field.normalizer - except AttributeError: - normalizer = None - return cls( - name=search_field.name, - type=search_field.type, - key=search_field.key, - hidden=hidden, - stored=search_field.stored, - searchable=search_field.searchable, - filterable=search_field.filterable, - sortable=search_field.sortable, - facetable=search_field.facetable, - permission_filter=search_field.permission_filter, - sensitivity_label=search_field.sensitivity_label, - analyzer_name=search_field.analyzer, - search_analyzer_name=search_field.search_analyzer, - index_analyzer_name=search_field.index_analyzer, - normalizer_name=normalizer, - synonym_map_names=search_field.synonym_maps, - fields=fields, - vector_search_dimensions=search_field.vector_search_dimensions, - vector_search_profile_name=search_field.vector_search_profile_name, - vector_encoding_format=search_field.vector_encoding_format, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchField instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchField instance - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchField.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchField instance - :rtype: SearchField - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchField.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -def SimpleField( - *, - name: str, - type: str, - key: bool = False, - hidden: bool = False, - filterable: bool = False, - sortable: bool = False, - facetable: bool = False, - **kw # pylint:disable=unused-argument -) -> SearchField: - """Configure a simple field for an Azure Search Index - - :keyword name: Required. The name of the field, which must be unique within the fields collection - of the index or parent field. - :paramtype name: str - :keyword type: Required. The data type of the field. Possible values include: SearchFieldDataType.String, - SearchFieldDataType.Int32, SearchFieldDataType.Int64, SearchFieldDataType.Double, SearchFieldDataType.Boolean, - SearchFieldDataType.DateTimeOffset, SearchFieldDataType.GeographyPoint, SearchFieldDataType.ComplexType, - from `azure.search.documents.SearchFieldDataType`. - :paramtype type: str - :keyword key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type SearchFieldDataType.String. Key fields can be used to look up documents directly and - update or delete specific documents. Default is False - :paramtype key: bool - :keyword hidden: A value indicating whether the field can be returned in a search result. - You can enable this option if you want to use a field (for example, margin) as a filter, - sorting, or scoring mechanism but do not want the field to be visible to the end user. This - property must be False for key fields. This property can be changed on existing fields. - Enabling this property does not cause any increase in index storage requirements. Default is - False. - :paramtype hidden: bool - :keyword filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - SearchFieldDataType.String or Collection(SearchFieldDataType.String) that are filterable do - not undergo word-breaking, so comparisons are for exact matches only. For example, if you - set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but - $filter=f eq 'sunny day' will. This property must be null for complex fields. Default is False - :paramtype filterable: bool - :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default Azure Cognitive Search sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. The default is - False. - :paramtype sortable: bool - :keyword facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). Fields of type SearchFieldDataType.GeographyPoint or - Collection(SearchFieldDataType.GeographyPoint) cannot be facetable. Default is False. - :paramtype facetable: bool - :return: The search field object. - :rtype: SearchField - """ - result: Dict[str, Any] = { - "name": name, - "type": type, - "key": key, - "searchable": False, - "filterable": filterable, - "facetable": facetable, - "sortable": sortable, - "hidden": hidden, - } - return SearchField(**result) - - -def SearchableField( - *, - name: str, - collection: bool = False, - key: bool = False, - hidden: bool = False, - searchable: bool = True, - filterable: bool = False, - sortable: bool = False, - facetable: bool = False, - analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - synonym_map_names: Optional[List[str]] = None, - **kw # pylint:disable=unused-argument -) -> SearchField: - """Configure a searchable text field for an Azure Search Index - - :keyword name: Required. The name of the field, which must be unique within the fields collection - of the index or parent field. - :paramtype name: str - :keyword collection: Whether this search field is a collection (default False) - :paramtype collection: bool - :keyword key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type SearchFieldDataType.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is False - :paramtype key: bool - :keyword hidden: A value indicating whether the field can be returned in a search result. - You can enable this option if you want to use a field (for example, margin) as a filter, - sorting, or scoring mechanism but do not want the field to be visible to the end user. This - property must be False for key fields. This property can be changed on existing fields. - Enabling this property does not cause any increase in index storage requirements. Default is - False. - :paramtype hidden: bool - :keyword searchable: A value indicating whether the field is full-text searchable. This means it - will undergo analysis such as word-breaking during indexing. If you set a searchable field to a - value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Note: searchable fields - consume extra space in your index since Azure Cognitive Search will store an additional - tokenized version of the field value for full-text searches. If you want to save space in your - index and you don't need a field to be included in searches, set searchable to false. Default - is True. - :paramtype searchable: bool - :keyword filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields that are - filterable do not undergo word-breaking, so comparisons are for exact matches only. For example, - if you set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but - $filter=f eq 'sunny day' will. Default is False. - :paramtype filterable: bool - :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default Azure Cognitive Search sorts results by score, but in many experiences - users will want to sort by fields in the documents. The default is False. - :paramtype sortable: bool - :keyword facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). Default is False. - :paramtype facetable: bool - :keyword analyzer_name: The name of the analyzer to use for the field. This option can't be set together - with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed - for the field. Possible values include: 'ar.microsoft', 'ar.lucene', 'hy.lucene', - 'bn.microsoft', 'eu.lucene', 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh- - Hans.microsoft', 'zh-Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', - 'cs.microsoft', 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', - 'en.microsoft', 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', - 'fr.lucene', 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', - 'gu.microsoft', 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', - 'is.microsoft', 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', - 'ja.microsoft', 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', - 'lv.lucene', 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', - 'no.lucene', 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt- - PT.microsoft', 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', - 'ru.lucene', 'sr-cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', - 'es.microsoft', 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', - 'th.microsoft', 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', - 'vi.microsoft', 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', - 'simple', 'stop', 'whitespace'. - :paramtype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword search_analyzer_name: The name of the analyzer used at search time for the field. It must be - set together with indexAnalyzer and it cannot be set together with the analyzer option. This - property cannot be set to the name of a language analyzer; use the analyzer property instead - if you need a language analyzer. This analyzer can be updated on an existing field. Possible - values include: - 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', 'bg.microsoft', - 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh-Hans.lucene', 'zh- - Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', 'cs.lucene', 'da.microsoft', - 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', 'en.lucene', 'et.microsoft', - 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', 'gl.lucene', 'de.microsoft', - 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', 'he.microsoft', 'hi.microsoft', - 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', 'id.microsoft', 'id.lucene', - 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', 'ja.lucene', 'kn.microsoft', - 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', 'lt.microsoft', 'ml.microsoft', - 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', 'fa.lucene', 'pl.microsoft', - 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', 'pt-PT.lucene', - 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- - cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', - 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', - 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', - 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', - 'whitespace'. - :paramtype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword index_analyzer_name: The name of the analyzer used at indexing time for the field. - It must be set together with searchAnalyzer and it cannot be set together with the analyzer - option. This property cannot be set to the name of a language analyzer; use the analyzer - property instead if you need a language analyzer. Once the analyzer is chosen, it cannot be - changed for the field. Possible values include: - 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', - 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh- - Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', - 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', - 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', - 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', - 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', - 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', - 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', - 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', - 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', - 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- - cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', - 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', - 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', - 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', - 'whitespace'. - :paramtype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword synonym_map_names: A list of the names of synonym maps to associate with this field. Currently - only one synonym map per field is supported. Assigning a synonym map to a field ensures that - query terms targeting that field are expanded at query-time using the rules in the synonym map. - This attribute can be changed on existing fields. - :paramtype synonym_map_names: list[str] - :return: The search field object. - :rtype: SearchField - """ - typ = Collection(String) if collection else String - result: Dict[str, Any] = { - "name": name, - "type": typ, - "key": key, - "searchable": searchable, - "filterable": filterable, - "facetable": facetable, - "sortable": sortable, - "hidden": hidden, - } - if analyzer_name: - result["analyzer_name"] = analyzer_name - if search_analyzer_name: - result["search_analyzer_name"] = search_analyzer_name - if index_analyzer_name: - result["index_analyzer_name"] = index_analyzer_name - if synonym_map_names: - result["synonym_map_names"] = synonym_map_names - return SearchField(**result) - - -def ComplexField( - *, - name: str, - collection: bool = False, - fields: Optional[List[SearchField]] = None, - **kw # pylint:disable=unused-argument -) -> SearchField: - """Configure a Complex or Complex collection field for an Azure Search Index - - :keyword name: Required. The name of the field, which must be unique within the fields collection - of the index or parent field. - :paramtype name: str - :keyword collection: Whether this complex field is a collection (default False) - :paramtype collection: bool - :keyword fields: A list of sub-fields - :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] - :return: The search field object. - :rtype: SearchField - """ - typ = Collection(ComplexType) if collection else ComplexType - result: Dict[str, Any] = {"name": name, "type": typ, "fields": fields} - return SearchField(**result) - - -class SearchIndex(_serialization.Model): - # pylint: disable=too-many-instance-attributes - """Represents a search index definition, which describes the fields and search behavior of an - index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the index. Required. - :vartype name: str - :ivar description: The description of the index. - :vartype description: str - :ivar fields: The fields of the index. Required. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - :ivar scoring_profiles: The scoring profiles for the index. - :vartype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] - :ivar default_scoring_profile: The name of the scoring profile to use if none is specified in - the query. If this property is not set and no scoring profile is specified in the query, then - default scoring (tf-idf) will be used. - :vartype default_scoring_profile: str - :ivar cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. - :vartype cors_options: ~azure.search.documents.indexes.models.CorsOptions - :ivar suggesters: The suggesters for the index. - :vartype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] - :ivar analyzers: The analyzers for the index. - :vartype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] - :ivar tokenizers: The tokenizers for the index. - :vartype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] - :ivar token_filters: The token filters for the index. - :vartype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] - :ivar char_filters: The character filters for the index. - :vartype char_filters: list[~azure.search.documents.indexes.models.CharFilter] - :ivar normalizers: The normalizers for the index. - :vartype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data in Azure Cognitive - Search. Once you have encrypted your data, it will always remain encrypted. Azure Cognitive - Search will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your data will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar similarity: The type of similarity algorithm to be used when scoring and ranking the - documents matching a search query. The similarity algorithm can only be defined at index - creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity - algorithm is used. - :vartype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm - :ivar semantic_search: Defines parameters for a search index that influence semantic capabilities. - :vartype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch - :ivar vector_search: Contains configuration options related to vector search. - :vartype vector_search: ~azure.search.documents.indexes.models.VectorSearch - :ivar permission_filter_option: A value indicating whether permission filtering is enabled for - the index. Known values are: "enabled" and "disabled". - :vartype permission_filter_option: str or - ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption - :ivar purview_enabled: A value indicating whether the index is leveraging Purview-specific - features. This property defaults to false and cannot be changed after index creation. - :vartype purview_enabled: bool - :ivar e_tag: The ETag of the index. - :vartype e_tag: str - """ - - def __init__( - self, - *, - name: str, - fields: List[SearchField], - description: Optional[str] = None, - scoring_profiles: Optional[List[ScoringProfile]] = None, - default_scoring_profile: Optional[str] = None, - cors_options: Optional[CorsOptions] = None, - suggesters: Optional[List[SearchSuggester]] = None, - analyzers: Optional[List[LexicalAnalyzer]] = None, - tokenizers: Optional[List[LexicalTokenizer]] = None, - token_filters: Optional[List[TokenFilter]] = None, - char_filters: Optional[List[CharFilter]] = None, - normalizers: Optional[List[LexicalNormalizer]] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - similarity: Optional[SimilarityAlgorithm] = None, - semantic_search: Optional[SemanticSearch] = None, - vector_search: Optional[VectorSearch] = None, - permission_filter_option: Optional[Union[str, SearchIndexPermissionFilterOption]] = None, - purview_enabled: Optional[bool] = None, - e_tag: Optional[str] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.fields = fields - self.description = description - self.scoring_profiles = scoring_profiles - self.default_scoring_profile = default_scoring_profile - self.cors_options = cors_options - self.suggesters = suggesters - self.analyzers = analyzers - self.tokenizers = tokenizers - self.token_filters = token_filters - self.char_filters = char_filters - self.normalizers = normalizers - self.encryption_key = encryption_key - self.similarity = similarity - self.semantic_search = semantic_search - self.vector_search = vector_search - self.permission_filter_option = permission_filter_option - self.purview_enabled = purview_enabled - self.e_tag = e_tag - - def _to_generated(self) -> _SearchIndex: - if self.analyzers: - analyzers = [pack_analyzer(x) for x in self.analyzers] # type: ignore # mypy: ignore - else: - analyzers = None - if self.tokenizers: - tokenizers = [ - x._to_generated() if isinstance(x, PatternTokenizer) else x # pylint:disable=protected-access - for x in self.tokenizers - ] - else: - tokenizers = None - if self.fields: - fields = [pack_search_field(x) for x in self.fields] - else: - fields = [] - return _SearchIndex( - name=self.name, - description=self.description, - fields=fields, - scoring_profiles=self.scoring_profiles, - default_scoring_profile=self.default_scoring_profile, - cors_options=self.cors_options, - suggesters=self.suggesters, - analyzers=analyzers, - tokenizers=tokenizers, - token_filters=self.token_filters, - char_filters=self.char_filters, - normalizers=self.normalizers, - # pylint:disable=protected-access - encryption_key=self.encryption_key._to_generated() if self.encryption_key else None, - similarity=self.similarity, - semantic_search=self.semantic_search, - e_tag=self.e_tag, - vector_search=self.vector_search, - permission_filter_option=self.permission_filter_option, - purview_enabled=self.purview_enabled, - ) - - @classmethod - def _from_generated(cls, search_index) -> Optional[Self]: - if not search_index: - return None - if search_index.analyzers: - analyzers = [unpack_analyzer(x) for x in search_index.analyzers] # type: ignore - else: - analyzers = None - if search_index.tokenizers: - tokenizers = [ - ( - PatternTokenizer._from_generated(x) # pylint:disable=protected-access - if isinstance(x, _PatternTokenizer) - else x - ) - for x in search_index.tokenizers - ] - else: - tokenizers = None - if search_index.fields: - # pylint:disable=protected-access - fields = [cast(SearchField, SearchField._from_generated(x)) for x in search_index.fields] - else: - fields = [] - try: - normalizers = search_index.normalizers - except AttributeError: - normalizers = None - return cls( - name=search_index.name, - description=search_index.description, - fields=fields, - scoring_profiles=search_index.scoring_profiles, - default_scoring_profile=search_index.default_scoring_profile, - cors_options=search_index.cors_options, - suggesters=search_index.suggesters, - analyzers=analyzers, - tokenizers=tokenizers, - token_filters=search_index.token_filters, - char_filters=search_index.char_filters, - normalizers=normalizers, - # pylint:disable=protected-access - encryption_key=SearchResourceEncryptionKey._from_generated(search_index.encryption_key), - similarity=search_index.similarity, - semantic_search=search_index.semantic_search, - e_tag=search_index.e_tag, - vector_search=search_index.vector_search, - permission_filter_option=search_index.permission_filter_option, - purview_enabled=search_index.purview_enabled, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndex instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndex instance - :rtype: SearchIndex - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndex.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndex instance - :rtype: SearchIndex - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchIndex.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -def pack_search_field(search_field: SearchField) -> _SearchField: - if isinstance(search_field, dict): - name = search_field.get("name") - assert name is not None # Hint for mypy - field_type = search_field.get("type") - assert field_type is not None # Hint for mypy - key = search_field.get("key") - hidden = search_field.get("hidden") - retrievable = not hidden if hidden is not None else None - searchable = search_field.get("searchable") - filterable = search_field.get("filterable") - sortable = search_field.get("sortable") - facetable = search_field.get("facetable") - permission_filter = search_field.get("permission_filter") - analyzer_name = search_field.get("analyzer_name") - sensitivity_label = search_field.get("sensitivity_label") - search_analyzer_name = search_field.get("search_analyzer_name") - index_analyzer_name = search_field.get("index_analyzer_name") - normalizer = search_field.get("normalizer") - synonym_map_names = search_field.get("synonym_map_names") - fields = search_field.get("fields") - fields = [pack_search_field(x) for x in fields] if fields else None - vector_search_dimensions = search_field.get("vector_search_dimensions") - vector_search_profile_name = search_field.get("vector_search_profile_name") - return _SearchField( - name=name, - type=field_type, - key=key, - retrievable=retrievable, - searchable=searchable, - filterable=filterable, - sortable=sortable, - facetable=facetable, - permission_filter=permission_filter, - sensitivity_label=sensitivity_label, - analyzer=analyzer_name, - search_analyzer=search_analyzer_name, - index_analyzer=index_analyzer_name, - normalizer=normalizer, - synonym_maps=synonym_map_names, - fields=fields, - vector_search_dimensions=vector_search_dimensions, - vector_search_profile_name=vector_search_profile_name, - ) - return search_field._to_generated() # pylint:disable=protected-access diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 31128c0a672d..3037077d35cd 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -1,226 +1,888 @@ -# pylint: disable=too-many-lines -# ------------------------------------------------------------------------- +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- - -from typing import Any, List, Optional, MutableMapping, Dict, Callable, Union -from enum import Enum -from typing_extensions import Self -from azure.core import CaseInsensitiveEnumMeta -from .._generated._utils import serialization as _serialization -from .._generated.models import ( - LexicalAnalyzer, - LexicalTokenizer, - AnalyzeRequest, - CustomAnalyzer as _CustomAnalyzer, - EntityRecognitionSkillV3 as _EntityRecognitionSkillV3, - PatternAnalyzer as _PatternAnalyzer, - PatternTokenizer as _PatternTokenizer, - SearchResourceEncryptionKey as _SearchResourceEncryptionKey, - SearchIndexerDataSource as _SearchIndexerDataSource, - SearchIndexerSkill, - SearchIndexerSkillset as _SearchIndexerSkillset, - SentimentSkillV3 as _SentimentSkillV3, - SynonymMap as _SynonymMap, - DataSourceCredentials, - AzureActiveDirectoryApplicationCredentials, - CognitiveServicesAccount, - SearchIndexerKnowledgeStore, - SearchIndexerIndexProjection, - SearchIndexerDataContainer, - DataChangeDetectionPolicy, - DataDeletionDetectionPolicy, - SearchIndexerDataIdentity, - SearchIndexer as _SearchIndexer, - IndexingSchedule, - IndexingParameters, - FieldMapping, - SearchIndexerCache, - IndexerPermissionOption, +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from ..._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import ( + KnowledgeBaseModelKind, + KnowledgeSourceKind, + VectorSearchAlgorithmKind, + VectorSearchCompressionKind, + VectorSearchVectorizerKind, ) -DELIMITER = "|" +if TYPE_CHECKING: + from .. import models as _models + from ...knowledgebases import models as _knowledgebases_models3 -class SearchIndexerSkillset(_serialization.Model): - """A list of skills. +class CognitiveServicesAccount(_Model): + """Base type for describing any Azure AI service resource attached to a skillset. - All required parameters must be populated in order to send to server. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AIServicesAccountIdentity, AIServicesAccountKey, CognitiveServicesAccountKey, + DefaultCognitiveServicesAccount - :ivar name: The name of the skillset. Required. + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description of the Azure AI service resource attached to a skillset.""" + + @overload + def __init__( + self, + *, + odata_type: str, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AIServicesAccountIdentity(CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.AIServicesByIdentity"): + """The multi-region account of an Azure AI service resource that's attached to a skillset. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar identity: The user-assigned managed identity used for connections to AI Service. If not + specified, the system-assigned managed identity is used. On updates to the skillset, if the + identity is unspecified, the value remains unchanged. If set to "none", the value of this + property is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. + :vartype subdomain_url: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.AIServicesByIdentity". + :vartype odata_type: str + """ + + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for connections to AI Service. If not specified, the + system-assigned managed identity is used. On updates to the skillset, if the identity is + unspecified, the value remains unchanged. If set to \"none\", the value of this property is + cleared.""" + subdomain_url: str = rest_field(name="subdomainUrl", visibility=["read", "create", "update", "delete", "query"]) + """The subdomain url for the corresponding AI Service. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.AIServicesByIdentity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.AIServicesByIdentity\".""" + + @overload + def __init__( + self, + *, + subdomain_url: str, + description: Optional[str] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.AIServicesByIdentity" # type: ignore + + +class AIServicesAccountKey(CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.AIServicesByKey"): + """The account key of an Azure AI service resource that's attached to a skillset, to be used with + the resource's subdomain. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar key: The key used to provision the Azure AI service resource attached to a skillset. + Required. + :vartype key: str + :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. + :vartype subdomain_url: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.AIServicesByKey". + :vartype odata_type: str + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key used to provision the Azure AI service resource attached to a skillset. Required.""" + subdomain_url: str = rest_field(name="subdomainUrl", visibility=["read", "create", "update", "delete", "query"]) + """The subdomain url for the corresponding AI Service. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.AIServicesByKey"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.AIServicesByKey\".""" + + @overload + def __init__( + self, + *, + key: str, + subdomain_url: str, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.AIServicesByKey" # type: ignore + + +class AIServicesVisionParameters(_Model): + """Specifies the AI Services Vision parameters for vectorizing a query image or text. + + :ivar model_version: The version of the model to use when calling the AI Services Vision + service. It will default to the latest available when not specified. Required. + :vartype model_version: str + :ivar resource_uri: The resource URI of the AI Services resource. Required. + :vartype resource_uri: str + :ivar api_key: API key of the designated AI Services resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the index, if the identity is unspecified, the value remains unchanged. If + set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + """ + + model_version: str = rest_field(name="modelVersion", visibility=["read", "create", "update", "delete", "query"]) + """The version of the model to use when calling the AI Services Vision service. It will default to + the latest available when not specified. Required.""" + resource_uri: str = rest_field(name="resourceUri", visibility=["read", "create", "update", "delete", "query"]) + """The resource URI of the AI Services resource. Required.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated AI Services resource.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the index, if the identity is unspecified, the value remains unchanged. If set to \"none\", the + value of this property is cleared.""" + + @overload + def __init__( + self, + *, + model_version: str, + resource_uri: str, + api_key: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorSearchVectorizer(_Model): + """Specifies the vectorization method to be used during query time. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AIServicesVisionVectorizer, AzureMachineLearningVectorizer, AzureOpenAIVectorizer, + WebApiVectorizer + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar kind: Type of VectorSearchVectorizer. Required. Known values are: "azureOpenAI", + "customWebApi", "aiServicesVision", and "aml". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind + """ + + __mapping__: dict[str, _Model] = {} + vectorizer_name: str = rest_field(name="name", visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular vectorization method. Required.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of VectorSearchVectorizer. Required. Known values are: \"azureOpenAI\", \"customWebApi\", + \"aiServicesVision\", and \"aml\".""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AIServicesVisionVectorizer(VectorSearchVectorizer, discriminator="aiServicesVision"): + """Clears the identity property of a datasource. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar ai_services_vision_parameters: Contains the parameters specific to AI Services Vision + embedding vectorization. + :vartype ai_services_vision_parameters: + ~azure.search.documents.indexes.models.AIServicesVisionParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings for an image or text input at query time using the Azure + AI Services Vision Vectorize API. + :vartype kind: str or ~azure.search.documents.indexes.models.AI_SERVICES_VISION + """ + + ai_services_vision_parameters: Optional["_models.AIServicesVisionParameters"] = rest_field( + name="aiServicesVisionParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to AI Services Vision embedding vectorization.""" + kind: Literal[VectorSearchVectorizerKind.AI_SERVICES_VISION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings for an image or text input at query time using the Azure AI + Services Vision Vectorize API.""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + ai_services_vision_parameters: Optional["_models.AIServicesVisionParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AI_SERVICES_VISION # type: ignore + + +class AnalyzedTokenInfo(_Model): + """Information about a token returned by an analyzer. + + :ivar token: The token returned by the analyzer. Required. + :vartype token: str + :ivar start_offset: The index of the first character of the token in the input text. Required. + :vartype start_offset: int + :ivar end_offset: The index of the last character of the token in the input text. Required. + :vartype end_offset: int + :ivar position: The position of the token in the input text relative to other tokens. The first + token in the input text has position 0, the next has position 1, and so on. Depending on the + analyzer used, some tokens might have the same position, for example if they are synonyms of + each other. Required. + :vartype position: int + """ + + token: str = rest_field(visibility=["read"]) + """The token returned by the analyzer. Required.""" + start_offset: int = rest_field(name="startOffset", visibility=["read"]) + """The index of the first character of the token in the input text. Required.""" + end_offset: int = rest_field(name="endOffset", visibility=["read"]) + """The index of the last character of the token in the input text. Required.""" + position: int = rest_field(visibility=["read"]) + """The position of the token in the input text relative to other tokens. The first token in the + input text has position 0, the next has position 1, and so on. Depending on the analyzer used, + some tokens might have the same position, for example if they are synonyms of each other. + Required.""" + + +class AnalyzeResult(_Model): + """The result of testing an analyzer on text. + + :ivar tokens: The list of tokens returned by the analyzer specified in the request. Required. + :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] + """ + + tokens: list["_models.AnalyzedTokenInfo"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of tokens returned by the analyzer specified in the request. Required.""" + + @overload + def __init__( + self, + *, + tokens: list["_models.AnalyzedTokenInfo"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AnalyzeTextOptions(_Model): + """Specifies some text and analysis components used to break that text into tokens. + + :ivar text: The text to break into tokens. Required. + :vartype text: str + :ivar analyzer_name: The name of the analyzer to use to break the given text. If this parameter + is not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters + are mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", + "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", + "zh-Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", + "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", + "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", + "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", + "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", + "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", + "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", + "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", + "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", + "pt-PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", + "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", + "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", + "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", + "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", + "simple", "stop", and "whitespace". + :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar tokenizer_name: The name of the tokenizer to use to break the given text. If this + parameter is not specified, you must specify an analyzer instead. The tokenizer and analyzer + parameters are mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", + "letter", "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", + "nGram", "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". + :vartype tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName + :ivar normalizer_name: The name of the normalizer to use to normalize the given text. Known + values are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". + :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :ivar token_filters: An optional list of token filters to use when breaking the given text. + This parameter can only be set when using the tokenizer parameter. + :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] + :ivar char_filters: An optional list of character filters to use when breaking the given text. + This parameter can only be set when using the tokenizer parameter. + :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text to break into tokens. Required.""" + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="analyzer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer to use to break the given text. If this parameter is not specified, + you must specify a tokenizer instead. The tokenizer and analyzer parameters are mutually + exclusive. Known values are: \"ar.microsoft\", \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", + \"eu.lucene\", \"bg.microsoft\", \"bg.lucene\", \"ca.microsoft\", \"ca.lucene\", + \"zh-Hans.microsoft\", \"zh-Hans.lucene\", \"zh-Hant.microsoft\", \"zh-Hant.lucene\", + \"hr.microsoft\", \"cs.microsoft\", \"cs.lucene\", \"da.microsoft\", \"da.lucene\", + \"nl.microsoft\", \"nl.lucene\", \"en.microsoft\", \"en.lucene\", \"et.microsoft\", + \"fi.microsoft\", \"fi.lucene\", \"fr.microsoft\", \"fr.lucene\", \"gl.lucene\", + \"de.microsoft\", \"de.lucene\", \"el.microsoft\", \"el.lucene\", \"gu.microsoft\", + \"he.microsoft\", \"hi.microsoft\", \"hi.lucene\", \"hu.microsoft\", \"hu.lucene\", + \"is.microsoft\", \"id.microsoft\", \"id.lucene\", \"ga.lucene\", \"it.microsoft\", + \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", \"kn.microsoft\", \"ko.microsoft\", + \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", \"lt.microsoft\", \"ml.microsoft\", + \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", \"no.lucene\", \"fa.lucene\", + \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", \"pt-BR.lucene\", \"pt-PT.microsoft\", + \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", \"ro.lucene\", \"ru.microsoft\", + \"ru.lucene\", \"sr-cyrillic.microsoft\", \"sr-latin.microsoft\", \"sk.microsoft\", + \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", \"sv.microsoft\", \"sv.lucene\", + \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", \"th.lucene\", \"tr.microsoft\", + \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", \"standard.lucene\", + \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", \"stop\", and + \"whitespace\".""" + tokenizer_name: Optional[Union[str, "_models.LexicalTokenizerName"]] = rest_field( + name="tokenizer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the tokenizer to use to break the given text. If this parameter is not specified, + you must specify an analyzer instead. The tokenizer and analyzer parameters are mutually + exclusive. Known values are: \"classic\", \"edgeNGram\", \"keyword_v2\", \"letter\", + \"lowercase\", \"microsoft_language_tokenizer\", \"microsoft_language_stemming_tokenizer\", + \"nGram\", \"path_hierarchy_v2\", \"pattern\", \"standard_v2\", \"uax_url_email\", and + \"whitespace\".""" + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( + name="normalizer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the normalizer to use to normalize the given text. Known values are: + \"asciifolding\", \"elision\", \"lowercase\", \"standard\", and \"uppercase\".""" + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """An optional list of token filters to use when breaking the given text. This parameter can only + be set when using the tokenizer parameter.""" + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """An optional list of character filters to use when breaking the given text. This parameter can + only be set when using the tokenizer parameter.""" + + @overload + def __init__( + self, + *, + text: str, + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + tokenizer_name: Optional[Union[str, "_models.LexicalTokenizerName"]] = None, + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TokenFilter(_Model): + """Base type for token filters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AsciiFoldingTokenFilter, CjkBigramTokenFilter, CommonGramTokenFilter, + DictionaryDecompounderTokenFilter, EdgeNGramTokenFilter, EdgeNGramTokenFilterV2, + ElisionTokenFilter, KeepTokenFilter, KeywordMarkerTokenFilter, LengthTokenFilter, + LimitTokenFilter, NGramTokenFilter, NGramTokenFilterV2, PatternCaptureTokenFilter, + PatternReplaceTokenFilter, PhoneticTokenFilter, ShingleTokenFilter, SnowballTokenFilter, + StemmerOverrideTokenFilter, StemmerTokenFilter, StopwordsTokenFilter, SynonymTokenFilter, + TruncateTokenFilter, UniqueTokenFilter, WordDelimiterTokenFilter + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. :vartype name: str - :ivar description: The description of the skillset. + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the token filter. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AsciiFoldingTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.AsciiFoldingTokenFilter"): + """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 + ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such + equivalents exist. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar preserve_original: A value indicating whether the original token will be kept. Default is + false. + :vartype preserve_original: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.AsciiFoldingTokenFilter". + :vartype odata_type: str + """ + + preserve_original: Optional[bool] = rest_field( + name="preserveOriginal", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the original token will be kept. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.AsciiFoldingTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.AsciiFoldingTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + preserve_original: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.AsciiFoldingTokenFilter" # type: ignore + + +class AzureActiveDirectoryApplicationCredentials(_Model): # pylint: disable=name-too-long + """Credentials of a registered application created for your search service, used for authenticated + access to the encryption keys stored in Azure Key Vault. + + :ivar application_id: An AAD Application ID that was granted the required access permissions to + the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID + should not be confused with the Object ID for your AAD Application. Required. + :vartype application_id: str + :ivar application_secret: The authentication key of the specified AAD application. + :vartype application_secret: str + """ + + application_id: str = rest_field(name="applicationId", visibility=["read", "create", "update", "delete", "query"]) + """An AAD Application ID that was granted the required access permissions to the Azure Key Vault + that is to be used when encrypting your data at rest. The Application ID should not be confused + with the Object ID for your AAD Application. Required.""" + application_secret: Optional[str] = rest_field( + name="applicationSecret", visibility=["read", "create", "update", "delete", "query"] + ) + """The authentication key of the specified AAD application.""" + + @overload + def __init__( + self, + *, + application_id: str, + application_secret: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSource(_Model): + """Represents a knowledge source definition. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureBlobKnowledgeSource, IndexedOneLakeKnowledgeSource, IndexedSharePointKnowledgeSource, + RemoteSharePointKnowledgeSource, SearchIndexKnowledgeSource, WebKnowledgeSource + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. :vartype description: str - :ivar skills: A list of skills in the skillset. Required. - :vartype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] - :ivar cognitive_services_account: Details about the Azure AI service to be used when running - skills. - :vartype cognitive_services_account: - ~azure.search.documents.indexes.models.CognitiveServicesAccount - :ivar knowledge_store: Definition of additional projections to Azure blob, table, or files, of - enriched data. - :vartype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore - :ivar index_projection: Definition of additional projections to secondary search index(es). - :vartype index_projection: ~azure.search.documents.indexes.models.SearchIndexerIndexProjection - :ivar e_tag: The ETag of the skillset. + :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", + "azureBlob", "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind + :ivar e_tag: The ETag of the knowledge source. :vartype e_tag: str :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your skillset - definition when you want full assurance that no one, not even Microsoft, can decrypt your - skillset definition. Once you have encrypted your skillset definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your skillset definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + __mapping__: dict[str, _Model] = {} + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the knowledge source. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined description.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The type of the knowledge source. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the knowledge source.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your knowledge source definition when you + want full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted + your knowledge source definition, it will always remain encrypted. The search service will + ignore attempts to set this property to null. You can change this property as needed if you + want to rotate your encryption key; Your knowledge source definition will be unaffected. + Encryption with customer-managed keys is not available for free search services, and is only + available for paid services created on or after January 1, 2019.""" + + @overload + def __init__( + self, + *, + name: str, + kind: str, + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureBlobKnowledgeSource(KnowledgeSource, discriminator="azureBlob"): + """Configuration for Azure Blob Storage knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the knowledge source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that read and ingest data from Azure Blob Storage to a + Search Index. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_BLOB + :ivar azure_blob_parameters: The type of the knowledge source. Required. + :vartype azure_blob_parameters: + ~azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters """ + kind: Literal[KnowledgeSourceKind.AZURE_BLOB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that read and ingest data from Azure Blob Storage to a Search + Index.""" + azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters" = rest_field( + name="azureBlobParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of the knowledge source. Required.""" + + @overload def __init__( self, *, name: str, - skills: List["SearchIndexerSkill"], + azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters", description: Optional[str] = None, - cognitive_services_account: Optional["CognitiveServicesAccount"] = None, - knowledge_store: Optional["SearchIndexerKnowledgeStore"] = None, - index_projection: Optional["SearchIndexerIndexProjection"] = None, e_tag: Optional[str] = None, - encryption_key: Optional["SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - super().__init__(**kwargs) - self.name = name - self.description = description - self.skills = skills - self.cognitive_services_account = cognitive_services_account - self.knowledge_store = knowledge_store - self.index_projection = index_projection - self.e_tag = e_tag - self.encryption_key = encryption_key - - def _to_generated(self) -> _SearchIndexerSkillset: - generated_skills = [] - for skill in self.skills: - if hasattr(skill, "_to_generated"): - generated_skills.append(skill._to_generated()) # pylint:disable=protected-access - else: - generated_skills.append(skill) - assert len(generated_skills) == len(self.skills) - encryption_key = getattr(self, "encryption_key", None) - return _SearchIndexerSkillset( - name=getattr(self, "name", ""), - description=getattr(self, "description", None), - skills=generated_skills, - cognitive_services_account=getattr(self, "cognitive_services_account", None), - knowledge_store=getattr(self, "knowledge_store", None), - index_projection=getattr(self, "index_projection", None), - e_tag=getattr(self, "e_tag", None), - encryption_key=( - encryption_key._to_generated() if encryption_key else None # pylint:disable=protected-access - ), - ) - - @classmethod - def _from_generated(cls, skillset) -> Optional[Self]: - if not skillset: - return None - custom_skills = [] - for skill in skillset.skills: - skill_cls = type(skill) - if skill_cls in [_EntityRecognitionSkillV3]: - custom_skills.append(EntityRecognitionSkill._from_generated(skill)) # pylint:disable=protected-access - elif skill_cls in [_SentimentSkillV3]: - custom_skills.append(SentimentSkill._from_generated(skill)) # pylint:disable=protected-access - else: - custom_skills.append(skill) - assert len(skillset.skills) == len(custom_skills) - kwargs = skillset.as_dict() - # pylint:disable=protected-access - kwargs["encryption_key"] = SearchResourceEncryptionKey._from_generated(skillset.encryption_key) - kwargs["skills"] = custom_skills - return cls(**kwargs) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndexerSkillset instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerSkillset instance - :rtype: SearchIndexerSkillset - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndexerSkillset.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerSkillset instance - :rtype: SearchIndexerSkillset - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchIndexerSkillset.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class EntityRecognitionSkillVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the Entity Recognition skill version to use.""" - - V1 = "#Microsoft.Skills.Text.EntityRecognitionSkill" - #: Use Entity Recognition skill V3. - V3 = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill" - #: Use latest version of Entity Recognition skill. - LATEST = V3 - - -class EntityRecognitionSkill(SearchIndexerSkill): - """This skill is deprecated. Use the V3.EntityRecognitionSkill instead. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.AZURE_BLOB # type: ignore + + +class AzureBlobKnowledgeSourceParameters(_Model): + """Parameters for Azure Blob Storage knowledge source. + + :ivar connection_string: Key-based connection string or the ResourceId format if using a + managed identity. Required. + :vartype connection_string: str + :ivar container_name: The name of the blob storage container. Required. + :vartype container_name: str + :ivar folder_path: Optional folder path within the container. + :vartype folder_path: str + :ivar is_adls_gen2: Set to true if connecting to an ADLS Gen2 storage account. Default is + false. + :vartype is_adls_gen2: bool + :ivar ingestion_parameters: Consolidates all general ingestion settings. + :vartype ingestion_parameters: + ~azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters + :ivar created_resources: Resources created by the knowledge source. + :vartype created_resources: ~azure.search.documents.indexes.models.CreatedResources + """ + + connection_string: str = rest_field( + name="connectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """Key-based connection string or the ResourceId format if using a managed identity. Required.""" + container_name: str = rest_field(name="containerName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the blob storage container. Required.""" + folder_path: Optional[str] = rest_field( + name="folderPath", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional folder path within the container.""" + is_adls_gen2: Optional[bool] = rest_field( + name="isADLSGen2", visibility=["read", "create", "update", "delete", "query"] + ) + """Set to true if connecting to an ADLS Gen2 storage account. Default is false.""" + ingestion_parameters: Optional["_knowledgebases_models3.KnowledgeSourceIngestionParameters"] = rest_field( + name="ingestionParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Consolidates all general ingestion settings.""" + created_resources: Optional["_models.CreatedResources"] = rest_field(name="createdResources", visibility=["read"]) + """Resources created by the knowledge source.""" + + @overload + def __init__( + self, + *, + connection_string: str, + container_name: str, + folder_path: Optional[str] = None, + is_adls_gen2: Optional[bool] = None, + ingestion_parameters: Optional["_knowledgebases_models3.KnowledgeSourceIngestionParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureMachineLearningParameters(_Model): + """Specifies the properties for connecting to an AML vectorizer. + + :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of + the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. + Required. + :vartype scoring_uri: str + :ivar authentication_key: (Required for key authentication) The key for the AML service. + :vartype authentication_key: str + :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID + of the AML service. It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. + :vartype resource_id: str + :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the + API call. + :vartype timeout: ~datetime.timedelta + :ivar region: (Optional for token authentication). The region the AML service is deployed in. + :vartype region: str + :ivar model_name: The name of the embedding model from the Azure AI Foundry Catalog that is + deployed at the provided endpoint. Known values are: + "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", + "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", + "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", + "Cohere-embed-v3-english", "Cohere-embed-v3-multilingual", and "Cohere-embed-v4". + :vartype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName + """ + + scoring_uri: str = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) + """(Required for no authentication or key authentication) The scoring URI of the AML service to + which the JSON payload will be sent. Only the https URI scheme is allowed. Required.""" + authentication_key: Optional[str] = rest_field( + name="key", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for key authentication) The key for the AML service.""" + resource_id: Optional[str] = rest_field( + name="resourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for token authentication). The Azure Resource Manager resource ID of the AML service. + It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional) When specified, indicates the timeout for the http client making the API call.""" + region: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional for token authentication). The region the AML service is deployed in.""" + model_name: Optional[Union[str, "_models.AIFoundryModelCatalogName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model from the Azure AI Foundry Catalog that is deployed at the + provided endpoint. Known values are: \"OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32\", + \"OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336\", + \"Facebook-DinoV2-Image-Embeddings-ViT-Base\", \"Facebook-DinoV2-Image-Embeddings-ViT-Giant\", + \"Cohere-embed-v3-english\", \"Cohere-embed-v3-multilingual\", and \"Cohere-embed-v4\".""" + + @overload + def __init__( + self, + *, + scoring_uri: str, + authentication_key: Optional[str] = None, + resource_id: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + region: Optional[str] = None, + model_name: Optional[Union[str, "_models.AIFoundryModelCatalogName"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerSkill(_Model): + """Base type for skills. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureMachineLearningSkill, ChatCompletionSkill, WebApiSkill, AzureOpenAIEmbeddingSkill, + CustomEntityLookupSkill, KeyPhraseExtractionSkill, LanguageDetectionSkill, MergeSkill, + PIIDetectionSkill, SplitSkill, TextTranslationSkill, EntityLinkingSkill, + EntityRecognitionSkillV3, SentimentSkillV3, ConditionalSkill, ContentUnderstandingSkill, + DocumentExtractionSkill, DocumentIntelligenceLayoutSkill, ShaperSkill, ImageAnalysisSkill, + OcrSkill, VisionVectorizeSkill + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. :vartype odata_type: str :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill with no name defined will be given a default name of its 1-based index in the skills array, @@ -238,112 +900,10707 @@ class EntityRecognitionSkill(SearchIndexerSkill): :ivar outputs: The output of a skill is either a field in a search index, or a value that can be consumed as an input by another skill. Required. :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar categories: A list of entity categories that should be extracted. - :vartype categories: list[str or ~azure.search.documents.indexes.models.EntityCategory] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", "el", - "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", and "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage - :ivar include_typeless_entities: Determines whether or not to include entities which are well - known but don't conform to a pre-defined type. If this configuration is not set (default), set - to null or set to false, entities which don't conform to one of the pre-defined types will not - be surfaced. - :vartype include_typeless_entities: bool - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar model_version: The version of the model to use when calling the Text Analytics service. + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the skill which uniquely identifies it within the skillset. A skill with no name + defined will be given a default name of its 1-based index in the skills array, prefixed with + the character '#'.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the skill which describes the inputs, outputs, and usage of the skill.""" + context: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Represents the level at which operations take place, such as the document root or document + content (for example, /document or /document/content). The default is /document.""" + inputs: list["_models.InputFieldMappingEntry"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Inputs of the skills could be a column in the source data set, or the output of an upstream + skill. Required.""" + outputs: list["_models.OutputFieldMappingEntry"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The output of a skill is either a field in a search index, or a value that can be consumed as + an input by another skill. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureMachineLearningSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.AmlSkill"): + """The AML skill allows you to extend AI enrichment with a custom Azure Machine Learning (AML) + model. Once an AML model is trained and deployed, an AML skill integrates it into AI + enrichment. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of + the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. + :vartype scoring_uri: str + :ivar authentication_key: (Required for key authentication) The key for the AML service. + :vartype authentication_key: str + :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID + of the AML service. It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. + :vartype resource_id: str + :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the + API call. + :vartype timeout: ~datetime.timedelta + :ivar region: (Optional for token authentication). The region the AML service is deployed in. + :vartype region: str + :ivar degree_of_parallelism: (Optional) When specified, indicates the number of calls the + indexer will make in parallel to the endpoint you have provided. You can decrease this value if + your endpoint is failing under too high of a request load, or raise it if your endpoint is able + to accept more requests and you would like an increase in the performance of the indexer. If + not set, a default value of 5 is used. The degreeOfParallelism can be set to a maximum of 10 + and a minimum of 1. + :vartype degree_of_parallelism: int + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Custom.AmlSkill". + :vartype odata_type: str + """ + + scoring_uri: Optional[str] = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) + """(Required for no authentication or key authentication) The scoring URI of the AML service to + which the JSON payload will be sent. Only the https URI scheme is allowed.""" + authentication_key: Optional[str] = rest_field( + name="key", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for key authentication) The key for the AML service.""" + resource_id: Optional[str] = rest_field( + name="resourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for token authentication). The Azure Resource Manager resource ID of the AML service. + It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional) When specified, indicates the timeout for the http client making the API call.""" + region: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional for token authentication). The region the AML service is deployed in.""" + degree_of_parallelism: Optional[int] = rest_field( + name="degreeOfParallelism", visibility=["read", "create", "update", "delete", "query"] + ) + """(Optional) When specified, indicates the number of calls the indexer will make in parallel to + the endpoint you have provided. You can decrease this value if your endpoint is failing under + too high of a request load, or raise it if your endpoint is able to accept more requests and + you would like an increase in the performance of the indexer. If not set, a default value of 5 + is used. The degreeOfParallelism can be set to a maximum of 10 and a minimum of 1.""" + odata_type: Literal["#Microsoft.Skills.Custom.AmlSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Custom.AmlSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + scoring_uri: Optional[str] = None, + authentication_key: Optional[str] = None, + resource_id: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + region: Optional[str] = None, + degree_of_parallelism: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.AmlSkill" # type: ignore + + +class AzureMachineLearningVectorizer(VectorSearchVectorizer, discriminator="aml"): + """Specifies an Azure Machine Learning endpoint deployed via the Azure AI Foundry Model Catalog + for generating the vector embedding of a query string. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar aml_parameters: Specifies the properties of the AML vectorizer. + :vartype aml_parameters: ~azure.search.documents.indexes.models.AzureMachineLearningParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings using an Azure Machine Learning endpoint deployed via the + Azure AI Foundry Model Catalog at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.AML + """ + + aml_parameters: Optional["_models.AzureMachineLearningParameters"] = rest_field( + name="amlParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the properties of the AML vectorizer.""" + kind: Literal[VectorSearchVectorizerKind.AML] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings using an Azure Machine Learning endpoint deployed via the Azure + AI Foundry Model Catalog at query time.""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + aml_parameters: Optional["_models.AzureMachineLearningParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AML # type: ignore + + +class AzureOpenAIEmbeddingSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"): + """Allows you to generate a vector embedding for a given text input using the Azure OpenAI + resource. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar resource_url: The resource URI of the Azure OpenAI resource. + :vartype resource_url: str + :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. + :vartype deployment_name: str + :ivar api_key: API key of the designated Azure OpenAI resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", + "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", + "gpt-5", "gpt-5-mini", and "gpt-5-nano". + :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + :ivar dimensions: The number of dimensions the resulting output embeddings should have. Only + supported in text-embedding-3 and later models. + :vartype dimensions: int + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill". + :vartype odata_type: str + """ + + resource_url: Optional[str] = rest_field( + name="resourceUri", visibility=["read", "create", "update", "delete", "query"] + ) + """The resource URI of the Azure OpenAI resource.""" + deployment_name: Optional[str] = rest_field( + name="deploymentId", visibility=["read", "create", "update", "delete", "query"] + ) + """ID of the Azure OpenAI model deployment on the designated resource.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated Azure OpenAI resource.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections.""" + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model that is deployed at the provided deploymentId path. Known + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", \"text-embedding-3-small\", + \"gpt-4o\", \"gpt-4o-mini\", \"gpt-4.1\", \"gpt-4.1-mini\", \"gpt-4.1-nano\", \"gpt-5\", + \"gpt-5-mini\", and \"gpt-5-nano\".""" + dimensions: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of dimensions the resulting output embeddings should have. Only supported in + text-embedding-3 and later models.""" + odata_type: Literal["#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + resource_url: Optional[str] = None, + deployment_name: Optional[str] = None, + api_key: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + dimensions: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill" # type: ignore + + +class AzureOpenAITokenizerParameters(_Model): + """Azure OpenAI Tokenizer parameters. + + :ivar encoder_model_name: Only applies if the unit is set to azureOpenAITokens. Options include + 'R50k_base', 'P50k_base', 'P50k_edit' and 'CL100k_base'. The default value is 'CL100k_base'. + Known values are: "r50k_base", "p50k_base", "p50k_edit", and "cl100k_base". + :vartype encoder_model_name: str or + ~azure.search.documents.indexes.models.SplitSkillEncoderModelName + :ivar allowed_special_tokens: (Optional) Only applies if the unit is set to azureOpenAITokens. + This parameter defines a collection of special tokens that are permitted within the + tokenization process. + :vartype allowed_special_tokens: list[str] + """ + + encoder_model_name: Optional[Union[str, "_models.SplitSkillEncoderModelName"]] = rest_field( + name="encoderModelName", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applies if the unit is set to azureOpenAITokens. Options include 'R50k_base', 'P50k_base', + 'P50k_edit' and 'CL100k_base'. The default value is 'CL100k_base'. Known values are: + \"r50k_base\", \"p50k_base\", \"p50k_edit\", and \"cl100k_base\".""" + allowed_special_tokens: Optional[list[str]] = rest_field( + name="allowedSpecialTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """(Optional) Only applies if the unit is set to azureOpenAITokens. This parameter defines a + collection of special tokens that are permitted within the tokenization process.""" + + @overload + def __init__( + self, + *, + encoder_model_name: Optional[Union[str, "_models.SplitSkillEncoderModelName"]] = None, + allowed_special_tokens: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureOpenAIVectorizer(VectorSearchVectorizer, discriminator="azureOpenAI"): + """Specifies the Azure OpenAI resource used to vectorize a query string. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar parameters: Contains the parameters specific to Azure OpenAI embedding vectorization. + :vartype parameters: ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings using an Azure OpenAI resource at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_OPEN_AI + """ + + parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = rest_field( + name="azureOpenAIParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to Azure OpenAI embedding vectorization.""" + kind: Literal[VectorSearchVectorizerKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings using an Azure OpenAI resource at query time.""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AZURE_OPEN_AI # type: ignore + + +class AzureOpenAIVectorizerParameters(_Model): + """Specifies the parameters for connecting to the Azure OpenAI resource. + + :ivar resource_url: The resource URI of the Azure OpenAI resource. + :vartype resource_url: str + :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. + :vartype deployment_name: str + :ivar api_key: API key of the designated Azure OpenAI resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", + "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", + "gpt-5", "gpt-5-mini", and "gpt-5-nano". + :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + """ + + resource_url: Optional[str] = rest_field( + name="resourceUri", visibility=["read", "create", "update", "delete", "query"] + ) + """The resource URI of the Azure OpenAI resource.""" + deployment_name: Optional[str] = rest_field( + name="deploymentId", visibility=["read", "create", "update", "delete", "query"] + ) + """ID of the Azure OpenAI model deployment on the designated resource.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated Azure OpenAI resource.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections.""" + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model that is deployed at the provided deploymentId path. Known + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", \"text-embedding-3-small\", + \"gpt-4o\", \"gpt-4o-mini\", \"gpt-4.1\", \"gpt-4.1-mini\", \"gpt-4.1-nano\", \"gpt-5\", + \"gpt-5-mini\", and \"gpt-5-nano\".""" + + @overload + def __init__( + self, + *, + resource_url: Optional[str] = None, + deployment_name: Optional[str] = None, + api_key: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorSearchCompression(_Model): + """Contains configuration options specific to the compression method used during indexing or + querying. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + BinaryQuantizationCompression, ScalarQuantizationCompression + + :ivar compression_name: The name to associate with this particular configuration. Required. + :vartype compression_name: str + :ivar rescoring_options: Contains the options for rescoring. + :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions + :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the + vectors reduces the size of the vectors and the amount of data that needs to be transferred + during search. This can save storage cost and improve search performance at the expense of + recall. It should be only used for embeddings trained with Matryoshka Representation Learning + (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no + truncation. + :vartype truncation_dimension: int + :ivar kind: Type of VectorSearchCompression. Required. Known values are: "scalarQuantization" + and "binaryQuantization". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind + """ + + __mapping__: dict[str, _Model] = {} + compression_name: str = rest_field(name="name", visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular configuration. Required.""" + rescoring_options: Optional["_models.RescoringOptions"] = rest_field( + name="rescoringOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the options for rescoring.""" + truncation_dimension: Optional[int] = rest_field( + name="truncationDimension", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of dimensions to truncate the vectors to. Truncating the vectors reduces the size of + the vectors and the amount of data that needs to be transferred during search. This can save + storage cost and improve search performance at the expense of recall. It should be only used + for embeddings trained with Matryoshka Representation Learning (MRL) such as OpenAI + text-embedding-3-large (small). The default value is null, which means no truncation.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of VectorSearchCompression. Required. Known values are: \"scalarQuantization\" and + \"binaryQuantization\".""" + + @overload + def __init__( + self, + *, + compression_name: str, + kind: str, + rescoring_options: Optional["_models.RescoringOptions"] = None, + truncation_dimension: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BinaryQuantizationCompression(VectorSearchCompression, discriminator="binaryQuantization"): + """Contains configuration options specific to the binary quantization compression method used + during indexing and querying. + + :ivar compression_name: The name to associate with this particular configuration. Required. + :vartype compression_name: str + :ivar rescoring_options: Contains the options for rescoring. + :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions + :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the + vectors reduces the size of the vectors and the amount of data that needs to be transferred + during search. This can save storage cost and improve search performance at the expense of + recall. It should be only used for embeddings trained with Matryoshka Representation Learning + (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no + truncation. + :vartype truncation_dimension: int + :ivar kind: The name of the kind of compression method being configured for use with vector + search. Required. Binary Quantization, a type of compression method. In binary quantization, + the original vectors values are compressed to the narrower binary type by discretizing and + representing each component of a vector using binary values, thereby reducing the overall data + size. + :vartype kind: str or ~azure.search.documents.indexes.models.BINARY_QUANTIZATION + """ + + kind: Literal[VectorSearchCompressionKind.BINARY_QUANTIZATION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of compression method being configured for use with vector search. + Required. Binary Quantization, a type of compression method. In binary quantization, the + original vectors values are compressed to the narrower binary type by discretizing and + representing each component of a vector using binary values, thereby reducing the overall data + size.""" + + @overload + def __init__( + self, + *, + compression_name: str, + rescoring_options: Optional["_models.RescoringOptions"] = None, + truncation_dimension: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchCompressionKind.BINARY_QUANTIZATION # type: ignore + + +class SimilarityAlgorithm(_Model): + """Base type for similarity algorithms. Similarity algorithms are used to calculate scores that + tie queries to documents. The higher the score, the more relevant the document is to that + specific query. Those scores are used to rank the search results. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + BM25SimilarityAlgorithm, ClassicSimilarityAlgorithm + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BM25SimilarityAlgorithm(SimilarityAlgorithm, discriminator="#Microsoft.Azure.Search.BM25Similarity"): + """Ranking function based on the Okapi BM25 similarity algorithm. BM25 is a TF-IDF-like algorithm + that includes length normalization (controlled by the 'b' parameter) as well as term frequency + saturation (controlled by the 'k1' parameter). + + :ivar k1: This property controls the scaling function between the term frequency of each + matching terms and the final relevance score of a document-query pair. By default, a value of + 1.2 is used. A value of 0.0 means the score does not scale with an increase in term frequency. + :vartype k1: float + :ivar b: This property controls how the length of a document affects the relevance score. By + default, a value of 0.75 is used. A value of 0.0 means no length normalization is applied, + while a value of 1.0 means the score is fully normalized by the length of the document. + :vartype b: float + :ivar odata_type: The discriminator for derived types. Required. Default value is + "#Microsoft.Azure.Search.BM25Similarity". + :vartype odata_type: str + """ + + k1: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This property controls the scaling function between the term frequency of each matching terms + and the final relevance score of a document-query pair. By default, a value of 1.2 is used. A + value of 0.0 means the score does not scale with an increase in term frequency.""" + b: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This property controls how the length of a document affects the relevance score. By default, a + value of 0.75 is used. A value of 0.0 means no length normalization is applied, while a value + of 1.0 means the score is fully normalized by the length of the document.""" + odata_type: Literal["#Microsoft.Azure.Search.BM25Similarity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator for derived types. Required. Default value is + \"#Microsoft.Azure.Search.BM25Similarity\".""" + + @overload + def __init__( + self, + *, + k1: Optional[float] = None, + b: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.BM25Similarity" # type: ignore + + +class CharFilter(_Model): + """Base type for character filters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + MappingCharFilter, PatternReplaceCharFilter + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the char filter. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionCommonModelParameters(_Model): + """Common language model parameters for Chat Completions. If omitted, default values are used. + + :ivar model_name: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not + specified. + :vartype model_name: str + :ivar frequency_penalty: A float in the range [-2,2] that reduces or increases likelihood of + repeated tokens. Default is 0. + :vartype frequency_penalty: float + :ivar presence_penalty: A float in the range [-2,2] that penalizes new tokens based on their + existing presence. Default is 0. + :vartype presence_penalty: float + :ivar max_tokens: Maximum number of tokens to generate. + :vartype max_tokens: int + :ivar temperature: Sampling temperature. Default is 0.7. + :vartype temperature: float + :ivar seed: Random seed for controlling deterministic outputs. If omitted, randomization is + used. + :vartype seed: int + :ivar stop: List of stop sequences that will cut off text generation. Default is none. + :vartype stop: list[str] + """ + + model_name: Optional[str] = rest_field(name="model", visibility=["read", "create", "update", "delete", "query"]) + """The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified.""" + frequency_penalty: Optional[float] = rest_field( + name="frequencyPenalty", visibility=["read", "create", "update", "delete", "query"] + ) + """A float in the range [-2,2] that reduces or increases likelihood of repeated tokens. Default is + 0.""" + presence_penalty: Optional[float] = rest_field( + name="presencePenalty", visibility=["read", "create", "update", "delete", "query"] + ) + """A float in the range [-2,2] that penalizes new tokens based on their existing presence. Default + is 0.""" + max_tokens: Optional[int] = rest_field(name="maxTokens", visibility=["read", "create", "update", "delete", "query"]) + """Maximum number of tokens to generate.""" + temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sampling temperature. Default is 0.7.""" + seed: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Random seed for controlling deterministic outputs. If omitted, randomization is used.""" + stop: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """List of stop sequences that will cut off text generation. Default is none.""" + + @overload + def __init__( + self, + *, + model_name: Optional[str] = None, + frequency_penalty: Optional[float] = None, + presence_penalty: Optional[float] = None, + max_tokens: Optional[int] = None, + temperature: Optional[float] = None, + seed: Optional[int] = None, + stop: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionResponseFormat(_Model): + """Determines how the language model's response should be serialized. Defaults to 'text'. + + :ivar type: Specifies how the LLM should format the response. Known values are: "text", + "jsonObject", and "jsonSchema". + :vartype type: str or ~azure.search.documents.indexes.models.ChatCompletionResponseFormatType + :ivar json_schema_properties: An open dictionary for extended properties. Required if 'type' == + 'json_schema'. + :vartype json_schema_properties: + ~azure.search.documents.indexes.models.ChatCompletionSchemaProperties + """ + + type: Optional[Union[str, "_models.ChatCompletionResponseFormatType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies how the LLM should format the response. Known values are: \"text\", \"jsonObject\", + and \"jsonSchema\".""" + json_schema_properties: Optional["_models.ChatCompletionSchemaProperties"] = rest_field( + name="jsonSchemaProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """An open dictionary for extended properties. Required if 'type' == 'json_schema'.""" + + @overload + def __init__( + self, + *, + type: Optional[Union[str, "_models.ChatCompletionResponseFormatType"]] = None, + json_schema_properties: Optional["_models.ChatCompletionSchemaProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionSchema(_Model): + """Object defining the custom schema the model will use to structure its output. + + :ivar type: Type of schema representation. Usually 'object'. Default is 'object'. + :vartype type: str + :ivar properties: A JSON-formatted string that defines the output schema's properties and + constraints for the model. + :vartype properties: str + :ivar required: An array of the property names that are required to be part of the model's + response. All properties must be included for structured outputs. + :vartype required: list[str] + :ivar additional_properties: Controls whether it is allowable for an object to contain + additional keys / values that were not defined in the JSON Schema. Default is false. + :vartype additional_properties: bool + """ + + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type of schema representation. Usually 'object'. Default is 'object'.""" + properties: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A JSON-formatted string that defines the output schema's properties and constraints for the + model.""" + required: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An array of the property names that are required to be part of the model's response. All + properties must be included for structured outputs.""" + additional_properties: Optional[bool] = rest_field( + name="additionalProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls whether it is allowable for an object to contain additional keys / values that were + not defined in the JSON Schema. Default is false.""" + + @overload + def __init__( + self, + *, + type: Optional[str] = None, + properties: Optional[str] = None, + required: Optional[list[str]] = None, + additional_properties: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionSchemaProperties(_Model): + """Properties for JSON schema response format. + + :ivar name: Name of the json schema the model will adhere to. + :vartype name: str + :ivar description: Description of the json schema the model will adhere to. + :vartype description: str + :ivar strict: Whether or not the model's response should use structured outputs. Default is + true. + :vartype strict: bool + :ivar schema: The schema definition. + :vartype schema: ~azure.search.documents.indexes.models.ChatCompletionSchema + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the json schema the model will adhere to.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description of the json schema the model will adhere to.""" + strict: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether or not the model's response should use structured outputs. Default is true.""" + schema: Optional["_models.ChatCompletionSchema"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The schema definition.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + strict: Optional[bool] = None, + schema: Optional["_models.ChatCompletionSchema"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.ChatCompletionSkill"): + """A skill that calls a language model via Azure AI Foundry's Chat Completions endpoint. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar uri: The url for the Web API. Required. + :vartype uri: str + :ivar http_headers: The headers required to make the http request. + :vartype http_headers: ~azure.search.documents.indexes.models.WebApiHttpHeaders + :ivar http_method: The method for the http request. + :vartype http_method: str + :ivar timeout: The desired timeout for the request. Default is 30 seconds. + :vartype timeout: ~datetime.timedelta + :ivar batch_size: The desired batch size which indicates number of documents. + :vartype batch_size: int + :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web + API. + :vartype degree_of_parallelism: int + :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure + function or some other application that provides the transformations. This value should be the + application ID created for the function or app when it was registered with Azure Active + Directory. When specified, the custom skill connects to the function or app using a managed ID + (either system or user-assigned) of the search service and the access token of the function or + app, using this value as the resource id for creating the scope of the access token. + :vartype auth_resource_id: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. + If set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot be + specified at the same time. + :vartype api_key: str + :ivar common_model_parameters: Common language model parameters that customers can tweak. If + omitted, reasonable defaults will be applied. + :vartype common_model_parameters: + ~azure.search.documents.indexes.models.ChatCompletionCommonModelParameters + :ivar extra_parameters: Open-type dictionary for model-specific parameters that should be + appended to the chat completions call. Follows Azure AI Foundry's extensibility pattern. + :vartype extra_parameters: dict[str, any] + :ivar extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. Default + is 'error'. Known values are: "pass-through", "drop", and "error". + :vartype extra_parameters_behavior: str or + ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior + :ivar response_format: Determines how the LLM should format its response. Defaults to 'text' + response type. + :vartype response_format: ~azure.search.documents.indexes.models.ChatCompletionResponseFormat + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Custom.ChatCompletionSkill". + :vartype odata_type: str + """ + + uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url for the Web API. Required.""" + http_headers: Optional["_models.WebApiHttpHeaders"] = rest_field( + name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """The headers required to make the http request.""" + http_method: Optional[str] = rest_field( + name="httpMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The method for the http request.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The desired timeout for the request. Default is 30 seconds.""" + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) + """The desired batch size which indicates number of documents.""" + degree_of_parallelism: Optional[int] = rest_field( + name="degreeOfParallelism", visibility=["read", "create", "update", "delete", "query"] + ) + """If set, the number of parallel calls that can be made to the Web API.""" + auth_resource_id: Optional[str] = rest_field( + name="authResourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """Applies to custom skills that connect to external code in an Azure function or some other + application that provides the transformations. This value should be the application ID created + for the function or app when it was registered with Azure Active Directory. When specified, the + custom skill connects to the function or app using a managed ID (either system or + user-assigned) of the search service and the access token of the function or app, using this + value as the resource id for creating the scope of the access token.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", + the value of this property is cleared.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key for authenticating to the model. Both apiKey and authIdentity cannot be specified at + the same time.""" + common_model_parameters: Optional["_models.ChatCompletionCommonModelParameters"] = rest_field( + name="commonModelParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Common language model parameters that customers can tweak. If omitted, reasonable defaults will + be applied.""" + extra_parameters: Optional[dict[str, Any]] = rest_field( + name="extraParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Open-type dictionary for model-specific parameters that should be appended to the chat + completions call. Follows Azure AI Foundry's extensibility pattern.""" + extra_parameters_behavior: Optional[Union[str, "_models.ChatCompletionExtraParametersBehavior"]] = rest_field( + name="extraParametersBehavior", visibility=["read", "create", "update", "delete", "query"] + ) + """How extra parameters are handled by Azure AI Foundry. Default is 'error'. Known values are: + \"pass-through\", \"drop\", and \"error\".""" + response_format: Optional["_models.ChatCompletionResponseFormat"] = rest_field( + name="responseFormat", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines how the LLM should format its response. Defaults to 'text' response type.""" + odata_type: Literal["#Microsoft.Skills.Custom.ChatCompletionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Custom.ChatCompletionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + uri: str, + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + http_headers: Optional["_models.WebApiHttpHeaders"] = None, + http_method: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + batch_size: Optional[int] = None, + degree_of_parallelism: Optional[int] = None, + auth_resource_id: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + api_key: Optional[str] = None, + common_model_parameters: Optional["_models.ChatCompletionCommonModelParameters"] = None, + extra_parameters: Optional[dict[str, Any]] = None, + extra_parameters_behavior: Optional[Union[str, "_models.ChatCompletionExtraParametersBehavior"]] = None, + response_format: Optional["_models.ChatCompletionResponseFormat"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.ChatCompletionSkill" # type: ignore + + +class CjkBigramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.CjkBigramTokenFilter"): + """Forms bigrams of CJK terms that are generated from the standard tokenizer. This token filter is + implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar ignore_scripts: The scripts to ignore. + :vartype ignore_scripts: list[str or + ~azure.search.documents.indexes.models.CjkBigramTokenFilterScripts] + :ivar output_unigrams: A value indicating whether to output both unigrams and bigrams (if + true), or just bigrams (if false). Default is false. + :vartype output_unigrams: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.CjkBigramTokenFilter". + :vartype odata_type: str + """ + + ignore_scripts: Optional[list[Union[str, "_models.CjkBigramTokenFilterScripts"]]] = rest_field( + name="ignoreScripts", visibility=["read", "create", "update", "delete", "query"] + ) + """The scripts to ignore.""" + output_unigrams: Optional[bool] = rest_field( + name="outputUnigrams", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to output both unigrams and bigrams (if true), or just bigrams (if + false). Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.CjkBigramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.CjkBigramTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + ignore_scripts: Optional[list[Union[str, "_models.CjkBigramTokenFilterScripts"]]] = None, + output_unigrams: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CjkBigramTokenFilter" # type: ignore + + +class ClassicSimilarityAlgorithm(SimilarityAlgorithm, discriminator="#Microsoft.Azure.Search.ClassicSimilarity"): + """Legacy similarity algorithm which uses the Lucene TFIDFSimilarity implementation of TF-IDF. + This variation of TF-IDF introduces static document length normalization as well as + coordinating factors that penalize documents that only partially match the searched queries. + + :ivar odata_type: The discriminator for derived types. Required. Default value is + "#Microsoft.Azure.Search.ClassicSimilarity". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.ClassicSimilarity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator for derived types. Required. Default value is + \"#Microsoft.Azure.Search.ClassicSimilarity\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ClassicSimilarity" # type: ignore + + +class LexicalTokenizer(_Model): + """Base type for tokenizers. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ClassicTokenizer, EdgeNGramTokenizer, KeywordTokenizer, KeywordTokenizerV2, + MicrosoftLanguageStemmingTokenizer, MicrosoftLanguageTokenizer, NGramTokenizer, + PathHierarchyTokenizerV2, PatternTokenizer, LuceneStandardTokenizer, LuceneStandardTokenizerV2, + UaxUrlEmailTokenizer + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the tokenizer. It must only contain letters, digits, spaces, dashes or underscores, + can only start and end with alphanumeric characters, and is limited to 128 characters. + Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ClassicTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.ClassicTokenizer"): + """Grammar-based tokenizer that is suitable for processing most European-language documents. This + tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.ClassicTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.ClassicTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.ClassicTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ClassicTokenizer" # type: ignore + + +class CognitiveServicesAccountKey( + CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.CognitiveServicesByKey" +): + """The multi-region account key of an Azure AI service resource that's attached to a skillset. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar key: The key used to provision the Azure AI service resource attached to a skillset. + Required. + :vartype key: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.CognitiveServicesByKey". + :vartype odata_type: str + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key used to provision the Azure AI service resource attached to a skillset. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.CognitiveServicesByKey"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.CognitiveServicesByKey\".""" + + @overload + def __init__( + self, + *, + key: str, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CognitiveServicesByKey" # type: ignore + + +class CommonGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.CommonGramTokenFilter"): + """Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed + too, with bigrams overlaid. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar common_words: The set of common words. Required. + :vartype common_words: list[str] + :ivar ignore_case: A value indicating whether common words matching will be case insensitive. + Default is false. + :vartype ignore_case: bool + :ivar use_query_mode: A value that indicates whether the token filter is in query mode. When in + query mode, the token filter generates bigrams and then removes common words and single terms + followed by a common word. Default is false. + :vartype use_query_mode: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.CommonGramTokenFilter". + :vartype odata_type: str + """ + + common_words: list[str] = rest_field(name="commonWords", visibility=["read", "create", "update", "delete", "query"]) + """The set of common words. Required.""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether common words matching will be case insensitive. Default is false.""" + use_query_mode: Optional[bool] = rest_field( + name="queryMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that indicates whether the token filter is in query mode. When in query mode, the token + filter generates bigrams and then removes common words and single terms followed by a common + word. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.CommonGramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.CommonGramTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + common_words: list[str], + ignore_case: Optional[bool] = None, + use_query_mode: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CommonGramTokenFilter" # type: ignore + + +class ConditionalSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.ConditionalSkill"): + """A skill that enables scenarios that require a Boolean operation to determine the data to assign + to an output. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.ConditionalSkill". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Skills.Util.ConditionalSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.ConditionalSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.ConditionalSkill" # type: ignore + + +class ContentUnderstandingSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.ContentUnderstandingSkill"): + """A skill that leverages Azure AI Content Understanding to process and extract structured + insights from documents, enabling enriched, searchable content for enhanced document indexing + and retrieval. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar extraction_options: Controls the cardinality of the content extracted from the document + by the skill. + :vartype extraction_options: list[str or + ~azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions] + :ivar chunking_properties: Controls the cardinality for chunking the content. + :vartype chunking_properties: + ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.ContentUnderstandingSkill". + :vartype odata_type: str + """ + + extraction_options: Optional[list[Union[str, "_models.ContentUnderstandingSkillExtractionOptions"]]] = rest_field( + name="extractionOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality of the content extracted from the document by the skill.""" + chunking_properties: Optional["_models.ContentUnderstandingSkillChunkingProperties"] = rest_field( + name="chunkingProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality for chunking the content.""" + odata_type: Literal["#Microsoft.Skills.Util.ContentUnderstandingSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.ContentUnderstandingSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + extraction_options: Optional[list[Union[str, "_models.ContentUnderstandingSkillExtractionOptions"]]] = None, + chunking_properties: Optional["_models.ContentUnderstandingSkillChunkingProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.ContentUnderstandingSkill" # type: ignore + + +class ContentUnderstandingSkillChunkingProperties(_Model): # pylint: disable=name-too-long + """Controls the cardinality for chunking the content. + + :ivar unit: The unit of the chunk. "characters" + :vartype unit: str or + ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit + :ivar maximum_length: The maximum chunk length in characters. Default is 500. + :vartype maximum_length: int + :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. + :vartype overlap_length: int + """ + + unit: Optional[Union[str, "_models.ContentUnderstandingSkillChunkingUnit"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The unit of the chunk. \"characters\"""" + maximum_length: Optional[int] = rest_field( + name="maximumLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum chunk length in characters. Default is 500.""" + overlap_length: Optional[int] = rest_field( + name="overlapLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The length of overlap provided between two text chunks. Default is 0.""" + + @overload + def __init__( + self, + *, + unit: Optional[Union[str, "_models.ContentUnderstandingSkillChunkingUnit"]] = None, + maximum_length: Optional[int] = None, + overlap_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CorsOptions(_Model): + """Defines options to control Cross-Origin Resource Sharing (CORS) for an index. + + :ivar allowed_origins: The list of origins from which JavaScript code will be granted access to + your index. Can contain a list of hosts of the form + {protocol}://{fully-qualified-domain-name}[:{port#}], or a single '*' to allow all origins (not + recommended). Required. + :vartype allowed_origins: list[str] + :ivar max_age_in_seconds: The duration for which browsers should cache CORS preflight + responses. Defaults to 5 minutes. + :vartype max_age_in_seconds: int + """ + + allowed_origins: list[str] = rest_field( + name="allowedOrigins", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of origins from which JavaScript code will be granted access to your index. Can + contain a list of hosts of the form {protocol}://{fully-qualified-domain-name}[:{port#}], or a + single '*' to allow all origins (not recommended). Required.""" + max_age_in_seconds: Optional[int] = rest_field( + name="maxAgeInSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The duration for which browsers should cache CORS preflight responses. Defaults to 5 minutes.""" + + @overload + def __init__( + self, + *, + allowed_origins: list[str], + max_age_in_seconds: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreatedResources(_Model): + """Resources created by the knowledge source. Keys represent resource types (e.g., 'datasource', + 'indexer', 'skillset', 'index') and values represent resource names. + + """ + + +class LexicalAnalyzer(_Model): + """Base type for analyzers. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + CustomAnalyzer, PatternAnalyzer, LuceneStandardAnalyzer, StopAnalyzer + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the analyzer. It must only contain letters, digits, spaces, dashes or underscores, + can only start and end with alphanumeric characters, and is limited to 128 characters. + Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.CustomAnalyzer"): + """Allows you to take control over the process of converting text into indexable/searchable + tokens. It's a user-defined configuration consisting of a single predefined tokenizer and one + or more filters. The tokenizer is responsible for breaking text into tokens, and the filters + for modifying tokens emitted by the tokenizer. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar tokenizer: The name of the tokenizer to use to divide continuous text into a sequence of + tokens, such as breaking a sentence into words. Required. Known values are: "classic", + "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", + "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", + "standard_v2", "uax_url_email", and "whitespace". + :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName + :ivar token_filters: A list of token filters used to filter out or modify the tokens generated + by a tokenizer. For example, you can specify a lowercase filter that converts all characters to + lowercase. The filters are run in the order in which they are listed. + :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] + :ivar char_filters: A list of character filters used to prepare input text before it is + processed by the tokenizer. For instance, they can replace certain characters or symbols. The + filters are run in the order in which they are listed. + :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.CustomAnalyzer". + :vartype odata_type: str + """ + + tokenizer: Union[str, "_models.LexicalTokenizerName"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the tokenizer to use to divide continuous text into a sequence of tokens, such as + breaking a sentence into words. Required. Known values are: \"classic\", \"edgeNGram\", + \"keyword_v2\", \"letter\", \"lowercase\", \"microsoft_language_tokenizer\", + \"microsoft_language_stemming_tokenizer\", \"nGram\", \"path_hierarchy_v2\", \"pattern\", + \"standard_v2\", \"uax_url_email\", and \"whitespace\".""" + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of token filters used to filter out or modify the tokens generated by a tokenizer. For + example, you can specify a lowercase filter that converts all characters to lowercase. The + filters are run in the order in which they are listed.""" + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of character filters used to prepare input text before it is processed by the tokenizer. + For instance, they can replace certain characters or symbols. The filters are run in the order + in which they are listed.""" + odata_type: Literal["#Microsoft.Azure.Search.CustomAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.CustomAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + tokenizer: Union[str, "_models.LexicalTokenizerName"], + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CustomAnalyzer" # type: ignore + + +class CustomEntity(_Model): + """An object that contains information about the matches that were found, and related metadata. + + :ivar name: The top-level entity descriptor. Matches in the skill output will be grouped by + this name, and it should represent the "normalized" form of the text being found. Required. + :vartype name: str + :ivar description: This field can be used as a passthrough for custom metadata about the + matched text(s). The value of this field will appear with every match of its entity in the + skill output. + :vartype description: str + :ivar type: This field can be used as a passthrough for custom metadata about the matched + text(s). The value of this field will appear with every match of its entity in the skill + output. + :vartype type: str + :ivar subtype: This field can be used as a passthrough for custom metadata about the matched + text(s). The value of this field will appear with every match of its entity in the skill + output. + :vartype subtype: str + :ivar id: This field can be used as a passthrough for custom metadata about the matched + text(s). The value of this field will appear with every match of its entity in the skill + output. + :vartype id: str + :ivar case_sensitive: Defaults to false. Boolean value denoting whether comparisons with the + entity name should be sensitive to character casing. Sample case insensitive matches of + "Microsoft" could be: microsoft, microSoft, MICROSOFT. + :vartype case_sensitive: bool + :ivar accent_sensitive: Defaults to false. Boolean value denoting whether comparisons with the + entity name should be sensitive to accent. + :vartype accent_sensitive: bool + :ivar fuzzy_edit_distance: Defaults to 0. Maximum value of 5. Denotes the acceptable number of + divergent characters that would still constitute a match with the entity name. The smallest + possible fuzziness for any given match is returned. For instance, if the edit distance is set + to 3, "Windows10" would still match "Windows", "Windows10" and "Windows 7". When case + sensitivity is set to false, case differences do NOT count towards fuzziness tolerance, but + otherwise do. + :vartype fuzzy_edit_distance: int + :ivar default_case_sensitive: Changes the default case sensitivity value for this entity. It be + used to change the default value of all aliases caseSensitive values. + :vartype default_case_sensitive: bool + :ivar default_accent_sensitive: Changes the default accent sensitivity value for this entity. + It be used to change the default value of all aliases accentSensitive values. + :vartype default_accent_sensitive: bool + :ivar default_fuzzy_edit_distance: Changes the default fuzzy edit distance value for this + entity. It can be used to change the default value of all aliases fuzzyEditDistance values. + :vartype default_fuzzy_edit_distance: int + :ivar aliases: An array of complex objects that can be used to specify alternative spellings or + synonyms to the root entity name. + :vartype aliases: list[~azure.search.documents.indexes.models.CustomEntityAlias] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The top-level entity descriptor. Matches in the skill output will be grouped by this name, and + it should represent the \"normalized\" form of the text being found. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + subtype: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + case_sensitive: Optional[bool] = rest_field( + name="caseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Defaults to false. Boolean value denoting whether comparisons with the entity name should be + sensitive to character casing. Sample case insensitive matches of \"Microsoft\" could be: + microsoft, microSoft, MICROSOFT.""" + accent_sensitive: Optional[bool] = rest_field( + name="accentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Defaults to false. Boolean value denoting whether comparisons with the entity name should be + sensitive to accent.""" + fuzzy_edit_distance: Optional[int] = rest_field( + name="fuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """Defaults to 0. Maximum value of 5. Denotes the acceptable number of divergent characters that + would still constitute a match with the entity name. The smallest possible fuzziness for any + given match is returned. For instance, if the edit distance is set to 3, \"Windows10\" would + still match \"Windows\", \"Windows10\" and \"Windows 7\". When case sensitivity is set to + false, case differences do NOT count towards fuzziness tolerance, but otherwise do.""" + default_case_sensitive: Optional[bool] = rest_field( + name="defaultCaseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Changes the default case sensitivity value for this entity. It be used to change the default + value of all aliases caseSensitive values.""" + default_accent_sensitive: Optional[bool] = rest_field( + name="defaultAccentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Changes the default accent sensitivity value for this entity. It be used to change the default + value of all aliases accentSensitive values.""" + default_fuzzy_edit_distance: Optional[int] = rest_field( + name="defaultFuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """Changes the default fuzzy edit distance value for this entity. It can be used to change the + default value of all aliases fuzzyEditDistance values.""" + aliases: Optional[list["_models.CustomEntityAlias"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An array of complex objects that can be used to specify alternative spellings or synonyms to + the root entity name.""" + + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + type: Optional[str] = None, + subtype: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + case_sensitive: Optional[bool] = None, + accent_sensitive: Optional[bool] = None, + fuzzy_edit_distance: Optional[int] = None, + default_case_sensitive: Optional[bool] = None, + default_accent_sensitive: Optional[bool] = None, + default_fuzzy_edit_distance: Optional[int] = None, + aliases: Optional[list["_models.CustomEntityAlias"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomEntityAlias(_Model): + """A complex object that can be used to specify alternative spellings or synonyms to the root + entity name. + + :ivar text: The text of the alias. Required. + :vartype text: str + :ivar case_sensitive: Determine if the alias is case sensitive. + :vartype case_sensitive: bool + :ivar accent_sensitive: Determine if the alias is accent sensitive. + :vartype accent_sensitive: bool + :ivar fuzzy_edit_distance: Determine the fuzzy edit distance of the alias. + :vartype fuzzy_edit_distance: int + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text of the alias. Required.""" + case_sensitive: Optional[bool] = rest_field( + name="caseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Determine if the alias is case sensitive.""" + accent_sensitive: Optional[bool] = rest_field( + name="accentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Determine if the alias is accent sensitive.""" + fuzzy_edit_distance: Optional[int] = rest_field( + name="fuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """Determine the fuzzy edit distance of the alias.""" + + @overload + def __init__( + self, + *, + text: str, + case_sensitive: Optional[bool] = None, + accent_sensitive: Optional[bool] = None, + fuzzy_edit_distance: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomEntityLookupSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.CustomEntityLookupSkill"): + """A skill looks for text from a custom, user-defined list of words and phrases. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "da", "de", "en", "es", "fi", "fr", "it", "ko", and "pt". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage + :ivar entities_definition_uri: Path to a JSON or CSV file containing all the target text to + match against. This entity definition is read at the beginning of an indexer run. Any updates + to this file during an indexer run will not take effect until subsequent runs. This config must + be accessible over HTTPS. + :vartype entities_definition_uri: str + :ivar inline_entities_definition: The inline CustomEntity definition. + :vartype inline_entities_definition: list[~azure.search.documents.indexes.models.CustomEntity] + :ivar global_default_case_sensitive: A global flag for CaseSensitive. If CaseSensitive is not + set in CustomEntity, this value will be the default value. + :vartype global_default_case_sensitive: bool + :ivar global_default_accent_sensitive: A global flag for AccentSensitive. If AccentSensitive is + not set in CustomEntity, this value will be the default value. + :vartype global_default_accent_sensitive: bool + :ivar global_default_fuzzy_edit_distance: A global flag for FuzzyEditDistance. If + FuzzyEditDistance is not set in CustomEntity, this value will be the default value. + :vartype global_default_fuzzy_edit_distance: int + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.CustomEntityLookupSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.CustomEntityLookupSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"da\", + \"de\", \"en\", \"es\", \"fi\", \"fr\", \"it\", \"ko\", and \"pt\".""" + entities_definition_uri: Optional[str] = rest_field( + name="entitiesDefinitionUri", visibility=["read", "create", "update", "delete", "query"] + ) + """Path to a JSON or CSV file containing all the target text to match against. This entity + definition is read at the beginning of an indexer run. Any updates to this file during an + indexer run will not take effect until subsequent runs. This config must be accessible over + HTTPS.""" + inline_entities_definition: Optional[list["_models.CustomEntity"]] = rest_field( + name="inlineEntitiesDefinition", visibility=["read", "create", "update", "delete", "query"] + ) + """The inline CustomEntity definition.""" + global_default_case_sensitive: Optional[bool] = rest_field( + name="globalDefaultCaseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """A global flag for CaseSensitive. If CaseSensitive is not set in CustomEntity, this value will + be the default value.""" + global_default_accent_sensitive: Optional[bool] = rest_field( + name="globalDefaultAccentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """A global flag for AccentSensitive. If AccentSensitive is not set in CustomEntity, this value + will be the default value.""" + global_default_fuzzy_edit_distance: Optional[int] = rest_field( + name="globalDefaultFuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """A global flag for FuzzyEditDistance. If FuzzyEditDistance is not set in CustomEntity, this + value will be the default value.""" + odata_type: Literal["#Microsoft.Skills.Text.CustomEntityLookupSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.CustomEntityLookupSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.CustomEntityLookupSkillLanguage"]] = None, + entities_definition_uri: Optional[str] = None, + inline_entities_definition: Optional[list["_models.CustomEntity"]] = None, + global_default_case_sensitive: Optional[bool] = None, + global_default_accent_sensitive: Optional[bool] = None, + global_default_fuzzy_edit_distance: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.CustomEntityLookupSkill" # type: ignore + + +class LexicalNormalizer(_Model): + """Base type for normalizers. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + CustomNormalizer + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the char filter. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomNormalizer(LexicalNormalizer, discriminator="#Microsoft.Azure.Search.CustomNormalizer"): + """Allows you to configure normalization for filterable, sortable, and facetable fields, which by + default operate with strict matching. This is a user-defined configuration consisting of at + least one or more filters, which modify the token that is stored. + + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar token_filters: A list of token filters used to filter out or modify the input token. For + example, you can specify a lowercase filter that converts all characters to lowercase. The + filters are run in the order in which they are listed. + :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] + :ivar char_filters: A list of character filters used to prepare input text before it is + processed. For instance, they can replace certain characters or symbols. The filters are run in + the order in which they are listed. + :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + :ivar odata_type: A URI fragment specifying the type of normalizer. Required. Default value is + "#Microsoft.Azure.Search.CustomNormalizer". + :vartype odata_type: str + """ + + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of token filters used to filter out or modify the input token. For example, you can + specify a lowercase filter that converts all characters to lowercase. The filters are run in + the order in which they are listed.""" + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of character filters used to prepare input text before it is processed. For instance, + they can replace certain characters or symbols. The filters are run in the order in which they + are listed.""" + odata_type: Literal["#Microsoft.Azure.Search.CustomNormalizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of normalizer. Required. Default value is + \"#Microsoft.Azure.Search.CustomNormalizer\".""" + + @overload + def __init__( + self, + *, + name: str, + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CustomNormalizer" # type: ignore + + +class DataChangeDetectionPolicy(_Model): + """Base type for data change detection policies. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + HighWaterMarkChangeDetectionPolicy, SqlIntegratedChangeTrackingPolicy + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataDeletionDetectionPolicy(_Model): + """Base type for data deletion detection policies. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + NativeBlobSoftDeleteDeletionDetectionPolicy, SoftDeleteColumnDeletionDetectionPolicy + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataSourceCredentials(_Model): + """Represents credentials that can be used to connect to a datasource. + + :ivar connection_string: The connection string for the datasource. Set to ```` (with + brackets) if you don't want the connection string updated. Set to ```` if you want to + remove the connection string value from the datasource. + :vartype connection_string: str + """ + + connection_string: Optional[str] = rest_field( + name="connectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """The connection string for the datasource. Set to ```` (with brackets) if you don't + want the connection string updated. Set to ```` if you want to remove the connection + string value from the datasource.""" + + @overload + def __init__( + self, + *, + connection_string: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DefaultCognitiveServicesAccount( + CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.DefaultCognitiveServices" +): + """An empty object that represents the default Azure AI service resource for a skillset. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.DefaultCognitiveServices". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.DefaultCognitiveServices"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.DefaultCognitiveServices\".""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DefaultCognitiveServices" # type: ignore + + +class DictionaryDecompounderTokenFilter( + TokenFilter, discriminator="#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter" +): + """Decomposes compound words found in many Germanic languages. This token filter is implemented + using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar word_list: The list of words to match against. Required. + :vartype word_list: list[str] + :ivar min_word_size: The minimum word size. Only words longer than this get processed. Default + is 5. Maximum is 300. + :vartype min_word_size: int + :ivar min_subword_size: The minimum subword size. Only subwords longer than this are outputted. + Default is 2. Maximum is 300. + :vartype min_subword_size: int + :ivar max_subword_size: The maximum subword size. Only subwords shorter than this are + outputted. Default is 15. Maximum is 300. + :vartype max_subword_size: int + :ivar only_longest_match: A value indicating whether to add only the longest matching subword + to the output. Default is false. + :vartype only_longest_match: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter". + :vartype odata_type: str + """ + + word_list: list[str] = rest_field(name="wordList", visibility=["read", "create", "update", "delete", "query"]) + """The list of words to match against. Required.""" + min_word_size: Optional[int] = rest_field( + name="minWordSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The minimum word size. Only words longer than this get processed. Default is 5. Maximum is 300.""" + min_subword_size: Optional[int] = rest_field( + name="minSubwordSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The minimum subword size. Only subwords longer than this are outputted. Default is 2. Maximum + is 300.""" + max_subword_size: Optional[int] = rest_field( + name="maxSubwordSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum subword size. Only subwords shorter than this are outputted. Default is 15. Maximum + is 300.""" + only_longest_match: Optional[bool] = rest_field( + name="onlyLongestMatch", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to add only the longest matching subword to the output. Default is + false.""" + odata_type: Literal["#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + word_list: list[str], + min_word_size: Optional[int] = None, + min_subword_size: Optional[int] = None, + max_subword_size: Optional[int] = None, + only_longest_match: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter" # type: ignore + + +class ScoringFunction(_Model): + """Base type for functions that can modify document scores during ranking. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + DistanceScoringFunction, FreshnessScoringFunction, MagnitudeScoringFunction, TagScoringFunction + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar type: Type of ScoringFunction. Required. Default value is None. + :vartype type: str + """ + + __mapping__: dict[str, _Model] = {} + field_name: str = rest_field(name="fieldName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the field used as input to the scoring function. Required.""" + boost: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A multiplier for the raw score. Must be a positive number not equal to 1.0. Required.""" + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how boosting will be interpolated across document scores; defaults to + \"Linear\". Known values are: \"linear\", \"constant\", \"quadratic\", and \"logarithmic\".""" + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """Type of ScoringFunction. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + type: str, + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DistanceScoringFunction(ScoringFunction, discriminator="distance"): + """Defines a function that boosts scores based on distance from a geographic location. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the distance scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.DistanceScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is "distance". + :vartype type: str + """ + + parameters: "_models.DistanceScoringParameters" = rest_field( + name="distance", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the distance scoring function. Required.""" + type: Literal["distance"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"distance\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.DistanceScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "distance" # type: ignore + + +class DistanceScoringParameters(_Model): + """Provides parameter values to a distance scoring function. + + :ivar reference_point_parameter: The name of the parameter passed in search queries to specify + the reference location. Required. + :vartype reference_point_parameter: str + :ivar boosting_distance: The distance in kilometers from the reference location where the + boosting range ends. Required. + :vartype boosting_distance: float + """ + + reference_point_parameter: str = rest_field( + name="referencePointParameter", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the parameter passed in search queries to specify the reference location. Required.""" + boosting_distance: float = rest_field( + name="boostingDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """The distance in kilometers from the reference location where the boosting range ends. Required.""" + + @overload + def __init__( + self, + *, + reference_point_parameter: str, + boosting_distance: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DocumentExtractionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.DocumentExtractionSkill"): + """A skill that extracts content from a file within the enrichment pipeline. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar parsing_mode: The parsingMode for the skill. Will be set to 'default' if not defined. + :vartype parsing_mode: str + :ivar data_to_extract: The type of data to be extracted for the skill. Will be set to + 'contentAndMetadata' if not defined. + :vartype data_to_extract: str + :ivar configuration: A dictionary of configurations for the skill. + :vartype configuration: dict[str, any] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.DocumentExtractionSkill". + :vartype odata_type: str + """ + + parsing_mode: Optional[str] = rest_field( + name="parsingMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The parsingMode for the skill. Will be set to 'default' if not defined.""" + data_to_extract: Optional[str] = rest_field( + name="dataToExtract", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of data to be extracted for the skill. Will be set to 'contentAndMetadata' if not + defined.""" + configuration: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A dictionary of configurations for the skill.""" + odata_type: Literal["#Microsoft.Skills.Util.DocumentExtractionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.DocumentExtractionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + parsing_mode: Optional[str] = None, + data_to_extract: Optional[str] = None, + configuration: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.DocumentExtractionSkill" # type: ignore + + +class DocumentIntelligenceLayoutSkill( + SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill" +): + """A skill that extracts content and layout information, via Azure AI Services, from files within + the enrichment pipeline. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar output_format: Controls the output format. Default is 'markdown'. Known values are: + "text" and "markdown". + :vartype output_format: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat + :ivar output_mode: Controls the cardinality of the output produced by the skill. Default is + 'oneToMany'. "oneToMany" + :vartype output_mode: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode + :ivar markdown_header_depth: The depth of headers in the markdown output. Default is h6. Known + values are: "h1", "h2", "h3", "h4", "h5", and "h6". + :vartype markdown_header_depth: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth + :ivar extraction_options: Controls the cardinality of the content extracted from the document + by the skill. + :vartype extraction_options: list[str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions] + :ivar chunking_properties: Controls the cardinality for chunking the content. + :vartype chunking_properties: + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill". + :vartype odata_type: str + """ + + output_format: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"]] = rest_field( + name="outputFormat", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the output format. Default is 'markdown'. Known values are: \"text\" and \"markdown\".""" + output_mode: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"]] = rest_field( + name="outputMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality of the output produced by the skill. Default is 'oneToMany'. + \"oneToMany\"""" + markdown_header_depth: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth"]] = ( + rest_field(name="markdownHeaderDepth", visibility=["read", "create", "update", "delete", "query"]) + ) + """The depth of headers in the markdown output. Default is h6. Known values are: \"h1\", \"h2\", + \"h3\", \"h4\", \"h5\", and \"h6\".""" + extraction_options: Optional[list[Union[str, "_models.DocumentIntelligenceLayoutSkillExtractionOptions"]]] = ( + rest_field(name="extractionOptions", visibility=["read", "create", "update", "delete", "query"]) + ) + """Controls the cardinality of the content extracted from the document by the skill.""" + chunking_properties: Optional["_models.DocumentIntelligenceLayoutSkillChunkingProperties"] = rest_field( + name="chunkingProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality for chunking the content.""" + odata_type: Literal["#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + output_format: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"]] = None, + output_mode: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"]] = None, + markdown_header_depth: Optional[ + Union[str, "_models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth"] + ] = None, + extraction_options: Optional[ + list[Union[str, "_models.DocumentIntelligenceLayoutSkillExtractionOptions"]] + ] = None, + chunking_properties: Optional["_models.DocumentIntelligenceLayoutSkillChunkingProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill" # type: ignore + + +class DocumentIntelligenceLayoutSkillChunkingProperties(_Model): # pylint: disable=name-too-long + """Controls the cardinality for chunking the content. + + :ivar unit: The unit of the chunk. "characters" + :vartype unit: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit + :ivar maximum_length: The maximum chunk length in characters. Default is 500. + :vartype maximum_length: int + :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. + :vartype overlap_length: int + """ + + unit: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillChunkingUnit"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The unit of the chunk. \"characters\"""" + maximum_length: Optional[int] = rest_field( + name="maximumLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum chunk length in characters. Default is 500.""" + overlap_length: Optional[int] = rest_field( + name="overlapLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The length of overlap provided between two text chunks. Default is 0.""" + + @overload + def __init__( + self, + *, + unit: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillChunkingUnit"]] = None, + maximum_length: Optional[int] = None, + overlap_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DocumentKeysOrIds(_Model): + """The type of the keysOrIds. + + :ivar document_keys: document keys to be reset. + :vartype document_keys: list[str] + :ivar datasource_document_ids: datasource document identifiers to be reset. + :vartype datasource_document_ids: list[str] + """ + + document_keys: Optional[list[str]] = rest_field( + name="documentKeys", visibility=["read", "create", "update", "delete", "query"] + ) + """document keys to be reset.""" + datasource_document_ids: Optional[list[str]] = rest_field( + name="datasourceDocumentIds", visibility=["read", "create", "update", "delete", "query"] + ) + """datasource document identifiers to be reset.""" + + @overload + def __init__( + self, + *, + document_keys: Optional[list[str]] = None, + datasource_document_ids: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EdgeNGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.EdgeNGramTokenFilter"): + """Generates n-grams of the given size(s) starting from the front or the back of an input token. + This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of + maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. + :vartype max_gram: int + :ivar side: Specifies which side of the input the n-gram should be generated from. Default is + "front". Known values are: "front" and "back". + :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.EdgeNGramTokenFilter". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Must be less than the value of maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2.""" + side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies which side of the input the n-gram should be generated from. Default is \"front\". + Known values are: \"front\" and \"back\".""" + odata_type: Literal["#Microsoft.Azure.Search.EdgeNGramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.EdgeNGramTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.EdgeNGramTokenFilter" # type: ignore + + +class EdgeNGramTokenFilterV2(TokenFilter, discriminator="#Microsoft.Azure.Search.EdgeNGramTokenFilterV2"): + """Generates n-grams of the given size(s) starting from the front or the back of an input token. + This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar side: Specifies which side of the input the n-gram should be generated from. Default is + "front". Known values are: "front" and "back". + :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies which side of the input the n-gram should be generated from. Default is \"front\". + Known values are: \"front\" and \"back\".""" + odata_type: Literal["#Microsoft.Azure.Search.EdgeNGramTokenFilterV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.EdgeNGramTokenFilterV2\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2" # type: ignore + + +class EdgeNGramTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.EdgeNGramTokenizer"): + """Tokenizes the input from an edge into n-grams of the given size(s). This tokenizer is + implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar token_chars: Character classes to keep in the tokens. + :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.EdgeNGramTokenizer". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = rest_field( + name="tokenChars", visibility=["read", "create", "update", "delete", "query"] + ) + """Character classes to keep in the tokens.""" + odata_type: Literal["#Microsoft.Azure.Search.EdgeNGramTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.EdgeNGramTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.EdgeNGramTokenizer" # type: ignore + + +class ElisionTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.ElisionTokenFilter"): + """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). This + token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar articles: The set of articles to remove. + :vartype articles: list[str] + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.ElisionTokenFilter". + :vartype odata_type: str + """ + + articles: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The set of articles to remove.""" + odata_type: Literal["#Microsoft.Azure.Search.ElisionTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.ElisionTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + articles: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ElisionTokenFilter" # type: ignore + + +class EntityLinkingSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.V3.EntityLinkingSkill"): + """Using the Text Analytics API, extracts linked entities from text. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.V3.EntityLinkingSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.V3.EntityLinkingSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.V3.EntityLinkingSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[str] = None, + minimum_precision: Optional[float] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.V3.EntityLinkingSkill" # type: ignore + + +class EntityRecognitionSkillV3(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.V3.EntityRecognitionSkill"): + """Using the Text Analytics API, extracts entities of different types from text. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar categories: A list of entity categories that should be extracted. + :vartype categories: list[str] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar model_version: The version of the model to use when calling the Text Analytics API. It + will default to the latest available when not specified. We recommend you do not specify this + value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.V3.EntityRecognitionSkill". + :vartype odata_type: str + """ + + categories: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of entity categories that should be extracted.""" + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics API. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.V3.EntityRecognitionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.V3.EntityRecognitionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + categories: Optional[list[str]] = None, + default_language_code: Optional[str] = None, + minimum_precision: Optional[float] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill" # type: ignore + + +class VectorSearchAlgorithmConfiguration(_Model): + """Contains configuration options specific to the algorithm used during indexing or querying. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ExhaustiveKnnAlgorithmConfiguration, HnswAlgorithmConfiguration + + :ivar name: The name to associate with this particular configuration. Required. + :vartype name: str + :ivar kind: Type of VectorSearchAlgorithmConfiguration. Required. Known values are: "hnsw" and + "exhaustiveKnn". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind + """ + + __mapping__: dict[str, _Model] = {} + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular configuration. Required.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of VectorSearchAlgorithmConfiguration. Required. Known values are: \"hnsw\" and + \"exhaustiveKnn\".""" + + @overload + def __init__( + self, + *, + name: str, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ExhaustiveKnnAlgorithmConfiguration(VectorSearchAlgorithmConfiguration, discriminator="exhaustiveKnn"): + """Contains configuration options specific to the exhaustive KNN algorithm used during querying, + which will perform brute-force search across the entire vector index. + + :ivar name: The name to associate with this particular configuration. Required. + :vartype name: str + :ivar parameters: Contains the parameters specific to exhaustive KNN algorithm. + :vartype parameters: ~azure.search.documents.indexes.models.ExhaustiveKnnParameters + :ivar kind: The name of the kind of algorithm being configured for use with vector search. + Required. Exhaustive KNN algorithm which will perform brute-force search. + :vartype kind: str or ~azure.search.documents.indexes.models.EXHAUSTIVE_KNN + """ + + parameters: Optional["_models.ExhaustiveKnnParameters"] = rest_field( + name="exhaustiveKnnParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to exhaustive KNN algorithm.""" + kind: Literal[VectorSearchAlgorithmKind.EXHAUSTIVE_KNN] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of algorithm being configured for use with vector search. Required. + Exhaustive KNN algorithm which will perform brute-force search.""" + + @overload + def __init__( + self, + *, + name: str, + parameters: Optional["_models.ExhaustiveKnnParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchAlgorithmKind.EXHAUSTIVE_KNN # type: ignore + + +class ExhaustiveKnnParameters(_Model): + """Contains the parameters specific to exhaustive KNN algorithm. + + :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", + "euclidean", "dotProduct", and "hamming". + :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric + """ + + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The similarity metric to use for vector comparisons. Known values are: \"cosine\", + \"euclidean\", \"dotProduct\", and \"hamming\".""" + + @overload + def __init__( + self, + *, + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FieldMapping(_Model): + """Defines a mapping between a field in a data source and a target field in an index. + + :ivar source_field_name: The name of the field in the data source. Required. + :vartype source_field_name: str + :ivar target_field_name: The name of the target field in the index. Same as the source field + name by default. + :vartype target_field_name: str + :ivar mapping_function: A function to apply to each source field value before indexing. + :vartype mapping_function: ~azure.search.documents.indexes.models.FieldMappingFunction + """ + + source_field_name: str = rest_field( + name="sourceFieldName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the field in the data source. Required.""" + target_field_name: Optional[str] = rest_field( + name="targetFieldName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the target field in the index. Same as the source field name by default.""" + mapping_function: Optional["_models.FieldMappingFunction"] = rest_field( + name="mappingFunction", visibility=["read", "create", "update", "delete", "query"] + ) + """A function to apply to each source field value before indexing.""" + + @overload + def __init__( + self, + *, + source_field_name: str, + target_field_name: Optional[str] = None, + mapping_function: Optional["_models.FieldMappingFunction"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FieldMappingFunction(_Model): + """Represents a function that transforms a value from a data source before indexing. + + :ivar name: The name of the field mapping function. Required. + :vartype name: str + :ivar parameters: A dictionary of parameter name/value pairs to pass to the function. Each + value must be of a primitive type. + :vartype parameters: dict[str, any] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the field mapping function. Required.""" + parameters: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A dictionary of parameter name/value pairs to pass to the function. Each value must be of a + primitive type.""" + + @overload + def __init__( + self, + *, + name: str, + parameters: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FreshnessScoringFunction(ScoringFunction, discriminator="freshness"): + """Defines a function that boosts scores based on the value of a date-time field. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the freshness scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.FreshnessScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is + "freshness". + :vartype type: str + """ + + parameters: "_models.FreshnessScoringParameters" = rest_field( + name="freshness", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the freshness scoring function. Required.""" + type: Literal["freshness"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"freshness\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.FreshnessScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "freshness" # type: ignore + + +class FreshnessScoringParameters(_Model): + """Provides parameter values to a freshness scoring function. + + :ivar boosting_duration: The expiration period after which boosting will stop for a particular + document. Required. + :vartype boosting_duration: ~datetime.timedelta + """ + + boosting_duration: datetime.timedelta = rest_field( + name="boostingDuration", visibility=["read", "create", "update", "delete", "query"] + ) + """The expiration period after which boosting will stop for a particular document. Required.""" + + @overload + def __init__( + self, + *, + boosting_duration: datetime.timedelta, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GetIndexStatisticsResult(_Model): + """Statistics for a given index. Statistics are collected periodically and are not guaranteed to + always be up-to-date. + + :ivar document_count: The number of documents in the index. Required. + :vartype document_count: int + :ivar storage_size: The amount of storage in bytes consumed by the index. Required. + :vartype storage_size: int + :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. + Required. + :vartype vector_index_size: int + """ + + document_count: int = rest_field(name="documentCount", visibility=["read"]) + """The number of documents in the index. Required.""" + storage_size: int = rest_field(name="storageSize", visibility=["read"]) + """The amount of storage in bytes consumed by the index. Required.""" + vector_index_size: int = rest_field(name="vectorIndexSize", visibility=["read"]) + """The amount of memory in bytes consumed by vectors in the index. Required.""" + + +class HighWaterMarkChangeDetectionPolicy( + DataChangeDetectionPolicy, discriminator="#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" +): + """Defines a data change detection policy that captures changes based on the value of a high water + mark column. + + :ivar high_water_mark_column_name: The name of the high water mark column. Required. + :vartype high_water_mark_column_name: str + :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. + Default value is "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy". + :vartype odata_type: str + """ + + high_water_mark_column_name: str = rest_field( + name="highWaterMarkColumnName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the high water mark column. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data change detection policy. Required. Default value is + \"#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy\".""" + + @overload + def __init__( + self, + *, + high_water_mark_column_name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" # type: ignore + + +class HnswAlgorithmConfiguration(VectorSearchAlgorithmConfiguration, discriminator="hnsw"): + """Contains configuration options specific to the HNSW approximate nearest neighbors algorithm + used during indexing and querying. The HNSW algorithm offers a tunable trade-off between search + speed and accuracy. + + :ivar name: The name to associate with this particular configuration. Required. + :vartype name: str + :ivar parameters: Contains the parameters specific to HNSW algorithm. + :vartype parameters: ~azure.search.documents.indexes.models.HnswParameters + :ivar kind: The name of the kind of algorithm being configured for use with vector search. + Required. HNSW (Hierarchical Navigable Small World), a type of approximate nearest neighbors + algorithm. + :vartype kind: str or ~azure.search.documents.indexes.models.HNSW + """ + + parameters: Optional["_models.HnswParameters"] = rest_field( + name="hnswParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to HNSW algorithm.""" + kind: Literal[VectorSearchAlgorithmKind.HNSW] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of algorithm being configured for use with vector search. Required. HNSW + (Hierarchical Navigable Small World), a type of approximate nearest neighbors algorithm.""" + + @overload + def __init__( + self, + *, + name: str, + parameters: Optional["_models.HnswParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchAlgorithmKind.HNSW # type: ignore + + +class HnswParameters(_Model): + """Contains the parameters specific to the HNSW algorithm. + + :ivar m: The number of bi-directional links created for every new element during construction. + Increasing this parameter value may improve recall and reduce retrieval times for datasets with + high intrinsic dimensionality at the expense of increased memory consumption and longer + indexing time. + :vartype m: int + :ivar ef_construction: The size of the dynamic list containing the nearest neighbors, which is + used during index time. Increasing this parameter may improve index quality, at the expense of + increased indexing time. At a certain point, increasing this parameter leads to diminishing + returns. + :vartype ef_construction: int + :ivar ef_search: The size of the dynamic list containing the nearest neighbors, which is used + during search time. Increasing this parameter may improve search results, at the expense of + slower search. At a certain point, increasing this parameter leads to diminishing returns. + :vartype ef_search: int + :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", + "euclidean", "dotProduct", and "hamming". + :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric + """ + + m: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of bi-directional links created for every new element during construction. + Increasing this parameter value may improve recall and reduce retrieval times for datasets with + high intrinsic dimensionality at the expense of increased memory consumption and longer + indexing time.""" + ef_construction: Optional[int] = rest_field( + name="efConstruction", visibility=["read", "create", "update", "delete", "query"] + ) + """The size of the dynamic list containing the nearest neighbors, which is used during index time. + Increasing this parameter may improve index quality, at the expense of increased indexing time. + At a certain point, increasing this parameter leads to diminishing returns.""" + ef_search: Optional[int] = rest_field(name="efSearch", visibility=["read", "create", "update", "delete", "query"]) + """The size of the dynamic list containing the nearest neighbors, which is used during search + time. Increasing this parameter may improve search results, at the expense of slower search. At + a certain point, increasing this parameter leads to diminishing returns.""" + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The similarity metric to use for vector comparisons. Known values are: \"cosine\", + \"euclidean\", \"dotProduct\", and \"hamming\".""" + + @overload + def __init__( + self, + *, + m: Optional[int] = None, + ef_construction: Optional[int] = None, + ef_search: Optional[int] = None, + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ImageAnalysisSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Vision.ImageAnalysisSkill"): + """A skill that analyzes image files. It extracts a rich set of visual features based on the image + content. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "ar", "az", "bg", "bs", "ca", "cs", "cy", "da", "de", "el", "en", "es", "et", + "eu", "fi", "fr", "ga", "gl", "he", "hi", "hr", "hu", "id", "it", "ja", "kk", "ko", "lt", "lv", + "mk", "ms", "nb", "nl", "pl", "prs", "pt-BR", "pt", "pt-PT", "ro", "ru", "sk", "sl", "sr-Cyrl", + "sr-Latn", "sv", "th", "tr", "uk", "vi", "zh", "zh-Hans", and "zh-Hant". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.ImageAnalysisSkillLanguage + :ivar visual_features: A list of visual features. + :vartype visual_features: list[str or ~azure.search.documents.indexes.models.VisualFeature] + :ivar details: A string indicating which domain-specific details to return. + :vartype details: list[str or ~azure.search.documents.indexes.models.ImageDetail] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Vision.ImageAnalysisSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.ImageAnalysisSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"ar\", + \"az\", \"bg\", \"bs\", \"ca\", \"cs\", \"cy\", \"da\", \"de\", \"el\", \"en\", \"es\", \"et\", + \"eu\", \"fi\", \"fr\", \"ga\", \"gl\", \"he\", \"hi\", \"hr\", \"hu\", \"id\", \"it\", \"ja\", + \"kk\", \"ko\", \"lt\", \"lv\", \"mk\", \"ms\", \"nb\", \"nl\", \"pl\", \"prs\", \"pt-BR\", + \"pt\", \"pt-PT\", \"ro\", \"ru\", \"sk\", \"sl\", \"sr-Cyrl\", \"sr-Latn\", \"sv\", \"th\", + \"tr\", \"uk\", \"vi\", \"zh\", \"zh-Hans\", and \"zh-Hant\".""" + visual_features: Optional[list[Union[str, "_models.VisualFeature"]]] = rest_field( + name="visualFeatures", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of visual features.""" + details: Optional[list[Union[str, "_models.ImageDetail"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A string indicating which domain-specific details to return.""" + odata_type: Literal["#Microsoft.Skills.Vision.ImageAnalysisSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Vision.ImageAnalysisSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.ImageAnalysisSkillLanguage"]] = None, + visual_features: Optional[list[Union[str, "_models.VisualFeature"]]] = None, + details: Optional[list[Union[str, "_models.ImageDetail"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Vision.ImageAnalysisSkill" # type: ignore + + +class IndexedOneLakeKnowledgeSource(KnowledgeSource, discriminator="indexedOneLake"): + """Configuration for OneLake knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the knowledge source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that reads data from indexed OneLake. + :vartype kind: str or ~azure.search.documents.indexes.models.INDEXED_ONE_LAKE + :ivar indexed_one_lake_parameters: The parameters for the knowledge source. Required. + :vartype indexed_one_lake_parameters: + ~azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSourceParameters + """ + + kind: Literal[KnowledgeSourceKind.INDEXED_ONE_LAKE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that reads data from indexed OneLake.""" + indexed_one_lake_parameters: "_models.IndexedOneLakeKnowledgeSourceParameters" = rest_field( + name="indexedOneLakeParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The parameters for the knowledge source. Required.""" + + @overload + def __init__( + self, + *, + name: str, + indexed_one_lake_parameters: "_models.IndexedOneLakeKnowledgeSourceParameters", + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.INDEXED_ONE_LAKE # type: ignore + + +class IndexedOneLakeKnowledgeSourceParameters(_Model): + """Parameters for OneLake knowledge source. + + :ivar fabric_workspace_id: OneLake workspace ID. Required. + :vartype fabric_workspace_id: str + :ivar lakehouse_id: Specifies which OneLake lakehouse to access. Required. + :vartype lakehouse_id: str + :ivar target_path: Optional OneLakehouse folder or shortcut to filter OneLake content. + :vartype target_path: str + :ivar ingestion_parameters: Consolidates all general ingestion settings. + :vartype ingestion_parameters: + ~azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters + :ivar created_resources: Resources created by the knowledge source. + :vartype created_resources: ~azure.search.documents.indexes.models.CreatedResources + """ + + fabric_workspace_id: str = rest_field( + name="fabricWorkspaceId", visibility=["read", "create", "update", "delete", "query"] + ) + """OneLake workspace ID. Required.""" + lakehouse_id: str = rest_field(name="lakehouseId", visibility=["read", "create", "update", "delete", "query"]) + """Specifies which OneLake lakehouse to access. Required.""" + target_path: Optional[str] = rest_field( + name="targetPath", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional OneLakehouse folder or shortcut to filter OneLake content.""" + ingestion_parameters: Optional["_knowledgebases_models3.KnowledgeSourceIngestionParameters"] = rest_field( + name="ingestionParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Consolidates all general ingestion settings.""" + created_resources: Optional["_models.CreatedResources"] = rest_field(name="createdResources", visibility=["read"]) + """Resources created by the knowledge source.""" + + @overload + def __init__( + self, + *, + fabric_workspace_id: str, + lakehouse_id: str, + target_path: Optional[str] = None, + ingestion_parameters: Optional["_knowledgebases_models3.KnowledgeSourceIngestionParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexedSharePointKnowledgeSource(KnowledgeSource, discriminator="indexedSharePoint"): + """Configuration for SharePoint knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the knowledge source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that reads data from indexed SharePoint. + :vartype kind: str or ~azure.search.documents.indexes.models.INDEXED_SHARE_POINT + :ivar indexed_share_point_parameters: The parameters for the knowledge source. Required. + :vartype indexed_share_point_parameters: + ~azure.search.documents.indexes.models.IndexedSharePointKnowledgeSourceParameters + """ + + kind: Literal[KnowledgeSourceKind.INDEXED_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that reads data from indexed SharePoint.""" + indexed_share_point_parameters: "_models.IndexedSharePointKnowledgeSourceParameters" = rest_field( + name="indexedSharePointParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The parameters for the knowledge source. Required.""" + + @overload + def __init__( + self, + *, + name: str, + indexed_share_point_parameters: "_models.IndexedSharePointKnowledgeSourceParameters", + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.INDEXED_SHARE_POINT # type: ignore + + +class IndexedSharePointKnowledgeSourceParameters(_Model): # pylint: disable=name-too-long + """Parameters for SharePoint knowledge source. + + :ivar connection_string: SharePoint connection string with format: + SharePointOnlineEndpoint=[SharePoint site url];ApplicationId=[Azure AD App + ID];ApplicationSecret=[Azure AD App client secret];TenantId=[SharePoint site tenant id]. + Required. + :vartype connection_string: str + :ivar container_name: Specifies which SharePoint libraries to access. Required. Known values + are: "defaultSiteLibrary", "allSiteLibraries", and "useQuery". + :vartype container_name: str or + ~azure.search.documents.indexes.models.IndexedSharePointContainerName + :ivar query: Optional query to filter SharePoint content. + :vartype query: str + :ivar ingestion_parameters: Consolidates all general ingestion settings. + :vartype ingestion_parameters: + ~azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters + :ivar created_resources: Resources created by the knowledge source. + :vartype created_resources: ~azure.search.documents.indexes.models.CreatedResources + """ + + connection_string: str = rest_field( + name="connectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """SharePoint connection string with format: SharePointOnlineEndpoint=[SharePoint site + url];ApplicationId=[Azure AD App ID];ApplicationSecret=[Azure AD App client + secret];TenantId=[SharePoint site tenant id]. Required.""" + container_name: Union[str, "_models.IndexedSharePointContainerName"] = rest_field( + name="containerName", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies which SharePoint libraries to access. Required. Known values are: + \"defaultSiteLibrary\", \"allSiteLibraries\", and \"useQuery\".""" + query: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional query to filter SharePoint content.""" + ingestion_parameters: Optional["_knowledgebases_models3.KnowledgeSourceIngestionParameters"] = rest_field( + name="ingestionParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Consolidates all general ingestion settings.""" + created_resources: Optional["_models.CreatedResources"] = rest_field(name="createdResources", visibility=["read"]) + """Resources created by the knowledge source.""" + + @overload + def __init__( + self, + *, + connection_string: str, + container_name: Union[str, "_models.IndexedSharePointContainerName"], + query: Optional[str] = None, + ingestion_parameters: Optional["_knowledgebases_models3.KnowledgeSourceIngestionParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexerCurrentState(_Model): + """Represents all of the state that defines and dictates the indexer's current execution. + + :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", + "indexingResetDocs", and "indexingResync". + :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode + :ivar all_docs_initial_tracking_state: Change tracking state used when indexing starts on all + documents in the datasource. + :vartype all_docs_initial_tracking_state: str + :ivar all_docs_final_tracking_state: Change tracking state value when indexing finishes on all + documents in the datasource. + :vartype all_docs_final_tracking_state: str + :ivar reset_docs_initial_tracking_state: Change tracking state used when indexing starts on + select, reset documents in the datasource. + :vartype reset_docs_initial_tracking_state: str + :ivar reset_docs_final_tracking_state: Change tracking state value when indexing finishes on + select, reset documents in the datasource. + :vartype reset_docs_final_tracking_state: str + :ivar resync_initial_tracking_state: Change tracking state used when indexing starts on + selective options from the datasource. + :vartype resync_initial_tracking_state: str + :ivar resync_final_tracking_state: Change tracking state value when indexing finishes on + selective options from the datasource. + :vartype resync_final_tracking_state: str + :ivar reset_document_keys: The list of document keys that have been reset. The document key is + the document's unique identifier for the data in the search index. The indexer will prioritize + selectively re-ingesting these keys. + :vartype reset_document_keys: list[str] + :ivar reset_datasource_document_ids: The list of datasource document ids that have been reset. + The datasource document id is the unique identifier for the data in the datasource. The indexer + will prioritize selectively re-ingesting these ids. + :vartype reset_datasource_document_ids: list[str] + """ + + mode: Optional[Union[str, "_models.IndexingMode"]] = rest_field(visibility=["read"]) + """The mode the indexer is running in. Known values are: \"indexingAllDocs\", + \"indexingResetDocs\", and \"indexingResync\".""" + all_docs_initial_tracking_state: Optional[str] = rest_field(name="allDocsInitialTrackingState", visibility=["read"]) + """Change tracking state used when indexing starts on all documents in the datasource.""" + all_docs_final_tracking_state: Optional[str] = rest_field(name="allDocsFinalTrackingState", visibility=["read"]) + """Change tracking state value when indexing finishes on all documents in the datasource.""" + reset_docs_initial_tracking_state: Optional[str] = rest_field( + name="resetDocsInitialTrackingState", visibility=["read"] + ) + """Change tracking state used when indexing starts on select, reset documents in the datasource.""" + reset_docs_final_tracking_state: Optional[str] = rest_field(name="resetDocsFinalTrackingState", visibility=["read"]) + """Change tracking state value when indexing finishes on select, reset documents in the + datasource.""" + resync_initial_tracking_state: Optional[str] = rest_field(name="resyncInitialTrackingState", visibility=["read"]) + """Change tracking state used when indexing starts on selective options from the datasource.""" + resync_final_tracking_state: Optional[str] = rest_field(name="resyncFinalTrackingState", visibility=["read"]) + """Change tracking state value when indexing finishes on selective options from the datasource.""" + reset_document_keys: Optional[list[str]] = rest_field(name="resetDocumentKeys", visibility=["read"]) + """The list of document keys that have been reset. The document key is the document's unique + identifier for the data in the search index. The indexer will prioritize selectively + re-ingesting these keys.""" + reset_datasource_document_ids: Optional[list[str]] = rest_field( + name="resetDatasourceDocumentIds", visibility=["read"] + ) + """The list of datasource document ids that have been reset. The datasource document id is the + unique identifier for the data in the datasource. The indexer will prioritize selectively + re-ingesting these ids.""" + + +class IndexerExecutionResult(_Model): + """Represents the result of an individual indexer execution. + + :ivar status: The outcome of this indexer execution. Required. Known values are: + "transientFailure", "success", "inProgress", and "reset". + :vartype status: str or ~azure.search.documents.indexes.models.IndexerExecutionStatus + :ivar status_detail: The outcome of this indexer execution. Known values are: "resetDocs" and + "resync". + :vartype status_detail: str or + ~azure.search.documents.indexes.models.IndexerExecutionStatusDetail + :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", + "indexingResetDocs", and "indexingResync". + :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode + :ivar error_message: The error message indicating the top-level error, if any. + :vartype error_message: str + :ivar start_time: The start time of this indexer execution. + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time of this indexer execution, if the execution has already completed. + :vartype end_time: ~datetime.datetime + :ivar errors: The item-level indexing errors. Required. + :vartype errors: list[~azure.search.documents.indexes.models.SearchIndexerError] + :ivar warnings: The item-level indexing warnings. Required. + :vartype warnings: list[~azure.search.documents.indexes.models.SearchIndexerWarning] + :ivar item_count: The number of items that were processed during this indexer execution. This + includes both successfully processed items and items where indexing was attempted but failed. + Required. + :vartype item_count: int + :ivar failed_item_count: The number of items that failed to be indexed during this indexer + execution. Required. + :vartype failed_item_count: int + :ivar initial_tracking_state: Change tracking state with which an indexer execution started. + :vartype initial_tracking_state: str + :ivar final_tracking_state: Change tracking state with which an indexer execution finished. + :vartype final_tracking_state: str + """ + + status: Union[str, "_models.IndexerExecutionStatus"] = rest_field(visibility=["read"]) + """The outcome of this indexer execution. Required. Known values are: \"transientFailure\", + \"success\", \"inProgress\", and \"reset\".""" + status_detail: Optional[Union[str, "_models.IndexerExecutionStatusDetail"]] = rest_field( + name="statusDetail", visibility=["read"] + ) + """The outcome of this indexer execution. Known values are: \"resetDocs\" and \"resync\".""" + mode: Optional[Union[str, "_models.IndexingMode"]] = rest_field(visibility=["read"]) + """The mode the indexer is running in. Known values are: \"indexingAllDocs\", + \"indexingResetDocs\", and \"indexingResync\".""" + error_message: Optional[str] = rest_field(name="errorMessage", visibility=["read"]) + """The error message indicating the top-level error, if any.""" + start_time: Optional[datetime.datetime] = rest_field(name="startTime", visibility=["read"], format="rfc3339") + """The start time of this indexer execution.""" + end_time: Optional[datetime.datetime] = rest_field(name="endTime", visibility=["read"], format="rfc3339") + """The end time of this indexer execution, if the execution has already completed.""" + errors: list["_models.SearchIndexerError"] = rest_field(visibility=["read"]) + """The item-level indexing errors. Required.""" + warnings: list["_models.SearchIndexerWarning"] = rest_field(visibility=["read"]) + """The item-level indexing warnings. Required.""" + item_count: int = rest_field(name="itemsProcessed", visibility=["read"]) + """The number of items that were processed during this indexer execution. This includes both + successfully processed items and items where indexing was attempted but failed. Required.""" + failed_item_count: int = rest_field(name="itemsFailed", visibility=["read"]) + """The number of items that failed to be indexed during this indexer execution. Required.""" + initial_tracking_state: Optional[str] = rest_field(name="initialTrackingState", visibility=["read"]) + """Change tracking state with which an indexer execution started.""" + final_tracking_state: Optional[str] = rest_field(name="finalTrackingState", visibility=["read"]) + """Change tracking state with which an indexer execution finished.""" + + +class IndexerResyncBody(_Model): + """Request body for resync indexer operation. + + :ivar options: Re-sync options that have been pre-defined from data source. + :vartype options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] + """ + + options: Optional[list[Union[str, "_models.IndexerResyncOption"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Re-sync options that have been pre-defined from data source.""" + + @overload + def __init__( + self, + *, + options: Optional[list[Union[str, "_models.IndexerResyncOption"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexerRuntime(_Model): + """Represents the indexer's cumulative runtime consumption in the service. + + :ivar used_seconds: Cumulative runtime of the indexer from the beginningTime to endingTime, in + seconds. Required. + :vartype used_seconds: int + :ivar remaining_seconds: Cumulative runtime remaining for all indexers in the service from the + beginningTime to endingTime, in seconds. + :vartype remaining_seconds: int + :ivar beginning_time: Beginning UTC time of the 24-hour period considered for indexer runtime + usage (inclusive). Required. + :vartype beginning_time: ~datetime.datetime + :ivar ending_time: End UTC time of the 24-hour period considered for indexer runtime usage + (inclusive). Required. + :vartype ending_time: ~datetime.datetime + """ + + used_seconds: int = rest_field(name="usedSeconds", visibility=["read", "create", "update", "delete", "query"]) + """Cumulative runtime of the indexer from the beginningTime to endingTime, in seconds. Required.""" + remaining_seconds: Optional[int] = rest_field( + name="remainingSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """Cumulative runtime remaining for all indexers in the service from the beginningTime to + endingTime, in seconds.""" + beginning_time: datetime.datetime = rest_field( + name="beginningTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Beginning UTC time of the 24-hour period considered for indexer runtime usage (inclusive). + Required.""" + ending_time: datetime.datetime = rest_field( + name="endingTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """End UTC time of the 24-hour period considered for indexer runtime usage (inclusive). Required.""" + + @overload + def __init__( + self, + *, + used_seconds: int, + beginning_time: datetime.datetime, + ending_time: datetime.datetime, + remaining_seconds: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingParameters(_Model): + """Represents parameters for indexer execution. + + :ivar batch_size: The number of items that are read from the data source and indexed as a + single batch in order to improve performance. The default depends on the data source type. + :vartype batch_size: int + :ivar max_failed_items: The maximum number of items that can fail indexing for indexer + execution to still be considered successful. -1 means no limit. Default is 0. + :vartype max_failed_items: int + :ivar max_failed_items_per_batch: The maximum number of items in a single batch that can fail + indexing for the batch to still be considered successful. -1 means no limit. Default is 0. + :vartype max_failed_items_per_batch: int + :ivar configuration: A dictionary of indexer-specific configuration properties. Each name is + the name of a specific property. Each value must be of a primitive type. + :vartype configuration: ~azure.search.documents.indexes.models.IndexingParametersConfiguration + """ + + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) + """The number of items that are read from the data source and indexed as a single batch in order + to improve performance. The default depends on the data source type.""" + max_failed_items: Optional[int] = rest_field( + name="maxFailedItems", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of items that can fail indexing for indexer execution to still be considered + successful. -1 means no limit. Default is 0.""" + max_failed_items_per_batch: Optional[int] = rest_field( + name="maxFailedItemsPerBatch", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of items in a single batch that can fail indexing for the batch to still be + considered successful. -1 means no limit. Default is 0.""" + configuration: Optional["_models.IndexingParametersConfiguration"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of indexer-specific configuration properties. Each name is the name of a specific + property. Each value must be of a primitive type.""" + + @overload + def __init__( + self, + *, + batch_size: Optional[int] = None, + max_failed_items: Optional[int] = None, + max_failed_items_per_batch: Optional[int] = None, + configuration: Optional["_models.IndexingParametersConfiguration"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingParametersConfiguration(_Model): + """A dictionary of indexer-specific configuration properties. Each name is the name of a specific + property. Each value must be of a primitive type. + + :ivar parsing_mode: Represents the parsing mode for indexing from an Azure blob data source. + Known values are: "default", "text", "delimitedText", "json", "jsonArray", "jsonLines", and + "markdown". + :vartype parsing_mode: str or ~azure.search.documents.indexes.models.BlobIndexerParsingMode + :ivar excluded_file_name_extensions: Comma-delimited list of filename extensions to ignore when + processing from Azure blob storage. For example, you could exclude ".png, .mp4" to skip over + those files during indexing. + :vartype excluded_file_name_extensions: str + :ivar indexed_file_name_extensions: Comma-delimited list of filename extensions to select when + processing from Azure blob storage. For example, you could focus indexing on specific + application files ".docx, .pptx, .msg" to specifically include those file types. + :vartype indexed_file_name_extensions: str + :ivar fail_on_unsupported_content_type: For Azure blobs, set to false if you want to continue + indexing when an unsupported content type is encountered, and you don't know all the content + types (file extensions) in advance. + :vartype fail_on_unsupported_content_type: bool + :ivar fail_on_unprocessable_document: For Azure blobs, set to false if you want to continue + indexing if a document fails indexing. + :vartype fail_on_unprocessable_document: bool + :ivar index_storage_metadata_only_for_oversized_documents: For Azure blobs, set this property + to true to still index storage metadata for blob content that is too large to process. + Oversized blobs are treated as errors by default. For limits on blob size, see + `https://learn.microsoft.com/azure/search/search-limits-quotas-capacity + `_. + :vartype index_storage_metadata_only_for_oversized_documents: bool + :ivar delimited_text_headers: For CSV blobs, specifies a comma-delimited list of column + headers, useful for mapping source fields to destination fields in an index. + :vartype delimited_text_headers: str + :ivar delimited_text_delimiter: For CSV blobs, specifies the end-of-line single-character + delimiter for CSV files where each line starts a new document (for example, "|"). + :vartype delimited_text_delimiter: str + :ivar first_line_contains_headers: For CSV blobs, indicates that the first (non-blank) line of + each blob contains headers. + :vartype first_line_contains_headers: bool + :ivar markdown_parsing_submode: Specifies the submode that will determine whether a markdown + file will be parsed into exactly one search document or multiple search documents. Default is + ``oneToMany``. Known values are: "oneToMany" and "oneToOne". + :vartype markdown_parsing_submode: str or + ~azure.search.documents.indexes.models.MarkdownParsingSubmode + :ivar markdown_header_depth: Specifies the max header depth that will be considered while + grouping markdown content. Default is ``h6``. Known values are: "h1", "h2", "h3", "h4", "h5", + and "h6". + :vartype markdown_header_depth: str or + ~azure.search.documents.indexes.models.MarkdownHeaderDepth + :ivar document_root: For JSON arrays, given a structured or semi-structured document, you can + specify a path to the array using this property. + :vartype document_root: str + :ivar data_to_extract: Specifies the data to extract from Azure blob storage and tells the + indexer which data to extract from image content when "imageAction" is set to a value other + than "none". This applies to embedded image content in a .PDF or other application, or image + files such as .jpg and .png, in Azure blobs. Known values are: "storageMetadata", + "allMetadata", and "contentAndMetadata". + :vartype data_to_extract: str or + ~azure.search.documents.indexes.models.BlobIndexerDataToExtract + :ivar image_action: Determines how to process embedded images and image files in Azure blob + storage. Setting the "imageAction" configuration to any value other than "none" requires that + a skillset also be attached to that indexer. Known values are: "none", + "generateNormalizedImages", and "generateNormalizedImagePerPage". + :vartype image_action: str or ~azure.search.documents.indexes.models.BlobIndexerImageAction + :ivar allow_skillset_to_read_file_data: If true, will create a path //document//file_data that + is an object representing the original file data downloaded from your blob data source. This + allows you to pass the original file data to a custom skill for processing within the + enrichment pipeline, or to the Document Extraction skill. + :vartype allow_skillset_to_read_file_data: bool + :ivar pdf_text_rotation_algorithm: Determines algorithm for text extraction from PDF files in + Azure blob storage. Known values are: "none" and "detectAngles". + :vartype pdf_text_rotation_algorithm: str or + ~azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm + :ivar execution_environment: Specifies the environment in which the indexer should execute. + Known values are: "standard" and "private". + :vartype execution_environment: str or + ~azure.search.documents.indexes.models.IndexerExecutionEnvironment + :ivar query_timeout: Increases the timeout beyond the 5-minute default for Azure SQL database + data sources, specified in the format "hh:mm:ss". + :vartype query_timeout: str + """ + + parsing_mode: Optional[Union[str, "_models.BlobIndexerParsingMode"]] = rest_field( + name="parsingMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Represents the parsing mode for indexing from an Azure blob data source. Known values are: + \"default\", \"text\", \"delimitedText\", \"json\", \"jsonArray\", \"jsonLines\", and + \"markdown\".""" + excluded_file_name_extensions: Optional[str] = rest_field( + name="excludedFileNameExtensions", visibility=["read", "create", "update", "delete", "query"] + ) + """Comma-delimited list of filename extensions to ignore when processing from Azure blob storage. + For example, you could exclude \".png, .mp4\" to skip over those files during indexing.""" + indexed_file_name_extensions: Optional[str] = rest_field( + name="indexedFileNameExtensions", visibility=["read", "create", "update", "delete", "query"] + ) + """Comma-delimited list of filename extensions to select when processing from Azure blob storage. + For example, you could focus indexing on specific application files \".docx, .pptx, .msg\" to + specifically include those file types.""" + fail_on_unsupported_content_type: Optional[bool] = rest_field( + name="failOnUnsupportedContentType", visibility=["read", "create", "update", "delete", "query"] + ) + """For Azure blobs, set to false if you want to continue indexing when an unsupported content type + is encountered, and you don't know all the content types (file extensions) in advance.""" + fail_on_unprocessable_document: Optional[bool] = rest_field( + name="failOnUnprocessableDocument", visibility=["read", "create", "update", "delete", "query"] + ) + """For Azure blobs, set to false if you want to continue indexing if a document fails indexing.""" + index_storage_metadata_only_for_oversized_documents: Optional[bool] = rest_field( + name="indexStorageMetadataOnlyForOversizedDocuments", visibility=["read", "create", "update", "delete", "query"] + ) + """For Azure blobs, set this property to true to still index storage metadata for blob content + that is too large to process. Oversized blobs are treated as errors by default. For limits on + blob size, see `https://learn.microsoft.com/azure/search/search-limits-quotas-capacity + `_.""" + delimited_text_headers: Optional[str] = rest_field( + name="delimitedTextHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """For CSV blobs, specifies a comma-delimited list of column headers, useful for mapping source + fields to destination fields in an index.""" + delimited_text_delimiter: Optional[str] = rest_field( + name="delimitedTextDelimiter", visibility=["read", "create", "update", "delete", "query"] + ) + """For CSV blobs, specifies the end-of-line single-character delimiter for CSV files where each + line starts a new document (for example, \"|\").""" + first_line_contains_headers: Optional[bool] = rest_field( + name="firstLineContainsHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """For CSV blobs, indicates that the first (non-blank) line of each blob contains headers.""" + markdown_parsing_submode: Optional[Union[str, "_models.MarkdownParsingSubmode"]] = rest_field( + name="markdownParsingSubmode", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the submode that will determine whether a markdown file will be parsed into exactly + one search document or multiple search documents. Default is ``oneToMany``. Known values are: + \"oneToMany\" and \"oneToOne\".""" + markdown_header_depth: Optional[Union[str, "_models.MarkdownHeaderDepth"]] = rest_field( + name="markdownHeaderDepth", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the max header depth that will be considered while grouping markdown content. Default + is ``h6``. Known values are: \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", and \"h6\".""" + document_root: Optional[str] = rest_field( + name="documentRoot", visibility=["read", "create", "update", "delete", "query"] + ) + """For JSON arrays, given a structured or semi-structured document, you can specify a path to the + array using this property.""" + data_to_extract: Optional[Union[str, "_models.BlobIndexerDataToExtract"]] = rest_field( + name="dataToExtract", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the data to extract from Azure blob storage and tells the indexer which data to + extract from image content when \"imageAction\" is set to a value other than \"none\". This + applies to embedded image content in a .PDF or other application, or image files such as .jpg + and .png, in Azure blobs. Known values are: \"storageMetadata\", \"allMetadata\", and + \"contentAndMetadata\".""" + image_action: Optional[Union[str, "_models.BlobIndexerImageAction"]] = rest_field( + name="imageAction", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines how to process embedded images and image files in Azure blob storage. Setting the + \"imageAction\" configuration to any value other than \"none\" requires that a skillset also be + attached to that indexer. Known values are: \"none\", \"generateNormalizedImages\", and + \"generateNormalizedImagePerPage\".""" + allow_skillset_to_read_file_data: Optional[bool] = rest_field( + name="allowSkillsetToReadFileData", visibility=["read", "create", "update", "delete", "query"] + ) + """If true, will create a path //document//file_data that is an object representing the original + file data downloaded from your blob data source. This allows you to pass the original file data + to a custom skill for processing within the enrichment pipeline, or to the Document Extraction + skill.""" + pdf_text_rotation_algorithm: Optional[Union[str, "_models.BlobIndexerPDFTextRotationAlgorithm"]] = rest_field( + name="pdfTextRotationAlgorithm", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines algorithm for text extraction from PDF files in Azure blob storage. Known values + are: \"none\" and \"detectAngles\".""" + execution_environment: Optional[Union[str, "_models.IndexerExecutionEnvironment"]] = rest_field( + name="executionEnvironment", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the environment in which the indexer should execute. Known values are: \"standard\" + and \"private\".""" + query_timeout: Optional[str] = rest_field( + name="queryTimeout", visibility=["read", "create", "update", "delete", "query"] + ) + """Increases the timeout beyond the 5-minute default for Azure SQL database data sources, + specified in the format \"hh:mm:ss\".""" + + @overload + def __init__( + self, + *, + parsing_mode: Optional[Union[str, "_models.BlobIndexerParsingMode"]] = None, + excluded_file_name_extensions: Optional[str] = None, + indexed_file_name_extensions: Optional[str] = None, + fail_on_unsupported_content_type: Optional[bool] = None, + fail_on_unprocessable_document: Optional[bool] = None, + index_storage_metadata_only_for_oversized_documents: Optional[bool] = None, + delimited_text_headers: Optional[str] = None, + delimited_text_delimiter: Optional[str] = None, + first_line_contains_headers: Optional[bool] = None, + markdown_parsing_submode: Optional[Union[str, "_models.MarkdownParsingSubmode"]] = None, + markdown_header_depth: Optional[Union[str, "_models.MarkdownHeaderDepth"]] = None, + document_root: Optional[str] = None, + data_to_extract: Optional[Union[str, "_models.BlobIndexerDataToExtract"]] = None, + image_action: Optional[Union[str, "_models.BlobIndexerImageAction"]] = None, + allow_skillset_to_read_file_data: Optional[bool] = None, + pdf_text_rotation_algorithm: Optional[Union[str, "_models.BlobIndexerPDFTextRotationAlgorithm"]] = None, + execution_environment: Optional[Union[str, "_models.IndexerExecutionEnvironment"]] = None, + query_timeout: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingSchedule(_Model): + """Represents a schedule for indexer execution. + + :ivar interval: The interval of time between indexer executions. Required. + :vartype interval: ~datetime.timedelta + :ivar start_time: The time when an indexer should start running. + :vartype start_time: ~datetime.datetime + """ + + interval: datetime.timedelta = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The interval of time between indexer executions. Required.""" + start_time: Optional[datetime.datetime] = rest_field( + name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time when an indexer should start running.""" + + @overload + def __init__( + self, + *, + interval: datetime.timedelta, + start_time: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexStatisticsSummary(_Model): + """Statistics for a given index. Statistics are collected periodically and are not guaranteed to + always be up-to-date. + + :ivar name: The name of the index. Required. + :vartype name: str + :ivar document_count: The number of documents in the index. Required. + :vartype document_count: int + :ivar storage_size: The amount of storage in bytes consumed by the index. Required. + :vartype storage_size: int + :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. + Required. + :vartype vector_index_size: int + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the index. Required.""" + document_count: int = rest_field(name="documentCount", visibility=["read"]) + """The number of documents in the index. Required.""" + storage_size: int = rest_field(name="storageSize", visibility=["read"]) + """The amount of storage in bytes consumed by the index. Required.""" + vector_index_size: int = rest_field(name="vectorIndexSize", visibility=["read"]) + """The amount of memory in bytes consumed by vectors in the index. Required.""" + + @overload + def __init__( + self, + *, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InputFieldMappingEntry(_Model): + """Input field mapping for a skill. + + :ivar name: The name of the input. Required. + :vartype name: str + :ivar source: The source of the input. + :vartype source: str + :ivar source_context: The source context used for selecting recursive inputs. + :vartype source_context: str + :ivar inputs: The recursive inputs used when creating a complex type. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the input. Required.""" + source: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The source of the input.""" + source_context: Optional[str] = rest_field( + name="sourceContext", visibility=["read", "create", "update", "delete", "query"] + ) + """The source context used for selecting recursive inputs.""" + inputs: Optional[list["_models.InputFieldMappingEntry"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The recursive inputs used when creating a complex type.""" + + @overload + def __init__( + self, + *, + name: str, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KeepTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.KeepTokenFilter"): + """A token filter that only keeps tokens with text contained in a specified list of words. This + token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar keep_words: The list of words to keep. Required. + :vartype keep_words: list[str] + :ivar lower_case_keep_words: A value indicating whether to lower case all words first. Default + is false. + :vartype lower_case_keep_words: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.KeepTokenFilter". + :vartype odata_type: str + """ + + keep_words: list[str] = rest_field(name="keepWords", visibility=["read", "create", "update", "delete", "query"]) + """The list of words to keep. Required.""" + lower_case_keep_words: Optional[bool] = rest_field( + name="keepWordsCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to lower case all words first. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.KeepTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.KeepTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + keep_words: list[str], + lower_case_keep_words: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeepTokenFilter" # type: ignore + + +class KeyPhraseExtractionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.KeyPhraseExtractionSkill"): + """A skill that uses text analytics for key phrase extraction. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "da", "nl", "en", "fi", "fr", "de", "it", "ja", "ko", "no", "pl", "pt-PT", + "pt-BR", "ru", "es", and "sv". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage + :ivar max_key_phrase_count: A number indicating how many key phrases to return. If absent, all + identified key phrases will be returned. + :vartype max_key_phrase_count: int + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.KeyPhraseExtractionSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.KeyPhraseExtractionSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"da\", + \"nl\", \"en\", \"fi\", \"fr\", \"de\", \"it\", \"ja\", \"ko\", \"no\", \"pl\", \"pt-PT\", + \"pt-BR\", \"ru\", \"es\", and \"sv\".""" + max_key_phrase_count: Optional[int] = rest_field( + name="maxKeyPhraseCount", visibility=["read", "create", "update", "delete", "query"] + ) + """A number indicating how many key phrases to return. If absent, all identified key phrases will + be returned.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.KeyPhraseExtractionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.KeyPhraseExtractionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.KeyPhraseExtractionSkillLanguage"]] = None, + max_key_phrase_count: Optional[int] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.KeyPhraseExtractionSkill" # type: ignore + + +class KeywordMarkerTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.KeywordMarkerTokenFilter"): + """Marks terms as keywords. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar keywords: A list of words to mark as keywords. Required. + :vartype keywords: list[str] + :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted + to lower case first. Default is false. + :vartype ignore_case: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.KeywordMarkerTokenFilter". + :vartype odata_type: str + """ + + keywords: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of words to mark as keywords. Required.""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to ignore case. If true, all words are converted to lower case + first. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.KeywordMarkerTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.KeywordMarkerTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + keywords: list[str], + ignore_case: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeywordMarkerTokenFilter" # type: ignore + + +class KeywordTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.KeywordTokenizer"): + """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar buffer_size: The read buffer size in bytes. Default is 256. + :vartype buffer_size: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.KeywordTokenizer". + :vartype odata_type: str + """ + + buffer_size: Optional[int] = rest_field( + name="bufferSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The read buffer size in bytes. Default is 256.""" + odata_type: Literal["#Microsoft.Azure.Search.KeywordTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.KeywordTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + buffer_size: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeywordTokenizer" # type: ignore + + +class KeywordTokenizerV2(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.KeywordTokenizerV2"): + """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 256. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.KeywordTokenizerV2". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 256. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.KeywordTokenizerV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.KeywordTokenizerV2\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeywordTokenizerV2" # type: ignore + + +class KnowledgeBase(_Model): + """Represents a knowledge base definition. + + :ivar name: The name of the knowledge base. Required. + :vartype name: str + :ivar knowledge_sources: Knowledge sources referenced by this knowledge base. Required. + :vartype knowledge_sources: + list[~azure.search.documents.indexes.models.KnowledgeSourceReference] + :ivar models: Contains configuration options on how to connect to AI models. + :vartype models: list[~azure.search.documents.indexes.models.KnowledgeBaseModel] + :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. + :vartype retrieval_reasoning_effort: + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort + :ivar output_mode: The output mode for the knowledge base. Known values are: "extractiveData" + and "answerSynthesis". + :vartype output_mode: str or + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode + :ivar e_tag: The ETag of the knowledge base. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar description: The description of the knowledge base. + :vartype description: str + :ivar retrieval_instructions: Instructions considered by the knowledge base when developing + query plan. + :vartype retrieval_instructions: str + :ivar answer_instructions: Instructions considered by the knowledge base when generating + answers. + :vartype answer_instructions: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the knowledge base. Required.""" + knowledge_sources: list["_models.KnowledgeSourceReference"] = rest_field( + name="knowledgeSources", visibility=["read", "create", "update", "delete", "query"] + ) + """Knowledge sources referenced by this knowledge base. Required.""" + models: Optional[list["_models.KnowledgeBaseModel"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options on how to connect to AI models.""" + retrieval_reasoning_effort: Optional["_knowledgebases_models3.KnowledgeRetrievalReasoningEffort"] = rest_field( + name="retrievalReasoningEffort", visibility=["read", "create", "update", "delete", "query"] + ) + """The retrieval reasoning effort configuration.""" + output_mode: Optional[Union[str, "_knowledgebases_models3.KnowledgeRetrievalOutputMode"]] = rest_field( + name="outputMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The output mode for the knowledge base. Known values are: \"extractiveData\" and + \"answerSynthesis\".""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the knowledge base.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the knowledge base.""" + retrieval_instructions: Optional[str] = rest_field( + name="retrievalInstructions", visibility=["read", "create", "update", "delete", "query"] + ) + """Instructions considered by the knowledge base when developing query plan.""" + answer_instructions: Optional[str] = rest_field( + name="answerInstructions", visibility=["read", "create", "update", "delete", "query"] + ) + """Instructions considered by the knowledge base when generating answers.""" + + @overload + def __init__( + self, + *, + name: str, + knowledge_sources: list["_models.KnowledgeSourceReference"], + models: Optional[list["_models.KnowledgeBaseModel"]] = None, + retrieval_reasoning_effort: Optional["_knowledgebases_models3.KnowledgeRetrievalReasoningEffort"] = None, + output_mode: Optional[Union[str, "_knowledgebases_models3.KnowledgeRetrievalOutputMode"]] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + description: Optional[str] = None, + retrieval_instructions: Optional[str] = None, + answer_instructions: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseModel(_Model): + """Specifies the connection parameters for the model to use for query planning. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseAzureOpenAIModel + + :ivar kind: The AI model to be used for query planning. Required. "azureOpenAI" + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeBaseModelKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The AI model to be used for query planning. Required. \"azureOpenAI\"""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseAzureOpenAIModel(KnowledgeBaseModel, discriminator="azureOpenAI"): + """Specifies the Azure OpenAI resource used to do query planning. + + :ivar kind: Required. Use Azure Open AI models for query planning. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_OPEN_AI + :ivar azure_open_ai_parameters: Azure OpenAI parameters. Required. + :vartype azure_open_ai_parameters: + ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters + """ + + kind: Literal[KnowledgeBaseModelKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. Use Azure Open AI models for query planning.""" + azure_open_ai_parameters: "_models.AzureOpenAIVectorizerParameters" = rest_field( + name="azureOpenAIParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Azure OpenAI parameters. Required.""" + + @overload + def __init__( + self, + *, + azure_open_ai_parameters: "_models.AzureOpenAIVectorizerParameters", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeBaseModelKind.AZURE_OPEN_AI # type: ignore + + +class KnowledgeSourceReference(_Model): + """Reference to a knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the knowledge source. Required.""" + + @overload + def __init__( + self, + *, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LanguageDetectionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.LanguageDetectionSkill"): + """A skill that detects the language of input text and reports a single language code for every + document submitted on the request. The language code is paired with a score indicating the + confidence of the analysis. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_country_hint: A country code to use as a hint to the language detection model if + it cannot disambiguate the language. + :vartype default_country_hint: str + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.LanguageDetectionSkill". + :vartype odata_type: str + """ + + default_country_hint: Optional[str] = rest_field( + name="defaultCountryHint", visibility=["read", "create", "update", "delete", "query"] + ) + """A country code to use as a hint to the language detection model if it cannot disambiguate the + language.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.LanguageDetectionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.LanguageDetectionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_country_hint: Optional[str] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.LanguageDetectionSkill" # type: ignore + + +class LengthTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.LengthTokenFilter"): + """Removes words that are too long or too short. This token filter is implemented using Apache + Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_length: The minimum length in characters. Default is 0. Maximum is 300. Must be less + than the value of max. + :vartype min_length: int + :ivar max_length: The maximum length in characters. Default and maximum is 300. + :vartype max_length: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.LengthTokenFilter". + :vartype odata_type: str + """ + + min_length: Optional[int] = rest_field(name="min", visibility=["read", "create", "update", "delete", "query"]) + """The minimum length in characters. Default is 0. Maximum is 300. Must be less than the value of + max.""" + max_length: Optional[int] = rest_field(name="max", visibility=["read", "create", "update", "delete", "query"]) + """The maximum length in characters. Default and maximum is 300.""" + odata_type: Literal["#Microsoft.Azure.Search.LengthTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.LengthTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.LengthTokenFilter" # type: ignore + + +class LimitTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.LimitTokenFilter"): + """Limits the number of tokens while indexing. This token filter is implemented using Apache + Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_count: The maximum number of tokens to produce. Default is 1. + :vartype max_token_count: int + :ivar consume_all_tokens: A value indicating whether all tokens from the input must be consumed + even if maxTokenCount is reached. Default is false. + :vartype consume_all_tokens: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.LimitTokenFilter". + :vartype odata_type: str + """ + + max_token_count: Optional[int] = rest_field( + name="maxTokenCount", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of tokens to produce. Default is 1.""" + consume_all_tokens: Optional[bool] = rest_field( + name="consumeAllTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether all tokens from the input must be consumed even if maxTokenCount is + reached. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.LimitTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.LimitTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_count: Optional[int] = None, + consume_all_tokens: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.LimitTokenFilter" # type: ignore + + +class ListDataSourcesResult(_Model): + """Response from a List Datasources request. If successful, it includes the full definitions of + all datasources. + + :ivar data_sources: The datasources in the Search service. Required. + :vartype data_sources: + list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + """ + + data_sources: list["_models.SearchIndexerDataSourceConnection"] = rest_field(name="value", visibility=["read"]) + """The datasources in the Search service. Required.""" + + +class ListIndexersResult(_Model): + """Response from a List Indexers request. If successful, it includes the full definitions of all + indexers. + + :ivar indexers: The indexers in the Search service. Required. + :vartype indexers: list[~azure.search.documents.indexes.models.SearchIndexer] + """ + + indexers: list["_models.SearchIndexer"] = rest_field(name="value", visibility=["read"]) + """The indexers in the Search service. Required.""" + + +class ListSkillsetsResult(_Model): + """Response from a list skillset request. If successful, it includes the full definitions of all + skillsets. + + :ivar skillsets: The skillsets defined in the Search service. Required. + :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + """ + + skillsets: list["_models.SearchIndexerSkillset"] = rest_field(name="value", visibility=["read"]) + """The skillsets defined in the Search service. Required.""" + + +class ListSynonymMapsResult(_Model): + """Response from a List SynonymMaps request. If successful, it includes the full definitions of + all synonym maps. + + :ivar synonym_maps: The synonym maps in the Search service. Required. + :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] + """ + + synonym_maps: list["_models.SynonymMap"] = rest_field(name="value", visibility=["read"]) + """The synonym maps in the Search service. Required.""" + + +class LuceneStandardAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StandardAnalyzer"): + """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop + filter. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar stopwords: A list of stopwords. + :vartype stopwords: list[str] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.StandardAnalyzer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stopwords.""" + odata_type: Literal["#Microsoft.Azure.Search.StandardAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.StandardAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + stopwords: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StandardAnalyzer" # type: ignore + + +class LuceneStandardTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.StandardTokenizer"): + """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using + Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.StandardTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split.""" + odata_type: Literal["#Microsoft.Azure.Search.StandardTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.StandardTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StandardTokenizer" # type: ignore + + +class LuceneStandardTokenizerV2(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.StandardTokenizerV2"): + """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using + Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.StandardTokenizerV2". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.StandardTokenizerV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.StandardTokenizerV2\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StandardTokenizerV2" # type: ignore + + +class MagnitudeScoringFunction(ScoringFunction, discriminator="magnitude"): + """Defines a function that boosts scores based on the magnitude of a numeric field. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the magnitude scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.MagnitudeScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is + "magnitude". + :vartype type: str + """ + + parameters: "_models.MagnitudeScoringParameters" = rest_field( + name="magnitude", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the magnitude scoring function. Required.""" + type: Literal["magnitude"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"magnitude\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.MagnitudeScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "magnitude" # type: ignore + + +class MagnitudeScoringParameters(_Model): + """Provides parameter values to a magnitude scoring function. + + :ivar boosting_range_start: The field value at which boosting starts. Required. + :vartype boosting_range_start: float + :ivar boosting_range_end: The field value at which boosting ends. Required. + :vartype boosting_range_end: float + :ivar should_boost_beyond_range_by_constant: A value indicating whether to apply a constant + boost for field values beyond the range end value; default is false. + :vartype should_boost_beyond_range_by_constant: bool + """ + + boosting_range_start: float = rest_field( + name="boostingRangeStart", visibility=["read", "create", "update", "delete", "query"] + ) + """The field value at which boosting starts. Required.""" + boosting_range_end: float = rest_field( + name="boostingRangeEnd", visibility=["read", "create", "update", "delete", "query"] + ) + """The field value at which boosting ends. Required.""" + should_boost_beyond_range_by_constant: Optional[bool] = rest_field( + name="constantBoostBeyondRange", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to apply a constant boost for field values beyond the range end + value; default is false.""" + + @overload + def __init__( + self, + *, + boosting_range_start: float, + boosting_range_end: float, + should_boost_beyond_range_by_constant: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MappingCharFilter(CharFilter, discriminator="#Microsoft.Azure.Search.MappingCharFilter"): + """A character filter that applies mappings defined with the mappings option. Matching is greedy + (longest pattern matching at a given point wins). Replacement is allowed to be the empty + string. This character filter is implemented using Apache Lucene. + + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar mappings: A list of mappings of the following format: "a=>b" (all occurrences of the + character "a" will be replaced with character "b"). Required. + :vartype mappings: list[str] + :ivar odata_type: A URI fragment specifying the type of char filter. Required. Default value is + "#Microsoft.Azure.Search.MappingCharFilter". + :vartype odata_type: str + """ + + mappings: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of mappings of the following format: \"a=>b\" (all occurrences of the character \"a\" + will be replaced with character \"b\"). Required.""" + odata_type: Literal["#Microsoft.Azure.Search.MappingCharFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of char filter. Required. Default value is + \"#Microsoft.Azure.Search.MappingCharFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + mappings: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.MappingCharFilter" # type: ignore + + +class MergeSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.MergeSkill"): + """A skill for merging two or more strings into a single unified string, with an optional + user-defined delimiter separating each component part. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar insert_pre_tag: The tag indicates the start of the merged text. By default, the tag is an + empty space. + :vartype insert_pre_tag: str + :ivar insert_post_tag: The tag indicates the end of the merged text. By default, the tag is an + empty space. + :vartype insert_post_tag: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.MergeSkill". + :vartype odata_type: str + """ + + insert_pre_tag: Optional[str] = rest_field( + name="insertPreTag", visibility=["read", "create", "update", "delete", "query"] + ) + """The tag indicates the start of the merged text. By default, the tag is an empty space.""" + insert_post_tag: Optional[str] = rest_field( + name="insertPostTag", visibility=["read", "create", "update", "delete", "query"] + ) + """The tag indicates the end of the merged text. By default, the tag is an empty space.""" + odata_type: Literal["#Microsoft.Skills.Text.MergeSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.MergeSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + insert_pre_tag: Optional[str] = None, + insert_post_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.MergeSkill" # type: ignore + + +class MicrosoftLanguageStemmingTokenizer( + LexicalTokenizer, discriminator="#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer" +): + """Divides text using language-specific rules and reduces words to their base forms. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are + split. Maximum token length that can be used is 300 characters. Tokens longer than 300 + characters are first split into tokens of length 300 and then each of those tokens is split + based on the max token length set. Default is 255. + :vartype max_token_length: int + :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as + the search tokenizer, set to false if used as the indexing tokenizer. Default is false. + :vartype is_search_tokenizer: bool + :ivar language: The language to use. The default is English. Known values are: "arabic", + "bangla", "bulgarian", "catalan", "croatian", "czech", "danish", "dutch", "english", + "estonian", "finnish", "french", "german", "greek", "gujarati", "hebrew", "hindi", "hungarian", + "icelandic", "indonesian", "italian", "kannada", "latvian", "lithuanian", "malay", "malayalam", + "marathi", "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", + "romanian", "russian", "serbianCyrillic", "serbianLatin", "slovak", "slovenian", "spanish", + "swedish", "tamil", "telugu", "turkish", "ukrainian", and "urdu". + :vartype language: str or + ~azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Tokens longer than the maximum length are split. Maximum token length + that can be used is 300 characters. Tokens longer than 300 characters are first split into + tokens of length 300 and then each of those tokens is split based on the max token length set. + Default is 255.""" + is_search_tokenizer: Optional[bool] = rest_field( + name="isSearchTokenizer", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how the tokenizer is used. Set to true if used as the search tokenizer, set + to false if used as the indexing tokenizer. Default is false.""" + language: Optional[Union[str, "_models.MicrosoftStemmingTokenizerLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. The default is English. Known values are: \"arabic\", \"bangla\", + \"bulgarian\", \"catalan\", \"croatian\", \"czech\", \"danish\", \"dutch\", \"english\", + \"estonian\", \"finnish\", \"french\", \"german\", \"greek\", \"gujarati\", \"hebrew\", + \"hindi\", \"hungarian\", \"icelandic\", \"indonesian\", \"italian\", \"kannada\", \"latvian\", + \"lithuanian\", \"malay\", \"malayalam\", \"marathi\", \"norwegianBokmaal\", \"polish\", + \"portuguese\", \"portugueseBrazilian\", \"punjabi\", \"romanian\", \"russian\", + \"serbianCyrillic\", \"serbianLatin\", \"slovak\", \"slovenian\", \"spanish\", \"swedish\", + \"tamil\", \"telugu\", \"turkish\", \"ukrainian\", and \"urdu\".""" + odata_type: Literal["#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + is_search_tokenizer: Optional[bool] = None, + language: Optional[Union[str, "_models.MicrosoftStemmingTokenizerLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer" # type: ignore + + +class MicrosoftLanguageTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.MicrosoftLanguageTokenizer"): + """Divides text using language-specific rules. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are + split. Maximum token length that can be used is 300 characters. Tokens longer than 300 + characters are first split into tokens of length 300 and then each of those tokens is split + based on the max token length set. Default is 255. + :vartype max_token_length: int + :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as + the search tokenizer, set to false if used as the indexing tokenizer. Default is false. + :vartype is_search_tokenizer: bool + :ivar language: The language to use. The default is English. Known values are: "bangla", + "bulgarian", "catalan", "chineseSimplified", "chineseTraditional", "croatian", "czech", + "danish", "dutch", "english", "french", "german", "greek", "gujarati", "hindi", "icelandic", + "indonesian", "italian", "japanese", "kannada", "korean", "malay", "malayalam", "marathi", + "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", "romanian", + "russian", "serbianCyrillic", "serbianLatin", "slovenian", "spanish", "swedish", "tamil", + "telugu", "thai", "ukrainian", "urdu", and "vietnamese". + :vartype language: str or ~azure.search.documents.indexes.models.MicrosoftTokenizerLanguage + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Tokens longer than the maximum length are split. Maximum token length + that can be used is 300 characters. Tokens longer than 300 characters are first split into + tokens of length 300 and then each of those tokens is split based on the max token length set. + Default is 255.""" + is_search_tokenizer: Optional[bool] = rest_field( + name="isSearchTokenizer", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how the tokenizer is used. Set to true if used as the search tokenizer, set + to false if used as the indexing tokenizer. Default is false.""" + language: Optional[Union[str, "_models.MicrosoftTokenizerLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. The default is English. Known values are: \"bangla\", \"bulgarian\", + \"catalan\", \"chineseSimplified\", \"chineseTraditional\", \"croatian\", \"czech\", + \"danish\", \"dutch\", \"english\", \"french\", \"german\", \"greek\", \"gujarati\", \"hindi\", + \"icelandic\", \"indonesian\", \"italian\", \"japanese\", \"kannada\", \"korean\", \"malay\", + \"malayalam\", \"marathi\", \"norwegianBokmaal\", \"polish\", \"portuguese\", + \"portugueseBrazilian\", \"punjabi\", \"romanian\", \"russian\", \"serbianCyrillic\", + \"serbianLatin\", \"slovenian\", \"spanish\", \"swedish\", \"tamil\", \"telugu\", \"thai\", + \"ukrainian\", \"urdu\", and \"vietnamese\".""" + odata_type: Literal["#Microsoft.Azure.Search.MicrosoftLanguageTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.MicrosoftLanguageTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + is_search_tokenizer: Optional[bool] = None, + language: Optional[Union[str, "_models.MicrosoftTokenizerLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer" # type: ignore + + +class NativeBlobSoftDeleteDeletionDetectionPolicy( + DataDeletionDetectionPolicy, discriminator="#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" +): # pylint: disable=name-too-long + """Defines a data deletion detection policy utilizing Azure Blob Storage's native soft delete + feature for deletion detection. + + :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. + Required. Default value is + "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data deletion detection policy. Required. Default value + is \"#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" # type: ignore + + +class NGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.NGramTokenFilter"): + """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of + maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. + :vartype max_gram: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.NGramTokenFilter". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Must be less than the value of maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2.""" + odata_type: Literal["#Microsoft.Azure.Search.NGramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.NGramTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NGramTokenFilter" # type: ignore + + +class NGramTokenFilterV2(TokenFilter, discriminator="#Microsoft.Azure.Search.NGramTokenFilterV2"): + """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.NGramTokenFilterV2". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + odata_type: Literal["#Microsoft.Azure.Search.NGramTokenFilterV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.NGramTokenFilterV2\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NGramTokenFilterV2" # type: ignore + + +class NGramTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.NGramTokenizer"): + """Tokenizes the input into n-grams of the given size(s). This tokenizer is implemented using + Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar token_chars: Character classes to keep in the tokens. + :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.NGramTokenizer". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = rest_field( + name="tokenChars", visibility=["read", "create", "update", "delete", "query"] + ) + """Character classes to keep in the tokens.""" + odata_type: Literal["#Microsoft.Azure.Search.NGramTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.NGramTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NGramTokenizer" # type: ignore + + +class OcrSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Vision.OcrSkill"): + """A skill that extracts text from image files. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "af", "sq", "anp", "ar", "ast", "awa", "az", "bfy", "eu", "be", "be-cyrl", + "be-latn", "bho", "bi", "brx", "bs", "bra", "br", "bg", "bns", "bua", "ca", "ceb", "rab", "ch", + "hne", "zh-Hans", "zh-Hant", "kw", "co", "crh", "hr", "cs", "da", "prs", "dhi", "doi", "nl", + "en", "myv", "et", "fo", "fj", "fil", "fi", "fr", "fur", "gag", "gl", "de", "gil", "gon", "el", + "kl", "gvr", "ht", "hlb", "hni", "bgc", "haw", "hi", "mww", "hoc", "hu", "is", "smn", "id", + "ia", "iu", "ga", "it", "ja", "Jns", "jv", "kea", "kac", "xnr", "krc", "kaa-cyrl", "kaa", + "csb", "kk-cyrl", "kk-latn", "klr", "kha", "quc", "ko", "kfq", "kpy", "kos", "kum", "ku-arab", + "ku-latn", "kru", "ky", "lkt", "la", "lt", "dsb", "smj", "lb", "bfz", "ms", "mt", "kmj", "gv", + "mi", "mr", "mn", "cnr-cyrl", "cnr-latn", "nap", "ne", "niu", "nog", "sme", "nb", "no", "oc", + "os", "ps", "fa", "pl", "pt", "pa", "ksh", "ro", "rm", "ru", "sck", "sm", "sa", "sat", "sco", + "gd", "sr", "sr-Cyrl", "sr-Latn", "xsr", "srx", "sms", "sk", "sl", "so", "sma", "es", "sw", + "sv", "tg", "tt", "tet", "thf", "to", "tr", "tk", "tyv", "hsb", "ur", "ug", "uz-arab", + "uz-cyrl", "uz", "vo", "wae", "cy", "fy", "yua", "za", "zu", and "unk". + :vartype default_language_code: str or ~azure.search.documents.indexes.models.OcrSkillLanguage + :ivar should_detect_orientation: A value indicating to turn orientation detection on or not. + Default is false. + :vartype should_detect_orientation: bool + :ivar line_ending: Defines the sequence of characters to use between the lines of text + recognized by the OCR skill. The default value is "space". Known values are: "space", + "carriageReturn", "lineFeed", and "carriageReturnLineFeed". + :vartype line_ending: str or ~azure.search.documents.indexes.models.OcrLineEnding + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Vision.OcrSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.OcrSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"af\", + \"sq\", \"anp\", \"ar\", \"ast\", \"awa\", \"az\", \"bfy\", \"eu\", \"be\", \"be-cyrl\", + \"be-latn\", \"bho\", \"bi\", \"brx\", \"bs\", \"bra\", \"br\", \"bg\", \"bns\", \"bua\", + \"ca\", \"ceb\", \"rab\", \"ch\", \"hne\", \"zh-Hans\", \"zh-Hant\", \"kw\", \"co\", \"crh\", + \"hr\", \"cs\", \"da\", \"prs\", \"dhi\", \"doi\", \"nl\", \"en\", \"myv\", \"et\", \"fo\", + \"fj\", \"fil\", \"fi\", \"fr\", \"fur\", \"gag\", \"gl\", \"de\", \"gil\", \"gon\", \"el\", + \"kl\", \"gvr\", \"ht\", \"hlb\", \"hni\", \"bgc\", \"haw\", \"hi\", \"mww\", \"hoc\", \"hu\", + \"is\", \"smn\", \"id\", \"ia\", \"iu\", \"ga\", \"it\", \"ja\", \"Jns\", \"jv\", \"kea\", + \"kac\", \"xnr\", \"krc\", \"kaa-cyrl\", \"kaa\", \"csb\", \"kk-cyrl\", \"kk-latn\", \"klr\", + \"kha\", \"quc\", \"ko\", \"kfq\", \"kpy\", \"kos\", \"kum\", \"ku-arab\", \"ku-latn\", + \"kru\", \"ky\", \"lkt\", \"la\", \"lt\", \"dsb\", \"smj\", \"lb\", \"bfz\", \"ms\", \"mt\", + \"kmj\", \"gv\", \"mi\", \"mr\", \"mn\", \"cnr-cyrl\", \"cnr-latn\", \"nap\", \"ne\", \"niu\", + \"nog\", \"sme\", \"nb\", \"no\", \"oc\", \"os\", \"ps\", \"fa\", \"pl\", \"pt\", \"pa\", + \"ksh\", \"ro\", \"rm\", \"ru\", \"sck\", \"sm\", \"sa\", \"sat\", \"sco\", \"gd\", \"sr\", + \"sr-Cyrl\", \"sr-Latn\", \"xsr\", \"srx\", \"sms\", \"sk\", \"sl\", \"so\", \"sma\", \"es\", + \"sw\", \"sv\", \"tg\", \"tt\", \"tet\", \"thf\", \"to\", \"tr\", \"tk\", \"tyv\", \"hsb\", + \"ur\", \"ug\", \"uz-arab\", \"uz-cyrl\", \"uz\", \"vo\", \"wae\", \"cy\", \"fy\", \"yua\", + \"za\", \"zu\", and \"unk\".""" + should_detect_orientation: Optional[bool] = rest_field( + name="detectOrientation", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating to turn orientation detection on or not. Default is false.""" + line_ending: Optional[Union[str, "_models.OcrLineEnding"]] = rest_field( + name="lineEnding", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the sequence of characters to use between the lines of text recognized by the OCR + skill. The default value is \"space\". Known values are: \"space\", \"carriageReturn\", + \"lineFeed\", and \"carriageReturnLineFeed\".""" + odata_type: Literal["#Microsoft.Skills.Vision.OcrSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Vision.OcrSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.OcrSkillLanguage"]] = None, + should_detect_orientation: Optional[bool] = None, + line_ending: Optional[Union[str, "_models.OcrLineEnding"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Vision.OcrSkill" # type: ignore + + +class OutputFieldMappingEntry(_Model): + """Output field mapping for a skill. + + :ivar name: The name of the output defined by the skill. Required. + :vartype name: str + :ivar target_name: The target name of the output. It is optional and default to name. + :vartype target_name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the output defined by the skill. Required.""" + target_name: Optional[str] = rest_field( + name="targetName", visibility=["read", "create", "update", "delete", "query"] + ) + """The target name of the output. It is optional and default to name.""" + + @overload + def __init__( + self, + *, + name: str, + target_name: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PathHierarchyTokenizerV2(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.PathHierarchyTokenizerV2"): + """Tokenizer for path-like hierarchies. This tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar delimiter: The delimiter character to use. Default is "/". + :vartype delimiter: str + :ivar replacement: A value that, if set, replaces the delimiter character. Default is "/". + :vartype replacement: str + :ivar max_token_length: The maximum token length. Default and maximum is 300. + :vartype max_token_length: int + :ivar reverse_token_order: A value indicating whether to generate tokens in reverse order. + Default is false. + :vartype reverse_token_order: bool + :ivar number_of_tokens_to_skip: The number of initial tokens to skip. Default is 0. + :vartype number_of_tokens_to_skip: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.PathHierarchyTokenizerV2". + :vartype odata_type: str + """ + + delimiter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The delimiter character to use. Default is \"/\".""" + replacement: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value that, if set, replaces the delimiter character. Default is \"/\".""" + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default and maximum is 300.""" + reverse_token_order: Optional[bool] = rest_field( + name="reverse", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to generate tokens in reverse order. Default is false.""" + number_of_tokens_to_skip: Optional[int] = rest_field( + name="skip", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of initial tokens to skip. Default is 0.""" + odata_type: Literal["#Microsoft.Azure.Search.PathHierarchyTokenizerV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.PathHierarchyTokenizerV2\".""" + + @overload + def __init__( + self, + *, + name: str, + delimiter: Optional[str] = None, + replacement: Optional[str] = None, + max_token_length: Optional[int] = None, + reverse_token_order: Optional[bool] = None, + number_of_tokens_to_skip: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2" # type: ignore + + +class PatternAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.PatternAnalyzer"): + """Flexibly separates text into terms via a regular expression pattern. This analyzer is + implemented using Apache Lucene. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar lower_case_terms: A value indicating whether terms should be lower-cased. Default is + true. + :vartype lower_case_terms: bool + :ivar pattern: A regular expression pattern to match token separators. Default is an expression + that matches one or more non-word characters. + :vartype pattern: str + :ivar flags: Regular expression flags, specified as a '|' separated string of RegexFlags + values. + :vartype flags: list[str or ~azure.search.documents.indexes.models.RegexFlags] + :ivar stopwords: A list of stopwords. + :vartype stopwords: list[str] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.PatternAnalyzer". + :vartype odata_type: str + """ + + lower_case_terms: Optional[bool] = rest_field( + name="lowercase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether terms should be lower-cased. Default is true.""" + pattern: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern to match token separators. Default is an expression that matches + one or more non-word characters.""" + flags: Optional[list[Union[str, "_models.RegexFlags"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="pipeDelimited" + ) + """Regular expression flags, specified as a '|' separated string of RegexFlags values.""" + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stopwords.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.PatternAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + lower_case_terms: Optional[bool] = None, + pattern: Optional[str] = None, + flags: Optional[list[Union[str, "_models.RegexFlags"]]] = None, + stopwords: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternAnalyzer" # type: ignore + + +class PatternCaptureTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.PatternCaptureTokenFilter"): + """Uses Java regexes to emit multiple tokens - one for each capture group in one or more patterns. + This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar patterns: A list of patterns to match against each token. Required. + :vartype patterns: list[str] + :ivar preserve_original: A value indicating whether to return the original token even if one of + the patterns matches. Default is true. + :vartype preserve_original: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.PatternCaptureTokenFilter". + :vartype odata_type: str + """ + + patterns: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of patterns to match against each token. Required.""" + preserve_original: Optional[bool] = rest_field( + name="preserveOriginal", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to return the original token even if one of the patterns matches. + Default is true.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternCaptureTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.PatternCaptureTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + patterns: list[str], + preserve_original: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternCaptureTokenFilter" # type: ignore + + +class PatternReplaceCharFilter(CharFilter, discriminator="#Microsoft.Azure.Search.PatternReplaceCharFilter"): + """A character filter that replaces characters in the input string. It uses a regular expression + to identify character sequences to preserve and a replacement pattern to identify characters to + replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\\\s+(bb)", and + replacement "$1#$2", the result would be "aa#bb aa#bb". This character filter is implemented + using Apache Lucene. + + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar pattern: A regular expression pattern. Required. + :vartype pattern: str + :ivar replacement: The replacement text. Required. + :vartype replacement: str + :ivar odata_type: A URI fragment specifying the type of char filter. Required. Default value is + "#Microsoft.Azure.Search.PatternReplaceCharFilter". + :vartype odata_type: str + """ + + pattern: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern. Required.""" + replacement: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The replacement text. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternReplaceCharFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of char filter. Required. Default value is + \"#Microsoft.Azure.Search.PatternReplaceCharFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + pattern: str, + replacement: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternReplaceCharFilter" # type: ignore + + +class PatternReplaceTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.PatternReplaceTokenFilter"): + """A character filter that replaces characters in the input string. It uses a regular expression + to identify character sequences to preserve and a replacement pattern to identify characters to + replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\\\s+(bb)", and + replacement "$1#$2", the result would be "aa#bb aa#bb". This token filter is implemented using + Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar pattern: A regular expression pattern. Required. + :vartype pattern: str + :ivar replacement: The replacement text. Required. + :vartype replacement: str + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.PatternReplaceTokenFilter". + :vartype odata_type: str + """ + + pattern: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern. Required.""" + replacement: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The replacement text. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternReplaceTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.PatternReplaceTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + pattern: str, + replacement: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternReplaceTokenFilter" # type: ignore + + +class PatternTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.PatternTokenizer"): + """Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is + implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar pattern: A regular expression pattern to match token separators. Default is an expression + that matches one or more non-word characters. + :vartype pattern: str + :ivar flags: Regular expression flags, specified as a '|' separated string of RegexFlags + values. + :vartype flags: list[str or ~azure.search.documents.indexes.models.RegexFlags] + :ivar group: The zero-based ordinal of the matching group in the regular expression pattern to + extract into tokens. Use -1 if you want to use the entire pattern to split the input into + tokens, irrespective of matching groups. Default is -1. + :vartype group: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.PatternTokenizer". + :vartype odata_type: str + """ + + pattern: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern to match token separators. Default is an expression that matches + one or more non-word characters.""" + flags: Optional[list[Union[str, "_models.RegexFlags"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="pipeDelimited" + ) + """Regular expression flags, specified as a '|' separated string of RegexFlags values.""" + group: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The zero-based ordinal of the matching group in the regular expression pattern to extract into + tokens. Use -1 if you want to use the entire pattern to split the input into tokens, + irrespective of matching groups. Default is -1.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.PatternTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + pattern: Optional[str] = None, + flags: Optional[list[Union[str, "_models.RegexFlags"]]] = None, + group: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternTokenizer" # type: ignore + + +class PhoneticTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.PhoneticTokenFilter"): + """Create tokens for phonetic matches. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar encoder: The phonetic encoder to use. Default is "metaphone". Known values are: + "metaphone", "doubleMetaphone", "soundex", "refinedSoundex", "caverphone1", "caverphone2", + "cologne", "nysiis", "koelnerPhonetik", "haasePhonetik", and "beiderMorse". + :vartype encoder: str or ~azure.search.documents.indexes.models.PhoneticEncoder + :ivar replace_original_tokens: A value indicating whether encoded tokens should replace + original tokens. If false, encoded tokens are added as synonyms. Default is true. + :vartype replace_original_tokens: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.PhoneticTokenFilter". + :vartype odata_type: str + """ + + encoder: Optional[Union[str, "_models.PhoneticEncoder"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The phonetic encoder to use. Default is \"metaphone\". Known values are: \"metaphone\", + \"doubleMetaphone\", \"soundex\", \"refinedSoundex\", \"caverphone1\", \"caverphone2\", + \"cologne\", \"nysiis\", \"koelnerPhonetik\", \"haasePhonetik\", and \"beiderMorse\".""" + replace_original_tokens: Optional[bool] = rest_field( + name="replace", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether encoded tokens should replace original tokens. If false, encoded + tokens are added as synonyms. Default is true.""" + odata_type: Literal["#Microsoft.Azure.Search.PhoneticTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.PhoneticTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + encoder: Optional[Union[str, "_models.PhoneticEncoder"]] = None, + replace_original_tokens: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PhoneticTokenFilter" # type: ignore + + +class PIIDetectionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.PIIDetectionSkill"): + """Using the Text Analytics API, extracts personal information from an input text and gives you + the option of masking it. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar masking_mode: A parameter that provides various ways to mask the personal information + detected in the input text. Default is 'none'. Known values are: "none" and "replace". + :vartype masking_mode: str or + ~azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode + :ivar mask: The character used to mask the text if the maskingMode parameter is set to replace. + Default is '*'. + :vartype mask: str + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar pii_categories: A list of PII entity categories that should be extracted and masked. + :vartype pii_categories: list[str] + :ivar domain: If specified, will set the PII domain to include only a subset of the entity + categories. Possible values include: 'phi', 'none'. Default is 'none'. + :vartype domain: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.PIIDetectionSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + masking_mode: Optional[Union[str, "_models.PIIDetectionSkillMaskingMode"]] = rest_field( + name="maskingMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A parameter that provides various ways to mask the personal information detected in the input + text. Default is 'none'. Known values are: \"none\" and \"replace\".""" + mask: Optional[str] = rest_field( + name="maskingCharacter", visibility=["read", "create", "update", "delete", "query"] + ) + """The character used to mask the text if the maskingMode parameter is set to replace. Default is + '*'.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + pii_categories: Optional[list[str]] = rest_field( + name="piiCategories", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of PII entity categories that should be extracted and masked.""" + domain: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """If specified, will set the PII domain to include only a subset of the entity categories. + Possible values include: 'phi', 'none'. Default is 'none'.""" + odata_type: Literal["#Microsoft.Skills.Text.PIIDetectionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.PIIDetectionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[str] = None, + minimum_precision: Optional[float] = None, + masking_mode: Optional[Union[str, "_models.PIIDetectionSkillMaskingMode"]] = None, + mask: Optional[str] = None, + model_version: Optional[str] = None, + pii_categories: Optional[list[str]] = None, + domain: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.PIIDetectionSkill" # type: ignore + + +class RemoteSharePointKnowledgeSource(KnowledgeSource, discriminator="remoteSharePoint"): + """Configuration for remote SharePoint knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the knowledge source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that reads data from remote SharePoint. + :vartype kind: str or ~azure.search.documents.indexes.models.REMOTE_SHARE_POINT + :ivar remote_share_point_parameters: The parameters for the remote SharePoint knowledge source. + :vartype remote_share_point_parameters: + ~azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters + """ + + kind: Literal[KnowledgeSourceKind.REMOTE_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that reads data from remote SharePoint.""" + remote_share_point_parameters: Optional["_models.RemoteSharePointKnowledgeSourceParameters"] = rest_field( + name="remoteSharePointParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The parameters for the remote SharePoint knowledge source.""" + + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + remote_share_point_parameters: Optional["_models.RemoteSharePointKnowledgeSourceParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.REMOTE_SHARE_POINT # type: ignore + + +class RemoteSharePointKnowledgeSourceParameters(_Model): # pylint: disable=name-too-long + """Parameters for remote SharePoint knowledge source. + + :ivar filter_expression: Keyword Query Language (KQL) expression with queryable SharePoint + properties and attributes to scope the retrieval before the query runs. + :vartype filter_expression: str + :ivar resource_metadata: A list of metadata fields to be returned for each item in the + response. Only retrievable metadata properties can be included in this list. By default, no + metadata is returned. + :vartype resource_metadata: list[str] + :ivar container_type_id: Container ID for SharePoint Embedded connection. When this is null, it + will use SharePoint Online. + :vartype container_type_id: str + """ + + filter_expression: Optional[str] = rest_field( + name="filterExpression", visibility=["read", "create", "update", "delete", "query"] + ) + """Keyword Query Language (KQL) expression with queryable SharePoint properties and attributes to + scope the retrieval before the query runs.""" + resource_metadata: Optional[list[str]] = rest_field( + name="resourceMetadata", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of metadata fields to be returned for each item in the response. Only retrievable + metadata properties can be included in this list. By default, no metadata is returned.""" + container_type_id: Optional[str] = rest_field( + name="containerTypeId", visibility=["read", "create", "update", "delete", "query"] + ) + """Container ID for SharePoint Embedded connection. When this is null, it will use SharePoint + Online.""" + + @overload + def __init__( + self, + *, + filter_expression: Optional[str] = None, + resource_metadata: Optional[list[str]] = None, + container_type_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RescoringOptions(_Model): + """Contains the options for rescoring. + + :ivar enable_rescoring: If set to true, after the initial search on the compressed vectors, the + similarity scores are recalculated using the full-precision vectors. This will improve recall + at the expense of latency. + :vartype enable_rescoring: bool + :ivar default_oversampling: Default oversampling factor. Oversampling retrieves a greater set + of potential documents to offset the resolution loss due to quantization. This increases the + set of results that will be rescored on full-precision vectors. Minimum value is 1, meaning no + oversampling (1x). This parameter can only be set when 'enableRescoring' is true. Higher values + improve recall at the expense of latency. + :vartype default_oversampling: float + :ivar rescore_storage_method: Controls the storage method for original vectors. This setting is + immutable. Known values are: "preserveOriginals" and "discardOriginals". + :vartype rescore_storage_method: str or + ~azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod + """ + + enable_rescoring: Optional[bool] = rest_field( + name="enableRescoring", visibility=["read", "create", "update", "delete", "query"] + ) + """If set to true, after the initial search on the compressed vectors, the similarity scores are + recalculated using the full-precision vectors. This will improve recall at the expense of + latency.""" + default_oversampling: Optional[float] = rest_field( + name="defaultOversampling", visibility=["read", "create", "update", "delete", "query"] + ) + """Default oversampling factor. Oversampling retrieves a greater set of potential documents to + offset the resolution loss due to quantization. This increases the set of results that will be + rescored on full-precision vectors. Minimum value is 1, meaning no oversampling (1x). This + parameter can only be set when 'enableRescoring' is true. Higher values improve recall at the + expense of latency.""" + rescore_storage_method: Optional[Union[str, "_models.VectorSearchCompressionRescoreStorageMethod"]] = rest_field( + name="rescoreStorageMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the storage method for original vectors. This setting is immutable. Known values are: + \"preserveOriginals\" and \"discardOriginals\".""" + + @overload + def __init__( + self, + *, + enable_rescoring: Optional[bool] = None, + default_oversampling: Optional[float] = None, + rescore_storage_method: Optional[Union[str, "_models.VectorSearchCompressionRescoreStorageMethod"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ResourceCounter(_Model): + """Represents a resource's usage and quota. + + :ivar usage: The resource usage amount. Required. + :vartype usage: int + :ivar quota: The resource amount quota. + :vartype quota: int + """ + + usage: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The resource usage amount. Required.""" + quota: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The resource amount quota.""" + + @overload + def __init__( + self, + *, + usage: int, + quota: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ScalarQuantizationCompression(VectorSearchCompression, discriminator="scalarQuantization"): + """Contains configuration options specific to the scalar quantization compression method used + during indexing and querying. + + :ivar compression_name: The name to associate with this particular configuration. Required. + :vartype compression_name: str + :ivar rescoring_options: Contains the options for rescoring. + :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions + :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the + vectors reduces the size of the vectors and the amount of data that needs to be transferred + during search. This can save storage cost and improve search performance at the expense of + recall. It should be only used for embeddings trained with Matryoshka Representation Learning + (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no + truncation. + :vartype truncation_dimension: int + :ivar parameters: Contains the parameters specific to Scalar Quantization. + :vartype parameters: ~azure.search.documents.indexes.models.ScalarQuantizationParameters + :ivar kind: The name of the kind of compression method being configured for use with vector + search. Required. Scalar Quantization, a type of compression method. In scalar quantization, + the original vectors values are compressed to a narrower type by discretizing and representing + each component of a vector using a reduced set of quantized values, thereby reducing the + overall data size. + :vartype kind: str or ~azure.search.documents.indexes.models.SCALAR_QUANTIZATION + """ + + parameters: Optional["_models.ScalarQuantizationParameters"] = rest_field( + name="scalarQuantizationParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to Scalar Quantization.""" + kind: Literal[VectorSearchCompressionKind.SCALAR_QUANTIZATION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of compression method being configured for use with vector search. + Required. Scalar Quantization, a type of compression method. In scalar quantization, the + original vectors values are compressed to a narrower type by discretizing and representing each + component of a vector using a reduced set of quantized values, thereby reducing the overall + data size.""" + + @overload + def __init__( + self, + *, + compression_name: str, + rescoring_options: Optional["_models.RescoringOptions"] = None, + truncation_dimension: Optional[int] = None, + parameters: Optional["_models.ScalarQuantizationParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchCompressionKind.SCALAR_QUANTIZATION # type: ignore + + +class ScalarQuantizationParameters(_Model): + """Contains the parameters specific to Scalar Quantization. + + :ivar quantized_data_type: The quantized data type of compressed vector values. "int8" + :vartype quantized_data_type: str or + ~azure.search.documents.indexes.models.VectorSearchCompressionTarget + """ + + quantized_data_type: Optional[Union[str, "_models.VectorSearchCompressionTarget"]] = rest_field( + name="quantizedDataType", visibility=["read", "create", "update", "delete", "query"] + ) + """The quantized data type of compressed vector values. \"int8\"""" + + @overload + def __init__( + self, + *, + quantized_data_type: Optional[Union[str, "_models.VectorSearchCompressionTarget"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ScoringProfile(_Model): + """Defines parameters for a search index that influence scoring in search queries. + + :ivar name: The name of the scoring profile. Required. + :vartype name: str + :ivar text_weights: Parameters that boost scoring based on text matches in certain index + fields. + :vartype text_weights: ~azure.search.documents.indexes.models.TextWeights + :ivar functions: The collection of functions that influence the scoring of documents. + :vartype functions: list[~azure.search.documents.indexes.models.ScoringFunction] + :ivar function_aggregation: A value indicating how the results of individual scoring functions + should be combined. Defaults to "Sum". Ignored if there are no scoring functions. Known values + are: "sum", "average", "minimum", "maximum", "firstMatching", and "product". + :vartype function_aggregation: str or + ~azure.search.documents.indexes.models.ScoringFunctionAggregation + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the scoring profile. Required.""" + text_weights: Optional["_models.TextWeights"] = rest_field( + name="text", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameters that boost scoring based on text matches in certain index fields.""" + functions: Optional[list["_models.ScoringFunction"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The collection of functions that influence the scoring of documents.""" + function_aggregation: Optional[Union[str, "_models.ScoringFunctionAggregation"]] = rest_field( + name="functionAggregation", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how the results of individual scoring functions should be combined. Defaults + to \"Sum\". Ignored if there are no scoring functions. Known values are: \"sum\", \"average\", + \"minimum\", \"maximum\", \"firstMatching\", and \"product\".""" + + @overload + def __init__( + self, + *, + name: str, + text_weights: Optional["_models.TextWeights"] = None, + functions: Optional[list["_models.ScoringFunction"]] = None, + function_aggregation: Optional[Union[str, "_models.ScoringFunctionAggregation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchAlias(_Model): + """Represents an index alias, which describes a mapping from the alias name to an index. The alias + name can be used in place of the index name for supported operations. + + :ivar name: The name of the alias. Required. + :vartype name: str + :ivar indexes: The name of the index this alias maps to. Only one index name may be specified. + Required. + :vartype indexes: list[str] + :ivar e_tag: The ETag of the alias. + :vartype e_tag: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the alias. Required.""" + indexes: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the index this alias maps to. Only one index name may be specified. Required.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the alias.""" + + @overload + def __init__( + self, + *, + name: str, + indexes: list[str], + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchField(_Model): + """Represents a field in an index definition, which describes the name, data type, and search + behavior of a field. + + :ivar name: The name of the field, which must be unique within the fields collection of the + index or parent field. Required. + :vartype name: str + :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", + "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", + "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". + :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType + :ivar key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type Edm.String. Key fields can be used to look up documents directly and update or delete + specific documents. Default is false for simple fields and null for complex fields. + :vartype key: bool + :ivar retrievable: A value indicating whether the field can be returned in a search result. You + can disable this option if you want to use a field (for example, margin) as a filter, sorting, + or scoring mechanism but do not want the field to be visible to the end user. This property + must be true for key fields, and it must be null for complex fields. This property can be + changed on existing fields. Enabling this property does not cause any increase in index storage + requirements. Default is true for simple fields, false for vector fields, and null for complex + fields. + :vartype retrievable: bool + :ivar stored: An immutable value indicating whether the field will be persisted separately on + disk to be returned in a search result. You can disable this option if you don't plan to return + the field contents in a search response to save on storage overhead. This can only be set + during index creation and only for vector fields. This property cannot be changed for existing + fields or set as false for new fields. If this property is set as false, the property + 'retrievable' must also be set to false. This property must be true or unset for key fields, + for new fields, and for non-vector fields, and it must be null for complex fields. Disabling + this property will reduce index storage requirements. The default is true for vector fields. + :vartype stored: bool + :ivar searchable: A value indicating whether the field is full-text searchable. This means it + will undergo analysis such as word-breaking during indexing. If you set a searchable field to a + value like "sunny day", internally it will be split into the individual tokens "sunny" and + "day". This enables full-text searches for these terms. Fields of type Edm.String or + Collection(Edm.String) are searchable by default. This property must be false for simple fields + of other non-string data types, and it must be null for complex fields. Note: searchable fields + consume extra space in your index to accommodate additional tokenized versions of the field + value for full-text searches. If you want to save space in your index and you don't need a + field to be included in searches, set searchable to false. + :vartype searchable: bool + :ivar filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields of type + Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so + comparisons are for exact matches only. For example, if you set such a field f to "sunny day", + $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property + must be null for complex fields. Default is true for simple fields and null for complex fields. + :vartype filterable: bool + :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default, the search engine sorts results by score, but in many experiences + users will want to sort by fields in the documents. A simple field can be sortable only if it + is single-valued (it has a single value in the scope of the parent document). Simple collection + fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex + collections are also multi-valued, and therefore cannot be sortable. This is true whether it's + an immediate parent field, or an ancestor field, that's the complex collection. Complex fields + cannot be sortable and the sortable property must be null for such fields. The default for + sortable is true for single-valued simple fields, false for multi-valued simple fields, and + null for complex fields. + :vartype sortable: bool + :ivar facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or + Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple + fields. + :vartype facetable: bool + :ivar permission_filter: A value indicating whether the field should be used as a permission + filter. Known values are: "userIds", "groupIds", and "rbacScope". + :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter + :ivar sensitivity_label: A value indicating whether the field contains sensitivity label + information. + :vartype sensitivity_label: bool + :ivar analyzer_name: The name of the analyzer to use for the field. This option can be used + only with searchable fields and it can't be set together with either searchAnalyzer or + indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null + for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", + "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar search_analyzer_name: The name of the analyzer used at search time for the field. This + option can be used only with searchable fields. It must be set together with indexAnalyzer and + it cannot be set together with the analyzer option. This property cannot be set to the name of + a language analyzer; use the analyzer property instead if you need a language analyzer. This + analyzer can be updated on an existing field. Must be null for complex fields. Known values + are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", + "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", + "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", + "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", + "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", + "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", + "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", + "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", + "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", + "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", + "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype search_analyzer_name: str or + ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar index_analyzer_name: The name of the analyzer used at indexing time for the field. This + option can be used only with searchable fields. It must be set together with searchAnalyzer and + it cannot be set together with the analyzer option. This property cannot be set to the name of + a language analyzer; use the analyzer property instead if you need a language analyzer. Once + the analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. + Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", + "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar normalizer_name: The name of the normalizer to use for the field. This option can be used + only with fields with filterable, sortable, or facetable enabled. Once the normalizer is + chosen, it cannot be changed for the field. Must be null for complex fields. Known values are: + "asciifolding", "elision", "lowercase", "standard", and "uppercase". + :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :ivar vector_search_dimensions: The dimensionality of the vector field. + :vartype vector_search_dimensions: int + :ivar vector_search_profile_name: The name of the vector search profile that specifies the + algorithm and vectorizer to use when searching the vector field. + :vartype vector_search_profile_name: str + :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" + :vartype vector_encoding_format: str or + ~azure.search.documents.indexes.models.VectorEncodingFormat + :ivar synonym_map_names: A list of the names of synonym maps to associate with this field. This + option can be used only with searchable fields. Currently only one synonym map per field is + supported. Assigning a synonym map to a field ensures that query terms targeting that field are + expanded at query-time using the rules in the synonym map. This attribute can be changed on + existing fields. Must be null or an empty collection for complex fields. + :vartype synonym_map_names: list[str] + :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or + Collection(Edm.ComplexType). Must be null or empty for simple fields. + :vartype fields: list[~azure.search.documents.indexes.models.SearchField] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the field, which must be unique within the fields collection of the index or parent + field. Required.""" + type: Union[str, "_models.SearchFieldDataType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The data type of the field. Required. Known values are: \"Edm.String\", \"Edm.Int32\", + \"Edm.Int64\", \"Edm.Double\", \"Edm.Boolean\", \"Edm.DateTimeOffset\", \"Edm.GeographyPoint\", + \"Edm.ComplexType\", \"Edm.Single\", \"Edm.Half\", \"Edm.Int16\", \"Edm.SByte\", and + \"Edm.Byte\".""" + key: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the field uniquely identifies documents in the index. Exactly one + top-level field in each index must be chosen as the key field and it must be of type + Edm.String. Key fields can be used to look up documents directly and update or delete specific + documents. Default is false for simple fields and null for complex fields.""" + retrievable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the field can be returned in a search result. You can disable this + option if you want to use a field (for example, margin) as a filter, sorting, or scoring + mechanism but do not want the field to be visible to the end user. This property must be true + for key fields, and it must be null for complex fields. This property can be changed on + existing fields. Enabling this property does not cause any increase in index storage + requirements. Default is true for simple fields, false for vector fields, and null for complex + fields.""" + stored: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An immutable value indicating whether the field will be persisted separately on disk to be + returned in a search result. You can disable this option if you don't plan to return the field + contents in a search response to save on storage overhead. This can only be set during index + creation and only for vector fields. This property cannot be changed for existing fields or set + as false for new fields. If this property is set as false, the property 'retrievable' must also + be set to false. This property must be true or unset for key fields, for new fields, and for + non-vector fields, and it must be null for complex fields. Disabling this property will reduce + index storage requirements. The default is true for vector fields.""" + searchable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the field is full-text searchable. This means it will undergo + analysis such as word-breaking during indexing. If you set a searchable field to a value like + \"sunny day\", internally it will be split into the individual tokens \"sunny\" and \"day\". + This enables full-text searches for these terms. Fields of type Edm.String or + Collection(Edm.String) are searchable by default. This property must be false for simple fields + of other non-string data types, and it must be null for complex fields. Note: searchable fields + consume extra space in your index to accommodate additional tokenized versions of the field + value for full-text searches. If you want to save space in your index and you don't need a + field to be included in searches, set searchable to false.""" + filterable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether to enable the field to be referenced in $filter queries. filterable + differs from searchable in how strings are handled. Fields of type Edm.String or + Collection(Edm.String) that are filterable do not undergo word-breaking, so comparisons are for + exact matches only. For example, if you set such a field f to \"sunny day\", $filter=f eq + 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property must be null for + complex fields. Default is true for simple fields and null for complex fields.""" + sortable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether to enable the field to be referenced in $orderby expressions. By + default, the search engine sorts results by score, but in many experiences users will want to + sort by fields in the documents. A simple field can be sortable only if it is single-valued (it + has a single value in the scope of the parent document). Simple collection fields cannot be + sortable, since they are multi-valued. Simple sub-fields of complex collections are also + multi-valued, and therefore cannot be sortable. This is true whether it's an immediate parent + field, or an ancestor field, that's the complex collection. Complex fields cannot be sortable + and the sortable property must be null for such fields. The default for sortable is true for + single-valued simple fields, false for multi-valued simple fields, and null for complex fields.""" + facetable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether to enable the field to be referenced in facet queries. Typically + used in a presentation of search results that includes hit count by category (for example, + search for digital cameras and see hits by brand, by megapixels, by price, and so on). This + property must be null for complex fields. Fields of type Edm.GeographyPoint or + Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple + fields.""" + permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = rest_field( + name="permissionFilter", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the field should be used as a permission filter. Known values are: + \"userIds\", \"groupIds\", and \"rbacScope\".""" + sensitivity_label: Optional[bool] = rest_field( + name="sensitivityLabel", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the field contains sensitivity label information.""" + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="analyzer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer to use for the field. This option can be used only with searchable + fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once the + analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known + values are: \"ar.microsoft\", \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", \"eu.lucene\", + \"bg.microsoft\", \"bg.lucene\", \"ca.microsoft\", \"ca.lucene\", \"zh-Hans.microsoft\", + \"zh-Hans.lucene\", \"zh-Hant.microsoft\", \"zh-Hant.lucene\", \"hr.microsoft\", + \"cs.microsoft\", \"cs.lucene\", \"da.microsoft\", \"da.lucene\", \"nl.microsoft\", + \"nl.lucene\", \"en.microsoft\", \"en.lucene\", \"et.microsoft\", \"fi.microsoft\", + \"fi.lucene\", \"fr.microsoft\", \"fr.lucene\", \"gl.lucene\", \"de.microsoft\", \"de.lucene\", + \"el.microsoft\", \"el.lucene\", \"gu.microsoft\", \"he.microsoft\", \"hi.microsoft\", + \"hi.lucene\", \"hu.microsoft\", \"hu.lucene\", \"is.microsoft\", \"id.microsoft\", + \"id.lucene\", \"ga.lucene\", \"it.microsoft\", \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", + \"kn.microsoft\", \"ko.microsoft\", \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", + \"lt.microsoft\", \"ml.microsoft\", \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", + \"no.lucene\", \"fa.lucene\", \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", + \"pt-BR.lucene\", \"pt-PT.microsoft\", \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", + \"ro.lucene\", \"ru.microsoft\", \"ru.lucene\", \"sr-cyrillic.microsoft\", + \"sr-latin.microsoft\", \"sk.microsoft\", \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", + \"sv.microsoft\", \"sv.lucene\", \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", + \"th.lucene\", \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", + \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", + \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" + search_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="searchAnalyzer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer used at search time for the field. This option can be used only with + searchable fields. It must be set together with indexAnalyzer and it cannot be set together + with the analyzer option. This property cannot be set to the name of a language analyzer; use + the analyzer property instead if you need a language analyzer. This analyzer can be updated on + an existing field. Must be null for complex fields. Known values are: \"ar.microsoft\", + \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", \"eu.lucene\", \"bg.microsoft\", \"bg.lucene\", + \"ca.microsoft\", \"ca.lucene\", \"zh-Hans.microsoft\", \"zh-Hans.lucene\", + \"zh-Hant.microsoft\", \"zh-Hant.lucene\", \"hr.microsoft\", \"cs.microsoft\", \"cs.lucene\", + \"da.microsoft\", \"da.lucene\", \"nl.microsoft\", \"nl.lucene\", \"en.microsoft\", + \"en.lucene\", \"et.microsoft\", \"fi.microsoft\", \"fi.lucene\", \"fr.microsoft\", + \"fr.lucene\", \"gl.lucene\", \"de.microsoft\", \"de.lucene\", \"el.microsoft\", \"el.lucene\", + \"gu.microsoft\", \"he.microsoft\", \"hi.microsoft\", \"hi.lucene\", \"hu.microsoft\", + \"hu.lucene\", \"is.microsoft\", \"id.microsoft\", \"id.lucene\", \"ga.lucene\", + \"it.microsoft\", \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", \"kn.microsoft\", + \"ko.microsoft\", \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", \"lt.microsoft\", + \"ml.microsoft\", \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", \"no.lucene\", + \"fa.lucene\", \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", \"pt-BR.lucene\", + \"pt-PT.microsoft\", \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", \"ro.lucene\", + \"ru.microsoft\", \"ru.lucene\", \"sr-cyrillic.microsoft\", \"sr-latin.microsoft\", + \"sk.microsoft\", \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", \"sv.microsoft\", + \"sv.lucene\", \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", \"th.lucene\", + \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", + \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", + \"stop\", and \"whitespace\".""" + index_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="indexAnalyzer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer used at indexing time for the field. This option can be used only with + searchable fields. It must be set together with searchAnalyzer and it cannot be set together + with the analyzer option. This property cannot be set to the name of a language analyzer; use + the analyzer property instead if you need a language analyzer. Once the analyzer is chosen, it + cannot be changed for the field. Must be null for complex fields. Known values are: + \"ar.microsoft\", \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", \"eu.lucene\", + \"bg.microsoft\", \"bg.lucene\", \"ca.microsoft\", \"ca.lucene\", \"zh-Hans.microsoft\", + \"zh-Hans.lucene\", \"zh-Hant.microsoft\", \"zh-Hant.lucene\", \"hr.microsoft\", + \"cs.microsoft\", \"cs.lucene\", \"da.microsoft\", \"da.lucene\", \"nl.microsoft\", + \"nl.lucene\", \"en.microsoft\", \"en.lucene\", \"et.microsoft\", \"fi.microsoft\", + \"fi.lucene\", \"fr.microsoft\", \"fr.lucene\", \"gl.lucene\", \"de.microsoft\", \"de.lucene\", + \"el.microsoft\", \"el.lucene\", \"gu.microsoft\", \"he.microsoft\", \"hi.microsoft\", + \"hi.lucene\", \"hu.microsoft\", \"hu.lucene\", \"is.microsoft\", \"id.microsoft\", + \"id.lucene\", \"ga.lucene\", \"it.microsoft\", \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", + \"kn.microsoft\", \"ko.microsoft\", \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", + \"lt.microsoft\", \"ml.microsoft\", \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", + \"no.lucene\", \"fa.lucene\", \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", + \"pt-BR.lucene\", \"pt-PT.microsoft\", \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", + \"ro.lucene\", \"ru.microsoft\", \"ru.lucene\", \"sr-cyrillic.microsoft\", + \"sr-latin.microsoft\", \"sk.microsoft\", \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", + \"sv.microsoft\", \"sv.lucene\", \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", + \"th.lucene\", \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", + \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", + \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( + name="normalizer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the normalizer to use for the field. This option can be used only with fields with + filterable, sortable, or facetable enabled. Once the normalizer is chosen, it cannot be changed + for the field. Must be null for complex fields. Known values are: \"asciifolding\", + \"elision\", \"lowercase\", \"standard\", and \"uppercase\".""" + vector_search_dimensions: Optional[int] = rest_field( + name="dimensions", visibility=["read", "create", "update", "delete", "query"] + ) + """The dimensionality of the vector field.""" + vector_search_profile_name: Optional[str] = rest_field( + name="vectorSearchProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the vector search profile that specifies the algorithm and vectorizer to use when + searching the vector field.""" + vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = rest_field( + name="vectorEncoding", visibility=["read", "create", "update", "delete", "query"] + ) + """The encoding format to interpret the field contents. \"packedBit\"""" + synonym_map_names: Optional[list[str]] = rest_field( + name="synonymMaps", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of the names of synonym maps to associate with this field. This option can be used only + with searchable fields. Currently only one synonym map per field is supported. Assigning a + synonym map to a field ensures that query terms targeting that field are expanded at query-time + using the rules in the synonym map. This attribute can be changed on existing fields. Must be + null or an empty collection for complex fields.""" + fields: Optional[list["_models.SearchField"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of sub-fields if this is a field of type Edm.ComplexType or Collection(Edm.ComplexType). + Must be null or empty for simple fields.""" + + @overload + def __init__( + self, + *, + name: str, + type: Union[str, "_models.SearchFieldDataType"], + key: Optional[bool] = None, + retrievable: Optional[bool] = None, + stored: Optional[bool] = None, + searchable: Optional[bool] = None, + filterable: Optional[bool] = None, + sortable: Optional[bool] = None, + facetable: Optional[bool] = None, + permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = None, + sensitivity_label: Optional[bool] = None, + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + search_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + index_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, + vector_search_dimensions: Optional[int] = None, + vector_search_profile_name: Optional[str] = None, + vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = None, + synonym_map_names: Optional[list[str]] = None, + fields: Optional[list["_models.SearchField"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndex(_Model): + """Represents a search index definition, which describes the fields and search behavior of an + index. + + :ivar name: The name of the index. Required. + :vartype name: str + :ivar description: The description of the index. + :vartype description: str + :ivar fields: The fields of the index. Required. + :vartype fields: list[~azure.search.documents.indexes.models.SearchField] + :ivar scoring_profiles: The scoring profiles for the index. + :vartype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] + :ivar default_scoring_profile: The name of the scoring profile to use if none is specified in + the query. If this property is not set and no scoring profile is specified in the query, then + default scoring (tf-idf) will be used. + :vartype default_scoring_profile: str + :ivar cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. + :vartype cors_options: ~azure.search.documents.indexes.models.CorsOptions + :ivar suggesters: The suggesters for the index. + :vartype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] + :ivar analyzers: The analyzers for the index. + :vartype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] + :ivar tokenizers: The tokenizers for the index. + :vartype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] + :ivar token_filters: The token filters for the index. + :vartype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] + :ivar char_filters: The character filters for the index. + :vartype char_filters: list[~azure.search.documents.indexes.models.CharFilter] + :ivar normalizers: The normalizers for the index. + :vartype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your data when you + want full assurance that no one, not even Microsoft, can decrypt your data. Once you have + encrypted your data, it will always remain encrypted. The search service will ignore attempts + to set this property to null. You can change this property as needed if you want to rotate your + encryption key; Your data will be unaffected. Encryption with customer-managed keys is not + available for free search services, and is only available for paid services created on or after + January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar similarity: The type of similarity algorithm to be used when scoring and ranking the + documents matching a search query. The similarity algorithm can only be defined at index + creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity + algorithm is used. + :vartype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm + :ivar semantic_search: Defines parameters for a search index that influence semantic + capabilities. + :vartype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch + :ivar vector_search: Contains configuration options related to vector search. + :vartype vector_search: ~azure.search.documents.indexes.models.VectorSearch + :ivar permission_filter_option: A value indicating whether permission filtering is enabled for + the index. Known values are: "enabled" and "disabled". + :vartype permission_filter_option: str or + ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption + :ivar purview_enabled: A value indicating whether Purview is enabled for the index. + :vartype purview_enabled: bool + :ivar e_tag: The ETag of the index. + :vartype e_tag: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the index. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the index.""" + fields: list["_models.SearchField"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The fields of the index. Required.""" + scoring_profiles: Optional[list["_models.ScoringProfile"]] = rest_field( + name="scoringProfiles", visibility=["read", "create", "update", "delete", "query"] + ) + """The scoring profiles for the index.""" + default_scoring_profile: Optional[str] = rest_field( + name="defaultScoringProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the scoring profile to use if none is specified in the query. If this property is + not set and no scoring profile is specified in the query, then default scoring (tf-idf) will be + used.""" + cors_options: Optional["_models.CorsOptions"] = rest_field( + name="corsOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Options to control Cross-Origin Resource Sharing (CORS) for the index.""" + suggesters: Optional[list["_models.SearchSuggester"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The suggesters for the index.""" + analyzers: Optional[list["_models.LexicalAnalyzer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The analyzers for the index.""" + tokenizers: Optional[list["_models.LexicalTokenizer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The tokenizers for the index.""" + token_filters: Optional[list["_models.TokenFilter"]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """The token filters for the index.""" + char_filters: Optional[list["_models.CharFilter"]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """The character filters for the index.""" + normalizers: Optional[list["_models.LexicalNormalizer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The normalizers for the index.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your data when you want full assurance + that no one, not even Microsoft, can decrypt your data. Once you have encrypted your data, it + will always remain encrypted. The search service will ignore attempts to set this property to + null. You can change this property as needed if you want to rotate your encryption key; Your + data will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019.""" + similarity: Optional["_models.SimilarityAlgorithm"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of similarity algorithm to be used when scoring and ranking the documents matching a + search query. The similarity algorithm can only be defined at index creation time and cannot be + modified on existing indexes. If null, the ClassicSimilarity algorithm is used.""" + semantic_search: Optional["_models.SemanticSearch"] = rest_field( + name="semantic", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines parameters for a search index that influence semantic capabilities.""" + vector_search: Optional["_models.VectorSearch"] = rest_field( + name="vectorSearch", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options related to vector search.""" + permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = rest_field( + name="permissionFilterOption", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether permission filtering is enabled for the index. Known values are: + \"enabled\" and \"disabled\".""" + purview_enabled: Optional[bool] = rest_field( + name="purviewEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether Purview is enabled for the index.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the index.""" + + @overload + def __init__( + self, + *, + name: str, + fields: list["_models.SearchField"], + description: Optional[str] = None, + scoring_profiles: Optional[list["_models.ScoringProfile"]] = None, + default_scoring_profile: Optional[str] = None, + cors_options: Optional["_models.CorsOptions"] = None, + suggesters: Optional[list["_models.SearchSuggester"]] = None, + analyzers: Optional[list["_models.LexicalAnalyzer"]] = None, + tokenizers: Optional[list["_models.LexicalTokenizer"]] = None, + token_filters: Optional[list["_models.TokenFilter"]] = None, + char_filters: Optional[list["_models.CharFilter"]] = None, + normalizers: Optional[list["_models.LexicalNormalizer"]] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + similarity: Optional["_models.SimilarityAlgorithm"] = None, + semantic_search: Optional["_models.SemanticSearch"] = None, + vector_search: Optional["_models.VectorSearch"] = None, + permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = None, + purview_enabled: Optional[bool] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexer(_Model): + """Represents an indexer. + + :ivar name: The name of the indexer. Required. + :vartype name: str + :ivar description: The description of the indexer. + :vartype description: str + :ivar data_source_name: The name of the datasource from which this indexer reads data. + Required. + :vartype data_source_name: str + :ivar skillset_name: The name of the skillset executing with this indexer. + :vartype skillset_name: str + :ivar target_index_name: The name of the index to which this indexer writes data. Required. + :vartype target_index_name: str + :ivar schedule: The schedule for this indexer. + :vartype schedule: ~azure.search.documents.indexes.models.IndexingSchedule + :ivar parameters: Parameters for indexer execution. + :vartype parameters: ~azure.search.documents.indexes.models.IndexingParameters + :ivar field_mappings: Defines mappings between fields in the data source and corresponding + target fields in the index. + :vartype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] + :ivar output_field_mappings: Output field mappings are applied after enrichment and immediately + before indexing. + :vartype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] + :ivar is_disabled: A value indicating whether the indexer is disabled. Default is false. + :vartype is_disabled: bool + :ivar e_tag: The ETag of the indexer. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your indexer + definition (as well as indexer execution status) when you want full assurance that no one, not + even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will + always remain encrypted. The search service will ignore attempts to set this property to null. + You can change this property as needed if you want to rotate your encryption key; Your indexer + definition (and indexer execution status) will be unaffected. Encryption with customer-managed + keys is not available for free search services, and is only available for paid services created + on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar cache: Adds caching to an enrichment pipeline to allow for incremental modification steps + without having to rebuild the index every time. + :vartype cache: ~azure.search.documents.indexes.models.SearchIndexerCache + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the indexer. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the indexer.""" + data_source_name: str = rest_field( + name="dataSourceName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the datasource from which this indexer reads data. Required.""" + skillset_name: Optional[str] = rest_field( + name="skillsetName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the skillset executing with this indexer.""" + target_index_name: str = rest_field( + name="targetIndexName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the index to which this indexer writes data. Required.""" + schedule: Optional["_models.IndexingSchedule"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The schedule for this indexer.""" + parameters: Optional["_models.IndexingParameters"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Parameters for indexer execution.""" + field_mappings: Optional[list["_models.FieldMapping"]] = rest_field( + name="fieldMappings", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines mappings between fields in the data source and corresponding target fields in the + index.""" + output_field_mappings: Optional[list["_models.FieldMapping"]] = rest_field( + name="outputFieldMappings", visibility=["read", "create", "update", "delete", "query"] + ) + """Output field mappings are applied after enrichment and immediately before indexing.""" + is_disabled: Optional[bool] = rest_field( + name="disabled", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the indexer is disabled. Default is false.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the indexer.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your indexer definition (as well as + indexer execution status) when you want full assurance that no one, not even Microsoft, can + decrypt them. Once you have encrypted your indexer definition, it will always remain encrypted. + The search service will ignore attempts to set this property to null. You can change this + property as needed if you want to rotate your encryption key; Your indexer definition (and + indexer execution status) will be unaffected. Encryption with customer-managed keys is not + available for free search services, and is only available for paid services created on or after + January 1, 2019.""" + cache: Optional["_models.SearchIndexerCache"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Adds caching to an enrichment pipeline to allow for incremental modification steps without + having to rebuild the index every time.""" + + @overload + def __init__( + self, + *, + name: str, + data_source_name: str, + target_index_name: str, + description: Optional[str] = None, + skillset_name: Optional[str] = None, + schedule: Optional["_models.IndexingSchedule"] = None, + parameters: Optional["_models.IndexingParameters"] = None, + field_mappings: Optional[list["_models.FieldMapping"]] = None, + output_field_mappings: Optional[list["_models.FieldMapping"]] = None, + is_disabled: Optional[bool] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + cache: Optional["_models.SearchIndexerCache"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerCache(_Model): + """The type of the cache. + + :ivar id: A guid for the SearchIndexerCache. + :vartype id: str + :ivar storage_connection_string: The connection string to the storage account where the cache + data will be persisted. + :vartype storage_connection_string: str + :ivar enable_reprocessing: Specifies whether incremental reprocessing is enabled. + :vartype enable_reprocessing: bool + :ivar identity: The user-assigned managed identity used for connections to the enrichment + cache. If the connection string indicates an identity (ResourceId) and it's not specified, the + system-assigned managed identity is used. On updates to the indexer, if the identity is + unspecified, the value remains unchanged. If set to "none", the value of this property is + cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A guid for the SearchIndexerCache.""" + storage_connection_string: Optional[str] = rest_field( + name="storageConnectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """The connection string to the storage account where the cache data will be persisted.""" + enable_reprocessing: Optional[bool] = rest_field( + name="enableReprocessing", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether incremental reprocessing is enabled.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for connections to the enrichment cache. If the + connection string indicates an identity (ResourceId) and it's not specified, the + system-assigned managed identity is used. On updates to the indexer, if the identity is + unspecified, the value remains unchanged. If set to \"none\", the value of this property is + cleared.""" + + @overload + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + storage_connection_string: Optional[str] = None, + enable_reprocessing: Optional[bool] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataContainer(_Model): + """Represents information about the entity (such as Azure SQL table or CosmosDB collection) that + will be indexed. + + :ivar name: The name of the table or view (for Azure SQL data source) or collection (for + CosmosDB data source) that will be indexed. Required. + :vartype name: str + :ivar query: A query that is applied to this data container. The syntax and meaning of this + parameter is datasource-specific. Not supported by Azure SQL datasources. + :vartype query: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the table or view (for Azure SQL data source) or collection (for CosmosDB data + source) that will be indexed. Required.""" + query: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A query that is applied to this data container. The syntax and meaning of this parameter is + datasource-specific. Not supported by Azure SQL datasources.""" + + @overload + def __init__( + self, + *, + name: str, + query: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataIdentity(_Model): + """Abstract base type for data identities. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + SearchIndexerDataNoneIdentity, SearchIndexerDataUserAssignedIdentity + + :ivar odata_type: A URI fragment specifying the type of identity. Required. Default value is + None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """A URI fragment specifying the type of identity. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataNoneIdentity( + SearchIndexerDataIdentity, discriminator="#Microsoft.Azure.Search.DataNoneIdentity" +): + """Clears the identity property of a datasource. + + :ivar odata_type: The discriminator for derived types. Required. Default value is + "#Microsoft.Azure.Search.DataNoneIdentity". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.DataNoneIdentity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator for derived types. Required. Default value is + \"#Microsoft.Azure.Search.DataNoneIdentity\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DataNoneIdentity" # type: ignore + + +class SearchIndexerDataSourceConnection(_Model): + """Represents a datasource definition, which can be used to configure an indexer. + + :ivar name: The name of the datasource. Required. + :vartype name: str + :ivar description: The description of the datasource. + :vartype description: str + :ivar type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", + "azureblob", "azuretable", "mysql", "adlsgen2", "onelake", and "sharepoint". + :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType + :ivar sub_type: A specific type of the data source, in case the resource is capable of + different modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts. + :vartype sub_type: str + :ivar credentials: Credentials for the datasource. Required. + :vartype credentials: ~azure.search.documents.indexes.models.DataSourceCredentials + :ivar container: The data container for the datasource. Required. + :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer + :ivar identity: An explicit managed identity to use for this datasource. If not specified and + the connection string is a managed identity, the system-assigned managed identity is used. If + not specified, the value remains unchanged. If "none" is specified, the value of this property + is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar indexer_permission_options: Ingestion options with various types of permission data. + :vartype indexer_permission_options: list[str or + ~azure.search.documents.indexes.models.IndexerPermissionOption] + :ivar data_change_detection_policy: The data change detection policy for the datasource. + :vartype data_change_detection_policy: + ~azure.search.documents.indexes.models.DataChangeDetectionPolicy + :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource. + :vartype data_deletion_detection_policy: + ~azure.search.documents.indexes.models.DataDeletionDetectionPolicy + :ivar e_tag: The ETag of the data source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your datasource + definition when you want full assurance that no one, not even Microsoft, can decrypt your data + source definition. Once you have encrypted your data source definition, it will always remain + encrypted. The search service will ignore attempts to set this property to null. You can change + this property as needed if you want to rotate your encryption key; Your datasource definition + will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the datasource. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the datasource.""" + type: Union[str, "_models.SearchIndexerDataSourceType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of the datasource. Required. Known values are: \"azuresql\", \"cosmosdb\", + \"azureblob\", \"azuretable\", \"mysql\", \"adlsgen2\", \"onelake\", and \"sharepoint\".""" + sub_type: Optional[str] = rest_field(name="subType", visibility=["read"]) + """A specific type of the data source, in case the resource is capable of different modalities. + For example, 'MongoDb' for certain 'cosmosDb' accounts.""" + credentials: "_models.DataSourceCredentials" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Credentials for the datasource. Required.""" + container: "_models.SearchIndexerDataContainer" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The data container for the datasource. Required.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An explicit managed identity to use for this datasource. If not specified and the connection + string is a managed identity, the system-assigned managed identity is used. If not specified, + the value remains unchanged. If \"none\" is specified, the value of this property is cleared.""" + indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = rest_field( + name="indexerPermissionOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Ingestion options with various types of permission data.""" + data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = rest_field( + name="dataChangeDetectionPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The data change detection policy for the datasource.""" + data_deletion_detection_policy: Optional["_models.DataDeletionDetectionPolicy"] = rest_field( + name="dataDeletionDetectionPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The data deletion detection policy for the datasource.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the data source.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your datasource definition when you want + full assurance that no one, not even Microsoft, can decrypt your data source definition. Once + you have encrypted your data source definition, it will always remain encrypted. The search + service will ignore attempts to set this property to null. You can change this property as + needed if you want to rotate your encryption key; Your datasource definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019.""" + + __flattened_items = ["connection_string"] + + @overload + def __init__( + self, + *, + name: str, + type: Union[str, "_models.SearchIndexerDataSourceType"], + credentials: "_models.DataSourceCredentials", + container: "_models.SearchIndexerDataContainer", + description: Optional[str] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = None, + data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = None, + data_deletion_detection_policy: Optional["_models.DataDeletionDetectionPolicy"] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.credentials is None: + return None + return getattr(self.credentials, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.credentials is None: + self.credentials = self._attr_to_rest_field["credentials"]._class_type() + setattr(self.credentials, key, value) + else: + super().__setattr__(key, value) + + +class SearchIndexerDataUserAssignedIdentity( + SearchIndexerDataIdentity, discriminator="#Microsoft.Azure.Search.DataUserAssignedIdentity" +): + """Specifies the identity for a datasource to use. + + :ivar resource_id: The fully qualified Azure resource Id of a user assigned managed identity + typically in the form + "/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId" + that should have been assigned to the search service. Required. + :vartype resource_id: str + :ivar odata_type: A URI fragment specifying the type of identity. Required. Default value is + "#Microsoft.Azure.Search.DataUserAssignedIdentity". + :vartype odata_type: str + """ + + resource_id: str = rest_field( + name="userAssignedIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The fully qualified Azure resource Id of a user assigned managed identity typically in the form + \"/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId\" + that should have been assigned to the search service. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.DataUserAssignedIdentity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of identity. Required. Default value is + \"#Microsoft.Azure.Search.DataUserAssignedIdentity\".""" + + @overload + def __init__( + self, + *, + resource_id: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DataUserAssignedIdentity" # type: ignore + + +class SearchIndexerError(_Model): + """Represents an item- or document-level indexing error. + + :ivar key: The key of the item for which indexing failed. + :vartype key: str + :ivar error_message: The message describing the error that occurred while processing the item. + Required. + :vartype error_message: str + :ivar status_code: The status code indicating why the indexing operation failed. Possible + values include: 400 for a malformed input document, 404 for document not found, 409 for a + version conflict, 422 when the index is temporarily unavailable, or 503 for when the service is + too busy. Required. + :vartype status_code: int + :ivar name: The name of the source at which the error originated. For example, this could refer + to a particular skill in the attached skillset. This may not be always available. + :vartype name: str + :ivar details: Additional, verbose details about the error to assist in debugging the indexer. + This may not be always available. + :vartype details: str + :ivar documentation_link: A link to a troubleshooting guide for these classes of errors. This + may not be always available. + :vartype documentation_link: str + """ + + key: Optional[str] = rest_field(visibility=["read"]) + """The key of the item for which indexing failed.""" + error_message: str = rest_field(name="errorMessage", visibility=["read"]) + """The message describing the error that occurred while processing the item. Required.""" + status_code: int = rest_field(name="statusCode", visibility=["read"]) + """The status code indicating why the indexing operation failed. Possible values include: 400 for + a malformed input document, 404 for document not found, 409 for a version conflict, 422 when + the index is temporarily unavailable, or 503 for when the service is too busy. Required.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the source at which the error originated. For example, this could refer to a + particular skill in the attached skillset. This may not be always available.""" + details: Optional[str] = rest_field(visibility=["read"]) + """Additional, verbose details about the error to assist in debugging the indexer. This may not be + always available.""" + documentation_link: Optional[str] = rest_field(name="documentationLink", visibility=["read"]) + """A link to a troubleshooting guide for these classes of errors. This may not be always + available.""" + + +class SearchIndexerIndexProjection(_Model): + """Definition of additional projections to secondary search indexes. + + :ivar selectors: A list of projections to be performed to secondary search indexes. Required. + :vartype selectors: + list[~azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector] + :ivar parameters: A dictionary of index projection-specific configuration properties. Each name + is the name of a specific property. Each value must be of a primitive type. + :vartype parameters: + ~azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters + """ + + selectors: list["_models.SearchIndexerIndexProjectionSelector"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of projections to be performed to secondary search indexes. Required.""" + parameters: Optional["_models.SearchIndexerIndexProjectionsParameters"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of index projection-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type.""" + + @overload + def __init__( + self, + *, + selectors: list["_models.SearchIndexerIndexProjectionSelector"], + parameters: Optional["_models.SearchIndexerIndexProjectionsParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerIndexProjectionSelector(_Model): + """Description for what data to store in the designated search index. + + :ivar target_index_name: Name of the search index to project to. Must have a key field with the + 'keyword' analyzer set. Required. + :vartype target_index_name: str + :ivar parent_key_field_name: Name of the field in the search index to map the parent document's + key value to. Must be a string field that is filterable and not the key field. Required. + :vartype parent_key_field_name: str + :ivar source_context: Source context for the projections. Represents the cardinality at which + the document will be split into multiple sub documents. Required. + :vartype source_context: str + :ivar mappings: Mappings for the projection, or which source should be mapped to which field in + the target index. Required. + :vartype mappings: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + """ + + target_index_name: str = rest_field( + name="targetIndexName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of the search index to project to. Must have a key field with the 'keyword' analyzer set. + Required.""" + parent_key_field_name: str = rest_field( + name="parentKeyFieldName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of the field in the search index to map the parent document's key value to. Must be a + string field that is filterable and not the key field. Required.""" + source_context: str = rest_field(name="sourceContext", visibility=["read", "create", "update", "delete", "query"]) + """Source context for the projections. Represents the cardinality at which the document will be + split into multiple sub documents. Required.""" + mappings: list["_models.InputFieldMappingEntry"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Mappings for the projection, or which source should be mapped to which field in the target + index. Required.""" + + @overload + def __init__( + self, + *, + target_index_name: str, + parent_key_field_name: str, + source_context: str, + mappings: list["_models.InputFieldMappingEntry"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerIndexProjectionsParameters(_Model): + """A dictionary of index projection-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type. + + :ivar projection_mode: Defines behavior of the index projections in relation to the rest of the + indexer. Known values are: "skipIndexingParentDocuments" and "includeIndexingParentDocuments". + :vartype projection_mode: str or ~azure.search.documents.indexes.models.IndexProjectionMode + """ + + projection_mode: Optional[Union[str, "_models.IndexProjectionMode"]] = rest_field( + name="projectionMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines behavior of the index projections in relation to the rest of the indexer. Known values + are: \"skipIndexingParentDocuments\" and \"includeIndexingParentDocuments\".""" + + @overload + def __init__( + self, + *, + projection_mode: Optional[Union[str, "_models.IndexProjectionMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStore(_Model): + """Definition of additional projections to azure blob, table, or files, of enriched data. + + :ivar storage_connection_string: The connection string to the storage account projections will + be stored in. Required. + :vartype storage_connection_string: str + :ivar projections: A list of additional projections to perform during indexing. Required. + :vartype projections: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection] + :ivar identity: The user-assigned managed identity used for connections to Azure Storage when + writing knowledge store projections. If the connection string indicates an identity + (ResourceId) and it's not specified, the system-assigned managed identity is used. On updates + to the indexer, if the identity is unspecified, the value remains unchanged. If set to "none", + the value of this property is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar parameters: A dictionary of knowledge store-specific configuration properties. Each name + is the name of a specific property. Each value must be of a primitive type. + :vartype parameters: + ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters + """ + + storage_connection_string: str = rest_field( + name="storageConnectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """The connection string to the storage account projections will be stored in. Required.""" + projections: list["_models.SearchIndexerKnowledgeStoreProjection"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of additional projections to perform during indexing. Required.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for connections to Azure Storage when writing knowledge + store projections. If the connection string indicates an identity (ResourceId) and it's not + specified, the system-assigned managed identity is used. On updates to the indexer, if the + identity is unspecified, the value remains unchanged. If set to \"none\", the value of this + property is cleared.""" + parameters: Optional["_models.SearchIndexerKnowledgeStoreParameters"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of knowledge store-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type.""" + + @overload + def __init__( + self, + *, + storage_connection_string: str, + projections: list["_models.SearchIndexerKnowledgeStoreProjection"], + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + parameters: Optional["_models.SearchIndexerKnowledgeStoreParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreProjectionSelector(_Model): # pylint: disable=name-too-long + """Abstract class to share properties between concrete selectors. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + """ + + reference_key_name: Optional[str] = rest_field( + name="referenceKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of reference key to different projection.""" + generated_key_name: Optional[str] = rest_field( + name="generatedKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of generated key to store projection under.""" + source: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Source data to project.""" + source_context: Optional[str] = rest_field( + name="sourceContext", visibility=["read", "create", "update", "delete", "query"] + ) + """Source context for complex projections.""" + inputs: Optional[list["_models.InputFieldMappingEntry"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Nested inputs for complex projections.""" + + @overload + def __init__( + self, + *, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreBlobProjectionSelector( + SearchIndexerKnowledgeStoreProjectionSelector +): # pylint: disable=name-too-long + """Abstract class to share properties between concrete selectors. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar storage_container: Blob container to store projections in. Required. + :vartype storage_container: str + """ + + storage_container: str = rest_field( + name="storageContainer", visibility=["read", "create", "update", "delete", "query"] + ) + """Blob container to store projections in. Required.""" + + @overload + def __init__( + self, + *, + storage_container: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreFileProjectionSelector( + SearchIndexerKnowledgeStoreBlobProjectionSelector +): # pylint: disable=name-too-long + """Projection definition for what data to store in Azure Files. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar storage_container: Blob container to store projections in. Required. + :vartype storage_container: str + """ + + @overload + def __init__( + self, + *, + storage_container: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreObjectProjectionSelector( + SearchIndexerKnowledgeStoreBlobProjectionSelector +): # pylint: disable=name-too-long + """Projection definition for what data to store in Azure Blob. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar storage_container: Blob container to store projections in. Required. + :vartype storage_container: str + """ + + @overload + def __init__( + self, + *, + storage_container: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreParameters(_Model): + """A dictionary of knowledge store-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type. + + :ivar synthesize_generated_key_name: Whether or not projections should synthesize a generated + key name if one isn't already present. + :vartype synthesize_generated_key_name: bool + """ + + synthesize_generated_key_name: Optional[bool] = rest_field( + name="synthesizeGeneratedKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Whether or not projections should synthesize a generated key name if one isn't already present.""" + + @overload + def __init__( + self, + *, + synthesize_generated_key_name: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreProjection(_Model): + """Container object for various projection selectors. + + :ivar tables: Projections to Azure Table storage. + :vartype tables: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector] + :ivar objects: Projections to Azure Blob storage. + :vartype objects: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector] + :ivar files: Projections to Azure File storage. + :vartype files: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector] + """ + + tables: Optional[list["_models.SearchIndexerKnowledgeStoreTableProjectionSelector"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Projections to Azure Table storage.""" + objects: Optional[list["_models.SearchIndexerKnowledgeStoreObjectProjectionSelector"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Projections to Azure Blob storage.""" + files: Optional[list["_models.SearchIndexerKnowledgeStoreFileProjectionSelector"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Projections to Azure File storage.""" + + @overload + def __init__( + self, + *, + tables: Optional[list["_models.SearchIndexerKnowledgeStoreTableProjectionSelector"]] = None, + objects: Optional[list["_models.SearchIndexerKnowledgeStoreObjectProjectionSelector"]] = None, + files: Optional[list["_models.SearchIndexerKnowledgeStoreFileProjectionSelector"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreTableProjectionSelector( + SearchIndexerKnowledgeStoreProjectionSelector +): # pylint: disable=name-too-long + """Description for what data to store in Azure Tables. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar generated_key_name: Name of generated key to store projection under. Required. + :vartype generated_key_name: str + :ivar table_name: Name of the Azure table to store projected data in. Required. + :vartype table_name: str + """ + + generated_key_name: str = rest_field( + name="generatedKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of generated key to store projection under. Required.""" + table_name: str = rest_field(name="tableName", visibility=["read", "create", "update", "delete", "query"]) + """Name of the Azure table to store projected data in. Required.""" + + @overload + def __init__( + self, + *, + generated_key_name: str, + table_name: str, + reference_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerLimits(_Model): + """Represents the limits that can be applied to an indexer. + + :ivar max_run_time: The maximum duration that the indexer is permitted to run for one + execution. + :vartype max_run_time: ~datetime.timedelta + :ivar max_document_extraction_size: The maximum size of a document, in bytes, which will be + considered valid for indexing. + :vartype max_document_extraction_size: int + :ivar max_document_content_characters_to_extract: The maximum number of characters that will be + extracted from a document picked up for indexing. + :vartype max_document_content_characters_to_extract: int + """ + + max_run_time: Optional[datetime.timedelta] = rest_field(name="maxRunTime", visibility=["read"]) + """The maximum duration that the indexer is permitted to run for one execution.""" + max_document_extraction_size: Optional[int] = rest_field(name="maxDocumentExtractionSize", visibility=["read"]) + """The maximum size of a document, in bytes, which will be considered valid for indexing.""" + max_document_content_characters_to_extract: Optional[int] = rest_field( + name="maxDocumentContentCharactersToExtract", visibility=["read"] + ) + """The maximum number of characters that will be extracted from a document picked up for indexing.""" + + +class SearchIndexerSkillset(_Model): + """A list of skills. + + :ivar name: The name of the skillset. Required. + :vartype name: str + :ivar description: The description of the skillset. + :vartype description: str + :ivar skills: A list of skills in the skillset. Required. + :vartype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] + :ivar cognitive_services_account: Details about the Azure AI service to be used when running + skills. + :vartype cognitive_services_account: + ~azure.search.documents.indexes.models.CognitiveServicesAccount + :ivar knowledge_store: Definition of additional projections to Azure blob, table, or files, of + enriched data. + :vartype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore + :ivar index_projection: Definition of additional projections to secondary search index(es). + :vartype index_projection: ~azure.search.documents.indexes.models.SearchIndexerIndexProjection + :ivar e_tag: The ETag of the skillset. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your skillset + definition when you want full assurance that no one, not even Microsoft, can decrypt your + skillset definition. Once you have encrypted your skillset definition, it will always remain + encrypted. The search service will ignore attempts to set this property to null. You can change + this property as needed if you want to rotate your encryption key; Your skillset definition + will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the skillset. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the skillset.""" + skills: list["_models.SearchIndexerSkill"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of skills in the skillset. Required.""" + cognitive_services_account: Optional["_models.CognitiveServicesAccount"] = rest_field( + name="cognitiveServices", visibility=["read", "create", "update", "delete", "query"] + ) + """Details about the Azure AI service to be used when running skills.""" + knowledge_store: Optional["_models.SearchIndexerKnowledgeStore"] = rest_field( + name="knowledgeStore", visibility=["read", "create", "update", "delete", "query"] + ) + """Definition of additional projections to Azure blob, table, or files, of enriched data.""" + index_projection: Optional["_models.SearchIndexerIndexProjection"] = rest_field( + name="indexProjections", visibility=["read", "create", "update", "delete", "query"] + ) + """Definition of additional projections to secondary search index(es).""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the skillset.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your skillset definition when you want + full assurance that no one, not even Microsoft, can decrypt your skillset definition. Once you + have encrypted your skillset definition, it will always remain encrypted. The search service + will ignore attempts to set this property to null. You can change this property as needed if + you want to rotate your encryption key; Your skillset definition will be unaffected. Encryption + with customer-managed keys is not available for free search services, and is only available for + paid services created on or after January 1, 2019.""" + + @overload + def __init__( + self, + *, + name: str, + skills: list["_models.SearchIndexerSkill"], + description: Optional[str] = None, + cognitive_services_account: Optional["_models.CognitiveServicesAccount"] = None, + knowledge_store: Optional["_models.SearchIndexerKnowledgeStore"] = None, + index_projection: Optional["_models.SearchIndexerIndexProjection"] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerStatus(_Model): + """Represents the current status and execution history of an indexer. + + :ivar name: The name of the indexer. Required. + :vartype name: str + :ivar status: Overall indexer status. Required. Known values are: "unknown", "error", and + "running". + :vartype status: str or ~azure.search.documents.indexes.models.IndexerStatus + :ivar runtime: Snapshot of the indexer's cumulative runtime consumption for the service over + the current UTC period. Required. + :vartype runtime: ~azure.search.documents.indexes.models.IndexerRuntime + :ivar last_result: The result of the most recent or an in-progress indexer execution. + :vartype last_result: ~azure.search.documents.indexes.models.IndexerExecutionResult + :ivar execution_history: History of the recent indexer executions, sorted in reverse + chronological order. Required. + :vartype execution_history: list[~azure.search.documents.indexes.models.IndexerExecutionResult] + :ivar limits: The execution limits for the indexer. Required. + :vartype limits: ~azure.search.documents.indexes.models.SearchIndexerLimits + :ivar current_state: All of the state that defines and dictates the indexer's current + execution. + :vartype current_state: ~azure.search.documents.indexes.models.IndexerCurrentState + """ + + name: str = rest_field(visibility=["read"]) + """The name of the indexer. Required.""" + status: Union[str, "_models.IndexerStatus"] = rest_field(visibility=["read"]) + """Overall indexer status. Required. Known values are: \"unknown\", \"error\", and \"running\".""" + runtime: "_models.IndexerRuntime" = rest_field(visibility=["read"]) + """Snapshot of the indexer's cumulative runtime consumption for the service over the current UTC + period. Required.""" + last_result: Optional["_models.IndexerExecutionResult"] = rest_field(name="lastResult", visibility=["read"]) + """The result of the most recent or an in-progress indexer execution.""" + execution_history: list["_models.IndexerExecutionResult"] = rest_field(name="executionHistory", visibility=["read"]) + """History of the recent indexer executions, sorted in reverse chronological order. Required.""" + limits: "_models.SearchIndexerLimits" = rest_field(visibility=["read"]) + """The execution limits for the indexer. Required.""" + current_state: Optional["_models.IndexerCurrentState"] = rest_field(name="currentState", visibility=["read"]) + """All of the state that defines and dictates the indexer's current execution.""" + + +class SearchIndexerWarning(_Model): + """Represents an item-level warning. + + :ivar key: The key of the item which generated a warning. + :vartype key: str + :ivar message: The message describing the warning that occurred while processing the item. + Required. + :vartype message: str + :ivar name: The name of the source at which the warning originated. For example, this could + refer to a particular skill in the attached skillset. This may not be always available. + :vartype name: str + :ivar details: Additional, verbose details about the warning to assist in debugging the + indexer. This may not be always available. + :vartype details: str + :ivar documentation_link: A link to a troubleshooting guide for these classes of warnings. This + may not be always available. + :vartype documentation_link: str + """ + + key: Optional[str] = rest_field(visibility=["read"]) + """The key of the item which generated a warning.""" + message: str = rest_field(visibility=["read"]) + """The message describing the warning that occurred while processing the item. Required.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the source at which the warning originated. For example, this could refer to a + particular skill in the attached skillset. This may not be always available.""" + details: Optional[str] = rest_field(visibility=["read"]) + """Additional, verbose details about the warning to assist in debugging the indexer. This may not + be always available.""" + documentation_link: Optional[str] = rest_field(name="documentationLink", visibility=["read"]) + """A link to a troubleshooting guide for these classes of warnings. This may not be always + available.""" + + +class SearchIndexFieldReference(_Model): + """Field reference for a search index. + + :ivar name: The name of the field. Required. + :vartype name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the field. Required.""" + + @overload + def __init__( + self, + *, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexKnowledgeSource(KnowledgeSource, discriminator="searchIndex"): + """Knowledge Source targeting a search index. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the knowledge source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that reads data from a Search Index. + :vartype kind: str or ~azure.search.documents.indexes.models.SEARCH_INDEX + :ivar search_index_parameters: The parameters for the knowledge source. Required. + :vartype search_index_parameters: + ~azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters + """ + + kind: Literal[KnowledgeSourceKind.SEARCH_INDEX] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that reads data from a Search Index.""" + search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters" = rest_field( + name="searchIndexParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The parameters for the knowledge source. Required.""" + + @overload + def __init__( + self, + *, + name: str, + search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters", + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.SEARCH_INDEX # type: ignore + + +class SearchIndexKnowledgeSourceParameters(_Model): + """Parameters for search index knowledge source. + + :ivar search_index_name: The name of the Search index. Required. + :vartype search_index_name: str + :ivar source_data_fields: Used to request additional fields for referenced source data. + :vartype source_data_fields: + list[~azure.search.documents.indexes.models.SearchIndexFieldReference] + :ivar search_fields: Used to restrict which fields to search on the search index. + :vartype search_fields: list[~azure.search.documents.indexes.models.SearchIndexFieldReference] + :ivar semantic_configuration_name: Used to specify a different semantic configuration on the + target search index other than the default one. + :vartype semantic_configuration_name: str + """ + + search_index_name: str = rest_field( + name="searchIndexName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the Search index. Required.""" + source_data_fields: Optional[list["_models.SearchIndexFieldReference"]] = rest_field( + name="sourceDataFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Used to request additional fields for referenced source data.""" + search_fields: Optional[list["_models.SearchIndexFieldReference"]] = rest_field( + name="searchFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Used to restrict which fields to search on the search index.""" + semantic_configuration_name: Optional[str] = rest_field( + name="semanticConfigurationName", visibility=["read", "create", "update", "delete", "query"] + ) + """Used to specify a different semantic configuration on the target search index other than the + default one.""" + + @overload + def __init__( + self, + *, + search_index_name: str, + source_data_fields: Optional[list["_models.SearchIndexFieldReference"]] = None, + search_fields: Optional[list["_models.SearchIndexFieldReference"]] = None, + semantic_configuration_name: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchResourceEncryptionKey(_Model): + """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be + used to encrypt or decrypt data-at-rest, such as indexes and synonym maps. + + :ivar key_name: The name of your Azure Key Vault key to be used to encrypt your data at rest. + Required. + :vartype key_name: str + :ivar key_version: The version of your Azure Key Vault key to be used to encrypt your data at + rest. + :vartype key_version: str + :ivar vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that contains + the key to be used to encrypt your data at rest. An example URI might be + ``https://my-keyvault-name.vault.azure.net``. Required. + :vartype vault_uri: str + :ivar access_credentials: Optional Azure Active Directory credentials used for accessing your + Azure Key Vault. Not required if using managed identity instead. + :vartype access_credentials: + ~azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials + :ivar identity: An explicit managed identity to use for this encryption key. If not specified + and the access credentials property is null, the system-assigned managed identity is used. On + update to the resource, if the explicit identity is unspecified, it remains unchanged. If + "none" is specified, the value of this property is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + """ + + key_name: str = rest_field(name="keyVaultKeyName", visibility=["read", "create", "update", "delete", "query"]) + """The name of your Azure Key Vault key to be used to encrypt your data at rest. Required.""" + key_version: Optional[str] = rest_field( + name="keyVaultKeyVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of your Azure Key Vault key to be used to encrypt your data at rest.""" + vault_uri: str = rest_field(name="keyVaultUri", visibility=["read", "create", "update", "delete", "query"]) + """The URI of your Azure Key Vault, also referred to as DNS name, that contains the key to be used + to encrypt your data at rest. An example URI might be + ``https://my-keyvault-name.vault.azure.net``. Required.""" + access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = rest_field( + name="accessCredentials", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional Azure Active Directory credentials used for accessing your Azure Key Vault. Not + required if using managed identity instead.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An explicit managed identity to use for this encryption key. If not specified and the access + credentials property is null, the system-assigned managed identity is used. On update to the + resource, if the explicit identity is unspecified, it remains unchanged. If \"none\" is + specified, the value of this property is cleared.""" + + __flattened_items = ["application_id", "application_secret"] + + @overload + def __init__( + self, + *, + key_name: str, + vault_uri: str, + key_version: Optional[str] = None, + access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.access_credentials is None: + return None + return getattr(self.access_credentials, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.access_credentials is None: + self.access_credentials = self._attr_to_rest_field["access_credentials"]._class_type() + setattr(self.access_credentials, key, value) + else: + super().__setattr__(key, value) + + +class SearchServiceCounters(_Model): + """Represents service-level resource counters and quotas. + + :ivar alias_counter: Total number of aliases. Required. + :vartype alias_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar document_counter: Total number of documents across all indexes in the service. Required. + :vartype document_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar index_counter: Total number of indexes. Required. + :vartype index_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar indexer_counter: Total number of indexers. Required. + :vartype indexer_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar data_source_counter: Total number of data sources. Required. + :vartype data_source_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar storage_size_counter: Total size of used storage in bytes. Required. + :vartype storage_size_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar synonym_map_counter: Total number of synonym maps. Required. + :vartype synonym_map_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar skillset_counter: Total number of skillsets. Required. + :vartype skillset_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar vector_index_size_counter: Total memory consumption of all vector indexes within the + service, in bytes. Required. + :vartype vector_index_size_counter: ~azure.search.documents.indexes.models.ResourceCounter + """ + + alias_counter: "_models.ResourceCounter" = rest_field( + name="aliasesCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of aliases. Required.""" + document_counter: "_models.ResourceCounter" = rest_field( + name="documentCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of documents across all indexes in the service. Required.""" + index_counter: "_models.ResourceCounter" = rest_field( + name="indexesCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of indexes. Required.""" + indexer_counter: "_models.ResourceCounter" = rest_field( + name="indexersCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of indexers. Required.""" + data_source_counter: "_models.ResourceCounter" = rest_field( + name="dataSourcesCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of data sources. Required.""" + storage_size_counter: "_models.ResourceCounter" = rest_field( + name="storageSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Total size of used storage in bytes. Required.""" + synonym_map_counter: "_models.ResourceCounter" = rest_field( + name="synonymMaps", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of synonym maps. Required.""" + skillset_counter: "_models.ResourceCounter" = rest_field( + name="skillsetCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of skillsets. Required.""" + vector_index_size_counter: "_models.ResourceCounter" = rest_field( + name="vectorIndexSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Total memory consumption of all vector indexes within the service, in bytes. Required.""" + + @overload + def __init__( + self, + *, + alias_counter: "_models.ResourceCounter", + document_counter: "_models.ResourceCounter", + index_counter: "_models.ResourceCounter", + indexer_counter: "_models.ResourceCounter", + data_source_counter: "_models.ResourceCounter", + storage_size_counter: "_models.ResourceCounter", + synonym_map_counter: "_models.ResourceCounter", + skillset_counter: "_models.ResourceCounter", + vector_index_size_counter: "_models.ResourceCounter", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchServiceLimits(_Model): + """Represents various service level limits. + + :ivar max_fields_per_index: The maximum allowed fields per index. + :vartype max_fields_per_index: int + :ivar max_field_nesting_depth_per_index: The maximum depth which you can nest sub-fields in an + index, including the top-level complex field. For example, a/b/c has a nesting depth of 3. + :vartype max_field_nesting_depth_per_index: int + :ivar max_complex_collection_fields_per_index: The maximum number of fields of type + Collection(Edm.ComplexType) allowed in an index. + :vartype max_complex_collection_fields_per_index: int + :ivar max_complex_objects_in_collections_per_document: The maximum number of objects in complex + collections allowed per document. + :vartype max_complex_objects_in_collections_per_document: int + :ivar max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per index. + :vartype max_storage_per_index_in_bytes: int + :ivar max_cumulative_indexer_runtime_seconds: The maximum cumulative indexer runtime in seconds + allowed for the service. + :vartype max_cumulative_indexer_runtime_seconds: int + """ + + max_fields_per_index: Optional[int] = rest_field( + name="maxFieldsPerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum allowed fields per index.""" + max_field_nesting_depth_per_index: Optional[int] = rest_field( + name="maxFieldNestingDepthPerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum depth which you can nest sub-fields in an index, including the top-level complex + field. For example, a/b/c has a nesting depth of 3.""" + max_complex_collection_fields_per_index: Optional[int] = rest_field( + name="maxComplexCollectionFieldsPerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of fields of type Collection(Edm.ComplexType) allowed in an index.""" + max_complex_objects_in_collections_per_document: Optional[int] = rest_field( + name="maxComplexObjectsInCollectionsPerDocument", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of objects in complex collections allowed per document.""" + max_storage_per_index_in_bytes: Optional[int] = rest_field( + name="maxStoragePerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum amount of storage in bytes allowed per index.""" + max_cumulative_indexer_runtime_seconds: Optional[int] = rest_field( + name="maxCumulativeIndexerRuntimeSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum cumulative indexer runtime in seconds allowed for the service.""" + + @overload + def __init__( + self, + *, + max_fields_per_index: Optional[int] = None, + max_field_nesting_depth_per_index: Optional[int] = None, + max_complex_collection_fields_per_index: Optional[int] = None, + max_complex_objects_in_collections_per_document: Optional[int] = None, + max_storage_per_index_in_bytes: Optional[int] = None, + max_cumulative_indexer_runtime_seconds: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchServiceStatistics(_Model): + """Response from a get service statistics request. If successful, it includes service level + counters and limits. + + :ivar counters: Service level resource counters. Required. + :vartype counters: ~azure.search.documents.indexes.models.SearchServiceCounters + :ivar limits: Service level general limits. Required. + :vartype limits: ~azure.search.documents.indexes.models.SearchServiceLimits + :ivar indexers_runtime: Service level indexer runtime consumption. Required. + :vartype indexers_runtime: ~azure.search.documents.indexes.models.ServiceIndexersRuntime + """ + + counters: "_models.SearchServiceCounters" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Service level resource counters. Required.""" + limits: "_models.SearchServiceLimits" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Service level general limits. Required.""" + indexers_runtime: "_models.ServiceIndexersRuntime" = rest_field( + name="indexersRuntime", visibility=["read", "create", "update", "delete", "query"] + ) + """Service level indexer runtime consumption. Required.""" + + @overload + def __init__( + self, + *, + counters: "_models.SearchServiceCounters", + limits: "_models.SearchServiceLimits", + indexers_runtime: "_models.ServiceIndexersRuntime", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchSuggester(_Model): + """Defines how the Suggest API should apply to a group of fields in the index. + + :ivar name: The name of the suggester. Required. + :vartype name: str + :ivar search_mode: A value indicating the capabilities of the suggester. Required. Default + value is "analyzingInfixMatching". + :vartype search_mode: str + :ivar source_fields: The list of field names to which the suggester applies. Each field must be + searchable. Required. + :vartype source_fields: list[str] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the suggester. Required.""" + search_mode: Literal["analyzingInfixMatching"] = rest_field( + name="searchMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating the capabilities of the suggester. Required. Default value is + \"analyzingInfixMatching\".""" + source_fields: list[str] = rest_field( + name="sourceFields", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of field names to which the suggester applies. Each field must be searchable. + Required.""" + + @overload + def __init__( + self, + *, + name: str, + source_fields: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.search_mode: Literal["analyzingInfixMatching"] = "analyzingInfixMatching" + + +class SemanticConfiguration(_Model): + """Defines a specific configuration to be used in the context of semantic capabilities. + + :ivar name: The name of the semantic configuration. Required. + :vartype name: str + :ivar prioritized_fields: Describes the title, content, and keyword fields to be used for + semantic ranking, captions, highlights, and answers. At least one of the three sub properties + (titleField, prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required. + :vartype prioritized_fields: ~azure.search.documents.indexes.models.SemanticPrioritizedFields + :ivar ranking_order: Specifies the score type to be used for the sort order of the search + results. Known values are: "BoostedRerankerScore" and "RerankerScore". + :vartype ranking_order: str or ~azure.search.documents.indexes.models.RankingOrder + :ivar flighting_opt_in: Determines which semantic or query rewrite models to use during model + flighting/upgrades. + :vartype flighting_opt_in: bool + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the semantic configuration. Required.""" + prioritized_fields: "_models.SemanticPrioritizedFields" = rest_field( + name="prioritizedFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Describes the title, content, and keyword fields to be used for semantic ranking, captions, + highlights, and answers. At least one of the three sub properties (titleField, + prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required.""" + ranking_order: Optional[Union[str, "_models.RankingOrder"]] = rest_field( + name="rankingOrder", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the score type to be used for the sort order of the search results. Known values are: + \"BoostedRerankerScore\" and \"RerankerScore\".""" + flighting_opt_in: Optional[bool] = rest_field( + name="flightingOptIn", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines which semantic or query rewrite models to use during model flighting/upgrades.""" + + @overload + def __init__( + self, + *, + name: str, + prioritized_fields: "_models.SemanticPrioritizedFields", + ranking_order: Optional[Union[str, "_models.RankingOrder"]] = None, + flighting_opt_in: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SemanticField(_Model): + """A field that is used as part of the semantic configuration. + + :ivar field_name: File name. Required. + :vartype field_name: str + """ + + field_name: str = rest_field(name="fieldName", visibility=["read", "create", "update", "delete", "query"]) + """File name. Required.""" + + @overload + def __init__( + self, + *, + field_name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SemanticPrioritizedFields(_Model): + """Describes the title, content, and keywords fields to be used for semantic ranking, captions, + highlights, and answers. + + :ivar title_field: Defines the title field to be used for semantic ranking, captions, + highlights, and answers. If you don't have a title field in your index, leave this blank. + :vartype title_field: ~azure.search.documents.indexes.models.SemanticField + :ivar content_fields: Defines the content fields to be used for semantic ranking, captions, + highlights, and answers. For the best result, the selected fields should contain text in + natural language form. The order of the fields in the array represents their priority. Fields + with lower priority may get truncated if the content is long. + :vartype content_fields: list[~azure.search.documents.indexes.models.SemanticField] + :ivar keywords_fields: Defines the keyword fields to be used for semantic ranking, captions, + highlights, and answers. For the best result, the selected fields should contain a list of + keywords. The order of the fields in the array represents their priority. Fields with lower + priority may get truncated if the content is long. + :vartype keywords_fields: list[~azure.search.documents.indexes.models.SemanticField] + """ + + title_field: Optional["_models.SemanticField"] = rest_field( + name="titleField", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the title field to be used for semantic ranking, captions, highlights, and answers. If + you don't have a title field in your index, leave this blank.""" + content_fields: Optional[list["_models.SemanticField"]] = rest_field( + name="prioritizedContentFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the content fields to be used for semantic ranking, captions, highlights, and answers. + For the best result, the selected fields should contain text in natural language form. The + order of the fields in the array represents their priority. Fields with lower priority may get + truncated if the content is long.""" + keywords_fields: Optional[list["_models.SemanticField"]] = rest_field( + name="prioritizedKeywordsFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the keyword fields to be used for semantic ranking, captions, highlights, and answers. + For the best result, the selected fields should contain a list of keywords. The order of the + fields in the array represents their priority. Fields with lower priority may get truncated if + the content is long.""" + + @overload + def __init__( + self, + *, + title_field: Optional["_models.SemanticField"] = None, + content_fields: Optional[list["_models.SemanticField"]] = None, + keywords_fields: Optional[list["_models.SemanticField"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SemanticSearch(_Model): + """Defines parameters for a search index that influence semantic capabilities. + + :ivar default_configuration_name: Allows you to set the name of a default semantic + configuration in your index, making it optional to pass it on as a query parameter every time. + :vartype default_configuration_name: str + :ivar configurations: The semantic configurations for the index. + :vartype configurations: list[~azure.search.documents.indexes.models.SemanticConfiguration] + """ + + default_configuration_name: Optional[str] = rest_field( + name="defaultConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows you to set the name of a default semantic configuration in your index, making it + optional to pass it on as a query parameter every time.""" + configurations: Optional[list["_models.SemanticConfiguration"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The semantic configurations for the index.""" + + @overload + def __init__( + self, + *, + default_configuration_name: Optional[str] = None, + configurations: Optional[list["_models.SemanticConfiguration"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SentimentSkillV3(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.V3.SentimentSkill"): + """Using the Text Analytics API, evaluates unstructured text and for each record, provides + sentiment labels (such as "negative", "neutral" and "positive") based on the highest confidence + score found by the service at a sentence and document-level. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar include_opinion_mining: If set to true, the skill output will include information from + Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated + assessment (adjective) in the text. Default is false. + :vartype include_opinion_mining: bool + :ivar model_version: The version of the model to use when calling the Text Analytics service. It will default to the latest available when not specified. We recommend you do not specify this value unless absolutely necessary. :vartype model_version: str - :ivar skill_version: The version of the skill to use when calling the Text Analytics service. - It will default to V1 when not specified. - :vartype skill_version: ~azure.search.documents.indexes.models.EntityRecognitionSkillVersion - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "categories": {"key": "categories", "type": "[str]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_typeless_entities": {"key": "includeTypelessEntities", "type": "bool"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "model_version": {"key": "modelVersion", "type": "str"}, - "skill_version": {"key": "skillVersion", "type": "str"}, - } - - def __init__(self, **kwargs): - # pop skill_version from kwargs to avoid warning in msrest - skill_version = kwargs.pop("skill_version", EntityRecognitionSkillVersion.V3) - - super(EntityRecognitionSkill, self).__init__(**kwargs) - self.skill_version = skill_version - self.odata_type = self.skill_version - self.categories = kwargs.get("categories", None) - self.default_language_code = kwargs.get("default_language_code", None) - self.minimum_precision = kwargs.get("minimum_precision", None) - self.include_typeless_entities = kwargs.get("include_typeless_entities", None) - self.model_version = kwargs.get("model_version", None) - - def _to_generated(self): - if self.skill_version in [ - EntityRecognitionSkillVersion.V3, - EntityRecognitionSkillVersion.LATEST, - ]: - return _EntityRecognitionSkillV3( - inputs=self.inputs, - outputs=self.outputs, - name=self.name, - description=self.description, - context=self.context, - odata_type=self.odata_type, - categories=self.categories, - default_language_code=self.default_language_code, - minimum_precision=self.minimum_precision, - model_version=self.model_version, - ) - return None - - @classmethod - def _from_generated(cls, skill): - if not skill: - return None - kwargs = skill.as_dict() - if isinstance(skill, _EntityRecognitionSkillV3): - return EntityRecognitionSkill(skill_version=EntityRecognitionSkillVersion.V3, **kwargs) - return None - - -class SentimentSkillVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the Sentiment Skill version to use.""" - - V1 = "#Microsoft.Skills.Text.SentimentSkill" - #: Use Sentiment skill V3. - V3 = "#Microsoft.Skills.Text.V3.SentimentSkill" - #: Use latest version of Sentiment skill. - LATEST = V3 - - -class SentimentSkill(SearchIndexerSkill): - """This skill is deprecated. Use the V3.SentimentSkill instead. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.V3.SentimentSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + include_opinion_mining: Optional[bool] = rest_field( + name="includeOpinionMining", visibility=["read", "create", "update", "delete", "query"] + ) + """If set to true, the skill output will include information from Text Analytics for opinion + mining, namely targets (nouns or verbs) and their associated assessment (adjective) in the + text. Default is false.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.V3.SentimentSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.V3.SentimentSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[str] = None, + include_opinion_mining: Optional[bool] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.V3.SentimentSkill" # type: ignore + + +class ServiceIndexersRuntime(_Model): + """Represents service-level indexer runtime counters. + + :ivar used_seconds: Cumulative runtime of all indexers in the service from the beginningTime to + endingTime, in seconds. Required. + :vartype used_seconds: int + :ivar remaining_seconds: Cumulative runtime remaining for all indexers in the service from the + beginningTime to endingTime, in seconds. + :vartype remaining_seconds: int + :ivar beginning_time: Beginning UTC time of the 24-hour period considered for indexer runtime + usage (inclusive). Required. + :vartype beginning_time: ~datetime.datetime + :ivar ending_time: End UTC time of the 24-hour period considered for indexer runtime usage + (inclusive). Required. + :vartype ending_time: ~datetime.datetime + """ + + used_seconds: int = rest_field(name="usedSeconds", visibility=["read", "create", "update", "delete", "query"]) + """Cumulative runtime of all indexers in the service from the beginningTime to endingTime, in + seconds. Required.""" + remaining_seconds: Optional[int] = rest_field( + name="remainingSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """Cumulative runtime remaining for all indexers in the service from the beginningTime to + endingTime, in seconds.""" + beginning_time: datetime.datetime = rest_field( + name="beginningTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Beginning UTC time of the 24-hour period considered for indexer runtime usage (inclusive). + Required.""" + ending_time: datetime.datetime = rest_field( + name="endingTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """End UTC time of the 24-hour period considered for indexer runtime usage (inclusive). Required.""" + + @overload + def __init__( + self, + *, + used_seconds: int, + beginning_time: datetime.datetime, + ending_time: datetime.datetime, + remaining_seconds: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShaperSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.ShaperSkill"): + """A skill for reshaping the outputs. It creates a complex type to support composite fields (also + known as multipart fields). + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.ShaperSkill". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Skills.Util.ShaperSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.ShaperSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.ShaperSkill" # type: ignore + + +class ShingleTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.ShingleTokenFilter"): + """Creates combinations of tokens as a single token. This token filter is implemented using Apache + Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_shingle_size: The maximum shingle size. Default and minimum value is 2. + :vartype max_shingle_size: int + :ivar min_shingle_size: The minimum shingle size. Default and minimum value is 2. Must be less + than the value of maxShingleSize. + :vartype min_shingle_size: int + :ivar output_unigrams: A value indicating whether the output stream will contain the input + tokens (unigrams) as well as shingles. Default is true. + :vartype output_unigrams: bool + :ivar output_unigrams_if_no_shingles: A value indicating whether to output unigrams for those + times when no shingles are available. This property takes precedence when outputUnigrams is set + to false. Default is false. + :vartype output_unigrams_if_no_shingles: bool + :ivar token_separator: The string to use when joining adjacent tokens to form a shingle. + Default is a single space (" "). + :vartype token_separator: str + :ivar filter_token: The string to insert for each position at which there is no token. Default + is an underscore ("_"). + :vartype filter_token: str + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.ShingleTokenFilter". + :vartype odata_type: str + """ + + max_shingle_size: Optional[int] = rest_field( + name="maxShingleSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum shingle size. Default and minimum value is 2.""" + min_shingle_size: Optional[int] = rest_field( + name="minShingleSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The minimum shingle size. Default and minimum value is 2. Must be less than the value of + maxShingleSize.""" + output_unigrams: Optional[bool] = rest_field( + name="outputUnigrams", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the output stream will contain the input tokens (unigrams) as well + as shingles. Default is true.""" + output_unigrams_if_no_shingles: Optional[bool] = rest_field( + name="outputUnigramsIfNoShingles", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to output unigrams for those times when no shingles are available. + This property takes precedence when outputUnigrams is set to false. Default is false.""" + token_separator: Optional[str] = rest_field( + name="tokenSeparator", visibility=["read", "create", "update", "delete", "query"] + ) + """The string to use when joining adjacent tokens to form a shingle. Default is a single space (\" + \").""" + filter_token: Optional[str] = rest_field( + name="filterToken", visibility=["read", "create", "update", "delete", "query"] + ) + """The string to insert for each position at which there is no token. Default is an underscore + (\"_\").""" + odata_type: Literal["#Microsoft.Azure.Search.ShingleTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.ShingleTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + max_shingle_size: Optional[int] = None, + min_shingle_size: Optional[int] = None, + output_unigrams: Optional[bool] = None, + output_unigrams_if_no_shingles: Optional[bool] = None, + token_separator: Optional[str] = None, + filter_token: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ShingleTokenFilter" # type: ignore + + +class SkillNames(_Model): + """The type of the skill names. + + :ivar skill_names: the names of skills to be reset. + :vartype skill_names: list[str] + """ + + skill_names: Optional[list[str]] = rest_field( + name="skillNames", visibility=["read", "create", "update", "delete", "query"] + ) + """the names of skills to be reset.""" + + @overload + def __init__( + self, + *, + skill_names: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SnowballTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.SnowballTokenFilter"): + """A filter that stems words using a Snowball-generated stemmer. This token filter is implemented + using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar language: The language to use. Required. Known values are: "armenian", "basque", + "catalan", "danish", "dutch", "english", "finnish", "french", "german", "german2", "hungarian", + "italian", "kp", "lovins", "norwegian", "porter", "portuguese", "romanian", "russian", + "spanish", "swedish", and "turkish". + :vartype language: str or ~azure.search.documents.indexes.models.SnowballTokenFilterLanguage + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.SnowballTokenFilter". + :vartype odata_type: str + """ + + language: Union[str, "_models.SnowballTokenFilterLanguage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. Required. Known values are: \"armenian\", \"basque\", \"catalan\", + \"danish\", \"dutch\", \"english\", \"finnish\", \"french\", \"german\", \"german2\", + \"hungarian\", \"italian\", \"kp\", \"lovins\", \"norwegian\", \"porter\", \"portuguese\", + \"romanian\", \"russian\", \"spanish\", \"swedish\", and \"turkish\".""" + odata_type: Literal["#Microsoft.Azure.Search.SnowballTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.SnowballTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + language: Union[str, "_models.SnowballTokenFilterLanguage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SnowballTokenFilter" # type: ignore + + +class SoftDeleteColumnDeletionDetectionPolicy( + DataDeletionDetectionPolicy, discriminator="#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy" +): + """Defines a data deletion detection policy that implements a soft-deletion strategy. It + determines whether an item should be deleted based on the value of a designated 'soft delete' + column. + + :ivar soft_delete_column_name: The name of the column to use for soft-deletion detection. + :vartype soft_delete_column_name: str + :ivar soft_delete_marker_value: The marker value that identifies an item as deleted. + :vartype soft_delete_marker_value: str + :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. + Required. Default value is "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy". + :vartype odata_type: str + """ + + soft_delete_column_name: Optional[str] = rest_field( + name="softDeleteColumnName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the column to use for soft-deletion detection.""" + soft_delete_marker_value: Optional[str] = rest_field( + name="softDeleteMarkerValue", visibility=["read", "create", "update", "delete", "query"] + ) + """The marker value that identifies an item as deleted.""" + odata_type: Literal["#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data deletion detection policy. Required. Default value + is \"#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy\".""" + + @overload + def __init__( + self, + *, + soft_delete_column_name: Optional[str] = None, + soft_delete_marker_value: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy" # type: ignore + + +class SplitSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.SplitSkill"): + """A skill to split a string into chunks of text. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "am", "bs", "cs", "da", "de", "en", "es", "et", "fi", "fr", "he", "hi", "hr", + "hu", "id", "is", "it", "ja", "ko", "lv", "nb", "nl", "pl", "pt", "pt-br", "ru", "sk", "sl", + "sr", "sv", "tr", "ur", and "zh". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.SplitSkillLanguage + :ivar text_split_mode: A value indicating which split mode to perform. Known values are: + "pages" and "sentences". + :vartype text_split_mode: str or ~azure.search.documents.indexes.models.TextSplitMode + :ivar maximum_page_length: The desired maximum page length. Default is 10000. + :vartype maximum_page_length: int + :ivar page_overlap_length: Only applicable when textSplitMode is set to 'pages'. If specified, + n+1th chunk will start with this number of characters/tokens from the end of the nth chunk. + :vartype page_overlap_length: int + :ivar maximum_pages_to_take: Only applicable when textSplitMode is set to 'pages'. If + specified, the SplitSkill will discontinue splitting after processing the first + 'maximumPagesToTake' pages, in order to improve performance when only a few initial pages are + needed from each document. + :vartype maximum_pages_to_take: int + :ivar unit: Only applies if textSplitMode is set to pages. There are two possible values. The + choice of the values will decide the length (maximumPageLength and pageOverlapLength) + measurement. The default is 'characters', which means the length will be measured by character. + Known values are: "characters" and "azureOpenAITokens". + :vartype unit: str or ~azure.search.documents.indexes.models.SplitSkillUnit + :ivar azure_open_ai_tokenizer_parameters: Only applies if the unit is set to azureOpenAITokens. + If specified, the splitSkill will use these parameters when performing the tokenization. The + parameters are a valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. + :vartype azure_open_ai_tokenizer_parameters: + ~azure.search.documents.indexes.models.AzureOpenAITokenizerParameters + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.SplitSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.SplitSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"am\", + \"bs\", \"cs\", \"da\", \"de\", \"en\", \"es\", \"et\", \"fi\", \"fr\", \"he\", \"hi\", \"hr\", + \"hu\", \"id\", \"is\", \"it\", \"ja\", \"ko\", \"lv\", \"nb\", \"nl\", \"pl\", \"pt\", + \"pt-br\", \"ru\", \"sk\", \"sl\", \"sr\", \"sv\", \"tr\", \"ur\", and \"zh\".""" + text_split_mode: Optional[Union[str, "_models.TextSplitMode"]] = rest_field( + name="textSplitMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which split mode to perform. Known values are: \"pages\" and \"sentences\".""" + maximum_page_length: Optional[int] = rest_field( + name="maximumPageLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The desired maximum page length. Default is 10000.""" + page_overlap_length: Optional[int] = rest_field( + name="pageOverlapLength", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applicable when textSplitMode is set to 'pages'. If specified, n+1th chunk will start with + this number of characters/tokens from the end of the nth chunk.""" + maximum_pages_to_take: Optional[int] = rest_field( + name="maximumPagesToTake", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applicable when textSplitMode is set to 'pages'. If specified, the SplitSkill will + discontinue splitting after processing the first 'maximumPagesToTake' pages, in order to + improve performance when only a few initial pages are needed from each document.""" + unit: Optional[Union[str, "_models.SplitSkillUnit"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Only applies if textSplitMode is set to pages. There are two possible values. The choice of the + values will decide the length (maximumPageLength and pageOverlapLength) measurement. The + default is 'characters', which means the length will be measured by character. Known values + are: \"characters\" and \"azureOpenAITokens\".""" + azure_open_ai_tokenizer_parameters: Optional["_models.AzureOpenAITokenizerParameters"] = rest_field( + name="azureOpenAITokenizerParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applies if the unit is set to azureOpenAITokens. If specified, the splitSkill will use + these parameters when performing the tokenization. The parameters are a valid + 'encoderModelName' and an optional 'allowedSpecialTokens' property.""" + odata_type: Literal["#Microsoft.Skills.Text.SplitSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.SplitSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.SplitSkillLanguage"]] = None, + text_split_mode: Optional[Union[str, "_models.TextSplitMode"]] = None, + maximum_page_length: Optional[int] = None, + page_overlap_length: Optional[int] = None, + maximum_pages_to_take: Optional[int] = None, + unit: Optional[Union[str, "_models.SplitSkillUnit"]] = None, + azure_open_ai_tokenizer_parameters: Optional["_models.AzureOpenAITokenizerParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.SplitSkill" # type: ignore + + +class SqlIntegratedChangeTrackingPolicy( + DataChangeDetectionPolicy, discriminator="#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy" +): + """Defines a data change detection policy that captures changes using the Integrated Change + Tracking feature of Azure SQL Database. + + :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. + Default value is "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data change detection policy. Required. Default value is + \"#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy" # type: ignore + + +class StemmerOverrideTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StemmerOverrideTokenFilter"): + """Provides the ability to override other stemming filters with custom dictionary-based stemming. + Any dictionary-stemmed terms will be marked as keywords so that they will not be stemmed with + stemmers down the chain. Must be placed before any stemming filters. This token filter is + implemented using Apache Lucene. See + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.html + `_. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar rules: A list of stemming rules in the following format: "word => stem", for example: + "ran => run". Required. + :vartype rules: list[str] + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.StemmerOverrideTokenFilter". + :vartype odata_type: str + """ + + rules: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stemming rules in the following format: \"word => stem\", for example: \"ran => + run\". Required.""" + odata_type: Literal["#Microsoft.Azure.Search.StemmerOverrideTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.StemmerOverrideTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + rules: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StemmerOverrideTokenFilter" # type: ignore + + +class StemmerTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StemmerTokenFilter"): + """Language specific stemming filter. This token filter is implemented using Apache Lucene. See + `https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters + `_. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar language: The language to use. Required. Known values are: "arabic", "armenian", + "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "dutchKp", + "english", "lightEnglish", "minimalEnglish", "possessiveEnglish", "porter2", "lovins", + "finnish", "lightFinnish", "french", "lightFrench", "minimalFrench", "galician", + "minimalGalician", "german", "german2", "lightGerman", "minimalGerman", "greek", "hindi", + "hungarian", "lightHungarian", "indonesian", "irish", "italian", "lightItalian", "sorani", + "latvian", "norwegian", "lightNorwegian", "minimalNorwegian", "lightNynorsk", "minimalNynorsk", + "portuguese", "lightPortuguese", "minimalPortuguese", "portugueseRslp", "romanian", "russian", + "lightRussian", "spanish", "lightSpanish", "swedish", "lightSwedish", and "turkish". + :vartype language: str or ~azure.search.documents.indexes.models.StemmerTokenFilterLanguage + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.StemmerTokenFilter". + :vartype odata_type: str + """ + + language: Union[str, "_models.StemmerTokenFilterLanguage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. Required. Known values are: \"arabic\", \"armenian\", \"basque\", + \"brazilian\", \"bulgarian\", \"catalan\", \"czech\", \"danish\", \"dutch\", \"dutchKp\", + \"english\", \"lightEnglish\", \"minimalEnglish\", \"possessiveEnglish\", \"porter2\", + \"lovins\", \"finnish\", \"lightFinnish\", \"french\", \"lightFrench\", \"minimalFrench\", + \"galician\", \"minimalGalician\", \"german\", \"german2\", \"lightGerman\", \"minimalGerman\", + \"greek\", \"hindi\", \"hungarian\", \"lightHungarian\", \"indonesian\", \"irish\", + \"italian\", \"lightItalian\", \"sorani\", \"latvian\", \"norwegian\", \"lightNorwegian\", + \"minimalNorwegian\", \"lightNynorsk\", \"minimalNynorsk\", \"portuguese\", + \"lightPortuguese\", \"minimalPortuguese\", \"portugueseRslp\", \"romanian\", \"russian\", + \"lightRussian\", \"spanish\", \"lightSpanish\", \"swedish\", \"lightSwedish\", and + \"turkish\".""" + odata_type: Literal["#Microsoft.Azure.Search.StemmerTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.StemmerTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + language: Union[str, "_models.StemmerTokenFilterLanguage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StemmerTokenFilter" # type: ignore + + +class StopAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StopAnalyzer"): + """Divides text at non-letters; Applies the lowercase and stopword token filters. This analyzer is + implemented using Apache Lucene. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar stopwords: A list of stopwords. + :vartype stopwords: list[str] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.StopAnalyzer". + :vartype odata_type: str + """ + + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stopwords.""" + odata_type: Literal["#Microsoft.Azure.Search.StopAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.StopAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + stopwords: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StopAnalyzer" # type: ignore + + +class StopwordsTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StopwordsTokenFilter"): + """Removes stop words from a token stream. This token filter is implemented using Apache Lucene. + See + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html + `_. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar stopwords: The list of stopwords. This property and the stopwords list property cannot + both be set. + :vartype stopwords: list[str] + :ivar stopwords_list: A predefined list of stopwords to use. This property and the stopwords + property cannot both be set. Default is English. Known values are: "arabic", "armenian", + "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", + "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", + "irish", "italian", "latvian", "norwegian", "persian", "portuguese", "romanian", "russian", + "sorani", "spanish", "swedish", "thai", and "turkish". + :vartype stopwords_list: str or ~azure.search.documents.indexes.models.StopwordsList + :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted + to lower case first. Default is false. + :vartype ignore_case: bool + :ivar remove_trailing_stop_words: A value indicating whether to ignore the last search term if + it's a stop word. Default is true. + :vartype remove_trailing_stop_words: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.StopwordsTokenFilter". + :vartype odata_type: str + """ + + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of stopwords. This property and the stopwords list property cannot both be set.""" + stopwords_list: Optional[Union[str, "_models.StopwordsList"]] = rest_field( + name="stopwordsList", visibility=["read", "create", "update", "delete", "query"] + ) + """A predefined list of stopwords to use. This property and the stopwords property cannot both be + set. Default is English. Known values are: \"arabic\", \"armenian\", \"basque\", \"brazilian\", + \"bulgarian\", \"catalan\", \"czech\", \"danish\", \"dutch\", \"english\", \"finnish\", + \"french\", \"galician\", \"german\", \"greek\", \"hindi\", \"hungarian\", \"indonesian\", + \"irish\", \"italian\", \"latvian\", \"norwegian\", \"persian\", \"portuguese\", \"romanian\", + \"russian\", \"sorani\", \"spanish\", \"swedish\", \"thai\", and \"turkish\".""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to ignore case. If true, all words are converted to lower case + first. Default is false.""" + remove_trailing_stop_words: Optional[bool] = rest_field( + name="removeTrailing", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to ignore the last search term if it's a stop word. Default is true.""" + odata_type: Literal["#Microsoft.Azure.Search.StopwordsTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.StopwordsTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + stopwords: Optional[list[str]] = None, + stopwords_list: Optional[Union[str, "_models.StopwordsList"]] = None, + ignore_case: Optional[bool] = None, + remove_trailing_stop_words: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StopwordsTokenFilter" # type: ignore + + +class SynonymMap(_Model): + """Represents a synonym map definition. + + :ivar name: The name of the synonym map. Required. + :vartype name: str + :ivar format: The format of the synonym map. Only the 'solr' format is currently supported. + Required. Default value is "solr". + :vartype format: str + :ivar synonyms: A series of synonym rules in the specified synonym map format. The rules must + be separated by newlines. Required. + :vartype synonyms: list[str] + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your data when you + want full assurance that no one, not even Microsoft, can decrypt your data. Once you have + encrypted your data, it will always remain encrypted. The search service will ignore attempts + to set this property to null. You can change this property as needed if you want to rotate your + encryption key; Your data will be unaffected. Encryption with customer-managed keys is not + available for free search services, and is only available for paid services created on or after + January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar e_tag: The ETag of the synonym map. + :vartype e_tag: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the synonym map. Required.""" + format: Literal["solr"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The format of the synonym map. Only the 'solr' format is currently supported. Required. Default + value is \"solr\".""" + synonyms: list[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="newlineDelimited" + ) + """A series of synonym rules in the specified synonym map format. The rules must be separated by + newlines. Required.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your data when you want full assurance + that no one, not even Microsoft, can decrypt your data. Once you have encrypted your data, it + will always remain encrypted. The search service will ignore attempts to set this property to + null. You can change this property as needed if you want to rotate your encryption key; Your + data will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the synonym map.""" + + @overload + def __init__( + self, + *, + name: str, + synonyms: list[str], + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.format: Literal["solr"] = "solr" + + +class SynonymTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.SynonymTokenFilter"): + """Matches single or multi-word synonyms in a token stream. This token filter is implemented using + Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar synonyms: A list of synonyms in following one of two formats: 1. incredible, + unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced + with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma + separated list of equivalent words. Set the expand option to change how this list is + interpreted. Required. + :vartype synonyms: list[str] + :ivar ignore_case: A value indicating whether to case-fold input for matching. Default is + false. + :vartype ignore_case: bool + :ivar expand: A value indicating whether all words in the list of synonyms (if => notation is + not used) will map to one another. If true, all words in the list of synonyms (if => notation + is not used) will map to one another. The following list: incredible, unbelievable, fabulous, + amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, + unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, + fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => + incredible. Default is true. + :vartype expand: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.SynonymTokenFilter". + :vartype odata_type: str + """ + + synonyms: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of synonyms in following one of two formats: 1. incredible, unbelievable, fabulous => + amazing - all terms on the left side of => symbol will be replaced with all terms on its right + side; 2. incredible, unbelievable, fabulous, amazing - comma separated list of equivalent + words. Set the expand option to change how this list is interpreted. Required.""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to case-fold input for matching. Default is false.""" + expand: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether all words in the list of synonyms (if => notation is not used) will + map to one another. If true, all words in the list of synonyms (if => notation is not used) + will map to one another. The following list: incredible, unbelievable, fabulous, amazing is + equivalent to: incredible, unbelievable, fabulous, amazing => incredible, unbelievable, + fabulous, amazing. If false, the following list: incredible, unbelievable, fabulous, amazing + will be equivalent to: incredible, unbelievable, fabulous, amazing => incredible. Default is + true.""" + odata_type: Literal["#Microsoft.Azure.Search.SynonymTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.SynonymTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + synonyms: list[str], + ignore_case: Optional[bool] = None, + expand: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SynonymTokenFilter" # type: ignore + + +class TagScoringFunction(ScoringFunction, discriminator="tag"): + """Defines a function that boosts scores of documents with string values matching a given list of + tags. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the tag scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.TagScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is "tag". + :vartype type: str + """ + + parameters: "_models.TagScoringParameters" = rest_field( + name="tag", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the tag scoring function. Required.""" + type: Literal["tag"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"tag\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.TagScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "tag" # type: ignore + + +class TagScoringParameters(_Model): + """Provides parameter values to a tag scoring function. + + :ivar tags_parameter: The name of the parameter passed in search queries to specify the list of + tags to compare against the target field. Required. + :vartype tags_parameter: str + """ + + tags_parameter: str = rest_field(name="tagsParameter", visibility=["read", "create", "update", "delete", "query"]) + """The name of the parameter passed in search queries to specify the list of tags to compare + against the target field. Required.""" + + @overload + def __init__( + self, + *, + tags_parameter: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TextTranslationSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.TranslationSkill"): + """A skill to translate text from one language to another. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_to_language_code: The language code to translate documents into for documents + that don't specify the to language explicitly. Required. Known values are: "af", "ar", "bn", + "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", + "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", + "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", + "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", + "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", and "pa". + :vartype default_to_language_code: str or + ~azure.search.documents.indexes.models.TextTranslationSkillLanguage + :ivar default_from_language_code: The language code to translate documents from for documents + that don't specify the from language explicitly. Known values are: "af", "ar", "bn", "bs", + "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", "fi", + "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", + "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", + "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", + "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", and "pa". + :vartype default_from_language_code: str or + ~azure.search.documents.indexes.models.TextTranslationSkillLanguage + :ivar suggested_from: The language code to translate documents from when neither the + fromLanguageCode input nor the defaultFromLanguageCode parameter are provided, and the + automatic language detection is unsuccessful. Default is ``en``. Known values are: "af", "ar", + "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", + "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", + "tlh", "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", + "pt-br", "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", + "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", and "pa". + :vartype suggested_from: str or + ~azure.search.documents.indexes.models.TextTranslationSkillLanguage + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.TranslationSkill". + :vartype odata_type: str + """ + + default_to_language_code: Union[str, "_models.TextTranslationSkillLanguage"] = rest_field( + name="defaultToLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The language code to translate documents into for documents that don't specify the to language + explicitly. Required. Known values are: \"af\", \"ar\", \"bn\", \"bs\", \"bg\", \"yue\", + \"ca\", \"zh-Hans\", \"zh-Hant\", \"hr\", \"cs\", \"da\", \"nl\", \"en\", \"et\", \"fj\", + \"fil\", \"fi\", \"fr\", \"de\", \"el\", \"ht\", \"he\", \"hi\", \"mww\", \"hu\", \"is\", + \"id\", \"it\", \"ja\", \"sw\", \"tlh\", \"tlh-Latn\", \"tlh-Piqd\", \"ko\", \"lv\", \"lt\", + \"mg\", \"ms\", \"mt\", \"nb\", \"fa\", \"pl\", \"pt\", \"pt-br\", \"pt-PT\", \"otq\", \"ro\", + \"ru\", \"sm\", \"sr-Cyrl\", \"sr-Latn\", \"sk\", \"sl\", \"es\", \"sv\", \"ty\", \"ta\", + \"te\", \"th\", \"to\", \"tr\", \"uk\", \"ur\", \"vi\", \"cy\", \"yua\", \"ga\", \"kn\", + \"mi\", \"ml\", and \"pa\".""" + default_from_language_code: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = rest_field( + name="defaultFromLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The language code to translate documents from for documents that don't specify the from + language explicitly. Known values are: \"af\", \"ar\", \"bn\", \"bs\", \"bg\", \"yue\", \"ca\", + \"zh-Hans\", \"zh-Hant\", \"hr\", \"cs\", \"da\", \"nl\", \"en\", \"et\", \"fj\", \"fil\", + \"fi\", \"fr\", \"de\", \"el\", \"ht\", \"he\", \"hi\", \"mww\", \"hu\", \"is\", \"id\", + \"it\", \"ja\", \"sw\", \"tlh\", \"tlh-Latn\", \"tlh-Piqd\", \"ko\", \"lv\", \"lt\", \"mg\", + \"ms\", \"mt\", \"nb\", \"fa\", \"pl\", \"pt\", \"pt-br\", \"pt-PT\", \"otq\", \"ro\", \"ru\", + \"sm\", \"sr-Cyrl\", \"sr-Latn\", \"sk\", \"sl\", \"es\", \"sv\", \"ty\", \"ta\", \"te\", + \"th\", \"to\", \"tr\", \"uk\", \"ur\", \"vi\", \"cy\", \"yua\", \"ga\", \"kn\", \"mi\", + \"ml\", and \"pa\".""" + suggested_from: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = rest_field( + name="suggestedFrom", visibility=["read", "create", "update", "delete", "query"] + ) + """The language code to translate documents from when neither the fromLanguageCode input nor the + defaultFromLanguageCode parameter are provided, and the automatic language detection is + unsuccessful. Default is ``en``. Known values are: \"af\", \"ar\", \"bn\", \"bs\", \"bg\", + \"yue\", \"ca\", \"zh-Hans\", \"zh-Hant\", \"hr\", \"cs\", \"da\", \"nl\", \"en\", \"et\", + \"fj\", \"fil\", \"fi\", \"fr\", \"de\", \"el\", \"ht\", \"he\", \"hi\", \"mww\", \"hu\", + \"is\", \"id\", \"it\", \"ja\", \"sw\", \"tlh\", \"tlh-Latn\", \"tlh-Piqd\", \"ko\", \"lv\", + \"lt\", \"mg\", \"ms\", \"mt\", \"nb\", \"fa\", \"pl\", \"pt\", \"pt-br\", \"pt-PT\", \"otq\", + \"ro\", \"ru\", \"sm\", \"sr-Cyrl\", \"sr-Latn\", \"sk\", \"sl\", \"es\", \"sv\", \"ty\", + \"ta\", \"te\", \"th\", \"to\", \"tr\", \"uk\", \"ur\", \"vi\", \"cy\", \"yua\", \"ga\", + \"kn\", \"mi\", \"ml\", and \"pa\".""" + odata_type: Literal["#Microsoft.Skills.Text.TranslationSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.TranslationSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + default_to_language_code: Union[str, "_models.TextTranslationSkillLanguage"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_from_language_code: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, + suggested_from: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.TranslationSkill" # type: ignore + + +class TextWeights(_Model): + """Defines weights on index fields for which matches should boost scoring in search queries. + + :ivar weights: The dictionary of per-field weights to boost document scoring. The keys are + field names and the values are the weights for each field. Required. + :vartype weights: dict[str, float] + """ + + weights: dict[str, float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The dictionary of per-field weights to boost document scoring. The keys are field names and the + values are the weights for each field. Required.""" + + @overload + def __init__( + self, + *, + weights: dict[str, float], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TruncateTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.TruncateTokenFilter"): + """Truncates the terms to a specific length. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar length: The length at which terms will be truncated. Default and maximum is 300. + :vartype length: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.TruncateTokenFilter". + :vartype odata_type: str + """ + + length: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The length at which terms will be truncated. Default and maximum is 300.""" + odata_type: Literal["#Microsoft.Azure.Search.TruncateTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.TruncateTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.TruncateTokenFilter" # type: ignore + + +class UaxUrlEmailTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.UaxUrlEmailTokenizer"): + """Tokenizes urls and emails as one token. This tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.UaxUrlEmailTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.UaxUrlEmailTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.UaxUrlEmailTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer" # type: ignore + + +class UniqueTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.UniqueTokenFilter"): + """Filters out tokens with same text as the previous token. This token filter is implemented using + Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar only_on_same_position: A value indicating whether to remove duplicates only at the same + position. Default is false. + :vartype only_on_same_position: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.UniqueTokenFilter". + :vartype odata_type: str + """ + + only_on_same_position: Optional[bool] = rest_field( + name="onlyOnSamePosition", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to remove duplicates only at the same position. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.UniqueTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.UniqueTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + only_on_same_position: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.UniqueTokenFilter" # type: ignore + + +class VectorSearch(_Model): + """Contains configuration options related to vector search. + + :ivar profiles: Defines combinations of configurations to use with vector search. + :vartype profiles: list[~azure.search.documents.indexes.models.VectorSearchProfile] + :ivar algorithms: Contains configuration options specific to the algorithm used during indexing + or querying. + :vartype algorithms: + list[~azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration] + :ivar vectorizers: Contains configuration options on how to vectorize text vector queries. + :vartype vectorizers: list[~azure.search.documents.indexes.models.VectorSearchVectorizer] + :ivar compressions: Contains configuration options specific to the compression method used + during indexing or querying. + :vartype compressions: list[~azure.search.documents.indexes.models.VectorSearchCompression] + """ + + profiles: Optional[list["_models.VectorSearchProfile"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Defines combinations of configurations to use with vector search.""" + algorithms: Optional[list["_models.VectorSearchAlgorithmConfiguration"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options specific to the algorithm used during indexing or querying.""" + vectorizers: Optional[list["_models.VectorSearchVectorizer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options on how to vectorize text vector queries.""" + compressions: Optional[list["_models.VectorSearchCompression"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options specific to the compression method used during indexing or + querying.""" + + @overload + def __init__( + self, + *, + profiles: Optional[list["_models.VectorSearchProfile"]] = None, + algorithms: Optional[list["_models.VectorSearchAlgorithmConfiguration"]] = None, + vectorizers: Optional[list["_models.VectorSearchVectorizer"]] = None, + compressions: Optional[list["_models.VectorSearchCompression"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorSearchProfile(_Model): + """Defines a combination of configurations to use with vector search. + + :ivar name: The name to associate with this particular vector search profile. Required. + :vartype name: str + :ivar algorithm_configuration_name: The name of the vector search algorithm configuration that + specifies the algorithm and optional parameters. Required. + :vartype algorithm_configuration_name: str + :ivar vectorizer_name: The name of the vectorization being configured for use with vector + search. + :vartype vectorizer_name: str + :ivar compression_name: The name of the compression method configuration that specifies the + compression method and optional parameters. + :vartype compression_name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular vector search profile. Required.""" + algorithm_configuration_name: str = rest_field( + name="algorithm", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the vector search algorithm configuration that specifies the algorithm and optional + parameters. Required.""" + vectorizer_name: Optional[str] = rest_field( + name="vectorizer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the vectorization being configured for use with vector search.""" + compression_name: Optional[str] = rest_field( + name="compression", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the compression method configuration that specifies the compression method and + optional parameters.""" + + @overload + def __init__( + self, + *, + name: str, + algorithm_configuration_name: str, + vectorizer_name: Optional[str] = None, + compression_name: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VisionVectorizeSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Vision.VectorizeSkill"): + """Allows you to generate a vector embedding for a given image or text input using the Azure AI + Services Vision Vectorize API. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar model_version: The version of the model to use when calling the AI Services Vision + service. It will default to the latest available when not specified. Required. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Vision.VectorizeSkill". :vartype odata_type: str + """ + + model_version: str = rest_field(name="modelVersion", visibility=["read", "create", "update", "delete", "query"]) + """The version of the model to use when calling the AI Services Vision service. It will default to + the latest available when not specified. Required.""" + odata_type: Literal["#Microsoft.Skills.Vision.VectorizeSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Vision.VectorizeSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + model_version: str, + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Vision.VectorizeSkill" # type: ignore + + +class WebApiHttpHeaders(_Model): + """A dictionary of http request headers.""" + + +class WebApiSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.WebApiSkill"): + """A skill that can call a Web API endpoint, allowing you to extend a skillset by having it call + your custom code. + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill with no name defined will be given a default name of its 1-based index in the skills array, prefixed with the character '#'. @@ -360,1082 +11617,499 @@ class SentimentSkill(SearchIndexerSkill): :ivar outputs: The output of a skill is either a field in a search index, or a value that can be consumed as an input by another skill. Required. :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", "ru", - "es", "sv", and "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.SentimentSkillLanguage - :ivar skill_version: The version of the skill to use when calling the Text Analytics service. - It will default to V1 when not specified. - :vartype skill_version: ~azure.search.documents.indexes.models.SentimentSkillVersion - :ivar include_opinion_mining: If set to true, the skill output will include information from - Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated - assessment (adjective) in the text. Default is false. Only used when ``skill_version`` is V3. - :vartype include_opinion_mining: bool - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str + :ivar uri: The url for the Web API. Required. + :vartype uri: str + :ivar http_headers: The headers required to make the http request. + :vartype http_headers: ~azure.search.documents.indexes.models.WebApiHttpHeaders + :ivar http_method: The method for the http request. + :vartype http_method: str + :ivar timeout: The desired timeout for the request. Default is 30 seconds. + :vartype timeout: ~datetime.timedelta + :ivar batch_size: The desired batch size which indicates number of documents. + :vartype batch_size: int + :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web + API. + :vartype degree_of_parallelism: int + :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure + function or some other application that provides the transformations. This value should be the + application ID created for the function or app when it was registered with Azure Active + Directory. When specified, the custom skill connects to the function or app using a managed ID + (either system or user-assigned) of the search service and the access token of the function or + app, using this value as the resource id for creating the scope of the access token. + :vartype auth_resource_id: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. + If set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Custom.WebApiSkill". + :vartype odata_type: str """ - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_opinion_mining": {"key": "includeOpinionMining", "type": "bool"}, - "model_version": {"key": "modelVersion", "type": "str"}, - "skill_version": {"key": "skillVersion", "type": "str"}, - } - - def __init__(self, **kwargs): - # pop skill_version from kwargs to avoid warning in msrest - skill_version = kwargs.pop("skill_version", SentimentSkillVersion.V3) - - super(SentimentSkill, self).__init__(**kwargs) - self.skill_version = skill_version - self.odata_type = self.skill_version - self.default_language_code = kwargs.get("default_language_code", None) - self.include_opinion_mining = kwargs.get("include_opinion_mining", None) - self.model_version = kwargs.get("model_version", None) - - def _to_generated(self): - if self.skill_version in [ - SentimentSkillVersion.V3, - SentimentSkillVersion.LATEST, - ]: - return _SentimentSkillV3( - inputs=self.inputs, - outputs=self.outputs, - name=self.name, - description=self.description, - context=self.context, - odata_type=self.odata_type, - default_language_code=self.default_language_code, - include_opinion_mining=self.include_opinion_mining, - model_version=self.model_version, - ) - return None - - @classmethod - def _from_generated(cls, skill): - if not skill: - return None - kwargs = skill.as_dict() - if isinstance(skill, _SentimentSkillV3): - return SentimentSkill(skill_version=SentimentSkillVersion.V3, **kwargs) - return None - - -class AnalyzeTextOptions(_serialization.Model): - """Specifies some text and analysis components used to break that text into tokens.""" - + uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url for the Web API. Required.""" + http_headers: Optional["_models.WebApiHttpHeaders"] = rest_field( + name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """The headers required to make the http request.""" + http_method: Optional[str] = rest_field( + name="httpMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The method for the http request.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The desired timeout for the request. Default is 30 seconds.""" + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) + """The desired batch size which indicates number of documents.""" + degree_of_parallelism: Optional[int] = rest_field( + name="degreeOfParallelism", visibility=["read", "create", "update", "delete", "query"] + ) + """If set, the number of parallel calls that can be made to the Web API.""" + auth_resource_id: Optional[str] = rest_field( + name="authResourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """Applies to custom skills that connect to external code in an Azure function or some other + application that provides the transformations. This value should be the application ID created + for the function or app when it was registered with Azure Active Directory. When specified, the + custom skill connects to the function or app using a managed ID (either system or + user-assigned) of the search service and the access token of the function or app, using this + value as the resource id for creating the scope of the access token.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", + the value of this property is cleared.""" + odata_type: Literal["#Microsoft.Skills.Custom.WebApiSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Custom.WebApiSkill\".""" + + @overload def __init__( self, *, - text: str, - analyzer_name: Optional[str] = None, - tokenizer_name: Optional[str] = None, - normalizer_name: Optional[str] = None, - token_filters: Optional[List[str]] = None, - char_filters: Optional[List[str]] = None, - **kwargs - ): - """ - :keyword text: Required. The text to break into tokens. - :paramtype text: str - :keyword analyzer_name: The name of the analyzer to use to break the given text. If this parameter is - not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are - mutually exclusive. Possible values include: "ar.microsoft", "ar.lucene", "hy.lucene", - "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh- - Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", - "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", - "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", - "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", - "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", - "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", - "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", - "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", - "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt- - PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", - "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", - "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", - "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", - "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", - "simple", "stop", "whitespace". - :paramtype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword tokenizer_name: The name of the tokenizer to use to break the given text. If this parameter - is not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters - are mutually exclusive. Possible values include: "classic", "edgeNGram", "keyword_v2", - "letter", "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", - "nGram", "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", "whitespace". - :paramtype tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :keyword token_filters: An optional list of token filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :paramtype token_filters: list[str] or list[~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: An optional list of character filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :paramtype char_filters: list[str] - """ - super().__init__(**kwargs) - self.text = text - self.analyzer_name = analyzer_name - self.tokenizer_name = tokenizer_name - self.normalizer_name = normalizer_name - self.token_filters = token_filters - self.char_filters = char_filters - - def _to_analyze_request(self): - return AnalyzeRequest( - text=self.text, - analyzer=self.analyzer_name, - tokenizer=self.tokenizer_name, - normalizer=self.normalizer_name, - token_filters=self.token_filters, - char_filters=self.char_filters, - ) - - @classmethod - def _from_analyze_request(cls, analyze_request) -> Optional[Self]: - if not analyze_request: - return None - return cls( - text=analyze_request.text, - analyzer_name=analyze_request.analyzer, - tokenizer_name=analyze_request.tokenizer, - normalizer_name=analyze_request.normalizer, - token_filters=analyze_request.token_filters, - char_filters=analyze_request.char_filters, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_analyze_request().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a AnalyzeTextOptions instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A AnalyzeTextOptions instance - :rtype: AnalyzeTextOptions - :raises DeserializationError: if something went wrong - """ - return cls._from_analyze_request(AnalyzeRequest.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_analyze_request().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A AnalyzeTextOptions instance - :rtype: AnalyzeTextOptions - :raises DeserializationError: if something went wrong - """ - return cls._from_analyze_request( - AnalyzeRequest.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class CustomAnalyzer(LexicalAnalyzer): - """Allows you to take control over the process of converting text into indexable/searchable - tokens. It's a user-defined configuration consisting of a single predefined tokenizer and one - or more filters. The tokenizer is responsible for breaking text into tokens, and the filters - for modifying tokens emitted by the tokenizer. + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + uri: str, + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + http_headers: Optional["_models.WebApiHttpHeaders"] = None, + http_method: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + batch_size: Optional[int] = None, + degree_of_parallelism: Optional[int] = None, + auth_resource_id: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ - All required parameters must be populated in order to send to server. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.WebApiSkill" # type: ignore - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar tokenizer_name: The name of the tokenizer to use to divide continuous text into a sequence - of tokens, such as breaking a sentence into words. Required. Known values are: "classic", - "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", - "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", - "standard_v2", "uax_url_email", and "whitespace". - :vartype tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar token_filters: A list of token filters used to filter out or modify the tokens generated - by a tokenizer. For example, you can specify a lowercase filter that converts all characters to - lowercase. The filters are run in the order in which they are listed. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: A list of character filters used to prepare input text before it is - processed by the tokenizer. For instance, they can replace certain characters or symbols. The - filters are run in the order in which they are listed. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + +class WebApiVectorizer(VectorSearchVectorizer, discriminator="customWebApi"): + """Specifies a user-defined vectorizer for generating the vector embedding of a query string. + Integration of an external vectorizer is achieved using the custom Web API interface of a + skillset. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar web_api_parameters: Specifies the properties of the user-defined vectorizer. + :vartype web_api_parameters: ~azure.search.documents.indexes.models.WebApiVectorizerParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings using a custom web endpoint at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.CUSTOM_WEB_API """ - def __init__(self, **kwargs): - super(CustomAnalyzer, self).__init__(**kwargs) - self.odata_type = "#Microsoft.Azure.Search.CustomAnalyzer" - self.tokenizer_name = kwargs["tokenizer_name"] - self.token_filters = kwargs.get("token_filters", None) - self.char_filters = kwargs.get("char_filters", None) - - def _to_generated(self): - return _CustomAnalyzer( - name=self.name, - odata_type=self.odata_type, - tokenizer=self.tokenizer_name, - token_filters=self.token_filters, - char_filters=self.char_filters, - ) - - @classmethod - def _from_generated(cls, custom_analyzer): - if not custom_analyzer: - return None - return cls( - name=custom_analyzer.name, - odata_type=custom_analyzer.odata_type, - tokenizer_name=custom_analyzer.tokenizer, - token_filters=custom_analyzer.token_filters, - char_filters=custom_analyzer.char_filters, - ) - - -class PatternAnalyzer(LexicalAnalyzer): - """Flexibly separates text into terms via a regular expression pattern. This analyzer is - implemented using Apache Lucene. + web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = rest_field( + name="customWebApiParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the properties of the user-defined vectorizer.""" + kind: Literal[VectorSearchVectorizerKind.CUSTOM_WEB_API] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings using a custom web endpoint at query time.""" - All required parameters must be populated in order to send to server. + @overload + def __init__( + self, + *, + vectorizer_name: str, + web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = None, + ) -> None: ... - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar lower_case_terms: A value indicating whether terms should be lower-cased. Default is - true. - :vartype lower_case_terms: bool - :ivar pattern: A regular expression pattern to match token separators. Default is an expression - that matches one or more non-word characters. - :vartype pattern: str - :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :vartype flags: list[str or ~azure.search.documents.indexes.models.RegexFlags] - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.CUSTOM_WEB_API # type: ignore + + +class WebApiVectorizerParameters(_Model): + """Specifies the properties for connecting to a user-defined vectorizer. + + :ivar url: The URI of the Web API providing the vectorizer. + :vartype url: str + :ivar http_headers: The headers required to make the HTTP request. + :vartype http_headers: dict[str, str] + :ivar http_method: The method for the HTTP request. + :vartype http_method: str + :ivar timeout: The desired timeout for the request. Default is 30 seconds. + :vartype timeout: ~datetime.timedelta + :ivar auth_resource_id: Applies to custom endpoints that connect to external code in an Azure + function or some other application that provides the transformations. This value should be the + application ID created for the function or app when it was registered with Azure Active + Directory. When specified, the vectorization connects to the function or app using a managed ID + (either system or user-assigned) of the search service and the access token of the function or + app, using this value as the resource id for creating the scope of the access token. + :vartype auth_resource_id: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. + If set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity """ - _validation = {"odata_type": {"required": True}, "name": {"required": True}} - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "lower_case_terms": {"key": "lowercase", "type": "bool"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "[str]"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__(self, **kwargs): - super(PatternAnalyzer, self).__init__(**kwargs) - self.odata_type = "#Microsoft.Azure.Search.PatternAnalyzer" - self.lower_case_terms = kwargs.get("lower_case_terms", True) - self.pattern = kwargs.get("pattern", r"\W+") - self.flags = kwargs.get("flags", None) - self.stopwords = kwargs.get("stopwords", None) - - def _to_generated(self): - if not self.flags: - flags = None - else: - flags = DELIMITER.join(self.flags) - return _PatternAnalyzer( - name=self.name, - lower_case_terms=self.lower_case_terms, - pattern=self.pattern, - flags=flags, - stopwords=self.stopwords, - ) - - @classmethod - def _from_generated(cls, pattern_analyzer): - if not pattern_analyzer: - return None - if not pattern_analyzer.flags: - flags = None - else: - flags = pattern_analyzer.flags.split(DELIMITER) - return cls( - name=pattern_analyzer.name, - lower_case_terms=pattern_analyzer.lower_case_terms, - pattern=pattern_analyzer.pattern, - flags=flags, - stopwords=pattern_analyzer.stopwords, - ) + url: Optional[str] = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) + """The URI of the Web API providing the vectorizer.""" + http_headers: Optional[dict[str, str]] = rest_field( + name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """The headers required to make the HTTP request.""" + http_method: Optional[str] = rest_field( + name="httpMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The method for the HTTP request.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The desired timeout for the request. Default is 30 seconds.""" + auth_resource_id: Optional[str] = rest_field( + name="authResourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """Applies to custom endpoints that connect to external code in an Azure function or some other + application that provides the transformations. This value should be the application ID created + for the function or app when it was registered with Azure Active Directory. When specified, the + vectorization connects to the function or app using a managed ID (either system or + user-assigned) of the search service and the access token of the function or app, using this + value as the resource id for creating the scope of the access token.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", + the value of this property is cleared.""" + + @overload + def __init__( + self, + *, + url: Optional[str] = None, + http_headers: Optional[dict[str, str]] = None, + http_method: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + auth_resource_id: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class PatternTokenizer(LexicalTokenizer): - """Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is - implemented using Apache Lucene. - All required parameters must be populated in order to send to server. +class WebKnowledgeSource(KnowledgeSource, discriminator="web"): + """Knowledge Source targeting web results. - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. + :ivar name: The name of the knowledge source. Required. :vartype name: str - :ivar pattern: A regular expression pattern to match token separators. Default is an expression - that matches one or more non-word characters. - :vartype pattern: str - :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :vartype flags: list[str or ~azure.search.documents.indexes.models.RegexFlags] - :ivar group: The zero-based ordinal of the matching group in the regular expression pattern to - extract into tokens. Use -1 if you want to use the entire pattern to split the input into - tokens, irrespective of matching groups. Default is -1. - :vartype group: int + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the knowledge source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that reads data from the web. + :vartype kind: str or ~azure.search.documents.indexes.models.WEB + :ivar web_parameters: The parameters for the web knowledge source. + :vartype web_parameters: ~azure.search.documents.indexes.models.WebKnowledgeSourceParameters """ - _validation = {"odata_type": {"required": True}, "name": {"required": True}} + kind: Literal[KnowledgeSourceKind.WEB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that reads data from the web.""" + web_parameters: Optional["_models.WebKnowledgeSourceParameters"] = rest_field( + name="webParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The parameters for the web knowledge source.""" - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "[str]"}, - "group": {"key": "group", "type": "int"}, - } - - def __init__(self, **kwargs): - super(PatternTokenizer, self).__init__(**kwargs) - self.odata_type = "#Microsoft.Azure.Search.PatternTokenizer" - self.pattern = kwargs.get("pattern", r"\W+") - self.flags = kwargs.get("flags", None) - self.group = kwargs.get("group", -1) + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + web_parameters: Optional["_models.WebKnowledgeSourceParameters"] = None, + ) -> None: ... - def _to_generated(self): - if not self.flags: - flags = None - else: - flags = DELIMITER.join(self.flags) - return _PatternTokenizer( - name=self.name, - pattern=self.pattern, - flags=flags, - group=self.group, - ) - - @classmethod - def _from_generated(cls, pattern_tokenizer): - if not pattern_tokenizer: - return None - if not pattern_tokenizer.flags: - flags = None - else: - flags = pattern_tokenizer.flags.split(DELIMITER) - return cls( - name=pattern_tokenizer.name, - pattern=pattern_tokenizer.pattern, - flags=flags, - group=pattern_tokenizer.group, - ) + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.WEB # type: ignore -class SearchResourceEncryptionKey(_serialization.Model): - """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be - used to encrypt or decrypt data-at-rest, such as indexes and synonym maps. - All required parameters must be populated in order to send to server. +class WebKnowledgeSourceDomain(_Model): + """Configuration for web knowledge source domain. - :ivar key_name: The name of your Azure Key Vault key to be used to encrypt your data at rest. - Required. - :vartype key_name: str - :ivar key_version: The version of your Azure Key Vault key to be used to encrypt your data at - rest. - :vartype key_version: str - :ivar vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that contains - the key to be used to encrypt your data at rest. An example URI might be - ``https://my-keyvault-name.vault.azure.net``. Required. - :vartype vault_uri: str - :ivar application_id: Optional Azure Active Directory application ID used to construct access - credentials. Supply this together with ``application_secret`` instead of ``access_credentials``. - :vartype application_id: str - :ivar application_secret: The authentication key of the specified AAD application. Used with - ``application_id`` to populate access credentials. - :vartype application_secret: str - :ivar identity: An explicit managed identity to use for this encryption key. If not specified - and the access credentials property is null, the system-assigned managed identity is used. On - update to the resource, if the explicit identity is unspecified, it remains unchanged. If - "none" is specified, the value of this property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar address: The address of the domain. Required. + :vartype address: str + :ivar include_subpages: Whether or not to include subpages from this domain. + :vartype include_subpages: bool """ + address: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The address of the domain. Required.""" + include_subpages: Optional[bool] = rest_field( + name="includeSubpages", visibility=["read", "create", "update", "delete", "query"] + ) + """Whether or not to include subpages from this domain.""" + + @overload def __init__( self, *, - key_name: str, - key_version: str, - vault_uri: str, - application_id: Optional[str] = None, - application_secret: Optional[str] = None, - identity: Optional[SearchIndexerDataIdentity] = None, - **kwargs - ): - super().__init__(**kwargs) - self.key_name = key_name - self.key_version = key_version - self.vault_uri = vault_uri - self.application_id = application_id - self.application_secret = application_secret - self.identity = identity - - def _to_generated(self): - if self.application_id and self.application_secret: - access_credentials = AzureActiveDirectoryApplicationCredentials( - application_id=self.application_id, - application_secret=self.application_secret, - ) - else: - access_credentials = None - return _SearchResourceEncryptionKey( - key_name=self.key_name, - key_version=self.key_version, - vault_uri=self.vault_uri, - access_credentials=access_credentials, - identity=self.identity, - ) - - @classmethod - def _from_generated(cls, search_resource_encryption_key) -> Optional[Self]: - if not search_resource_encryption_key: - return None - if search_resource_encryption_key.access_credentials: - application_id = search_resource_encryption_key.access_credentials.application_id - application_secret = search_resource_encryption_key.access_credentials.application_secret - else: - application_id = None - application_secret = None - return cls( - key_name=search_resource_encryption_key.key_name, - key_version=search_resource_encryption_key.key_version, - vault_uri=search_resource_encryption_key.vault_uri, - application_id=application_id, - application_secret=application_secret, - identity=search_resource_encryption_key.identity, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchResourceEncryptionKey instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchResourceEncryptionKey instance - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( # type: ignore - _SearchResourceEncryptionKey.deserialize(data, content_type=content_type) - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchResourceEncryptionKey instance - :rtype: SearchResourceEncryptionKey - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchResourceEncryptionKey.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class SynonymMap(_serialization.Model): - """Represents a synonym map definition. + address: str, + include_subpages: Optional[bool] = None, + ) -> None: ... - Variables are only populated by the server, and will be ignored when sending a request. + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ - All required parameters must be populated in order to send to server. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) - :ivar name: The name of the synonym map. Required. - :vartype name: str - :ivar format: The format of the synonym map. Only the 'solr' format is currently supported. - Required. Default value is "solr". - :vartype format: str - :ivar synonyms: A series of synonym rules in the specified synonym map format. The rules must - be separated by newlines. Required. - :vartype synonyms: list[str] - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar e_tag: The ETag of the synonym map. - :vartype e_tag: str + +class WebKnowledgeSourceDomains(_Model): + """Domain allow/block configuration for web knowledge source. + + :ivar allowed_domains: Domains that are allowed for web results. + :vartype allowed_domains: list[~azure.search.documents.indexes.models.WebKnowledgeSourceDomain] + :ivar blocked_domains: Domains that are blocked from web results. + :vartype blocked_domains: list[~azure.search.documents.indexes.models.WebKnowledgeSourceDomain] """ - format = "solr" + allowed_domains: Optional[list["_models.WebKnowledgeSourceDomain"]] = rest_field( + name="allowedDomains", visibility=["read", "create", "update", "delete", "query"] + ) + """Domains that are allowed for web results.""" + blocked_domains: Optional[list["_models.WebKnowledgeSourceDomain"]] = rest_field( + name="blockedDomains", visibility=["read", "create", "update", "delete", "query"] + ) + """Domains that are blocked from web results.""" + @overload def __init__( self, *, - name: str, - synonyms: List[str], - encryption_key: Optional[SearchResourceEncryptionKey] = None, - e_tag: Optional[str] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.synonyms = synonyms - self.encryption_key = encryption_key - self.e_tag = e_tag - - def _to_generated(self): - return _SynonymMap( - name=self.name, - synonyms="\n".join(self.synonyms), - encryption_key=( - self.encryption_key._to_generated() if self.encryption_key else None # pylint:disable=protected-access - ), - e_tag=self.e_tag, - ) - - @classmethod - def _from_generated(cls, synonym_map) -> Optional[Self]: - if not synonym_map: - return None - return cls( - name=synonym_map.name, - synonyms=synonym_map.synonyms.split("\n"), - # pylint:disable=protected-access - encryption_key=SearchResourceEncryptionKey._from_generated(synonym_map.encryption_key), - e_tag=synonym_map.e_tag, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SynonymMap instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SynonymMap instance - :rtype: SynonymMap - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SynonymMap.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SynonymMap instance - :rtype: SynonymMap - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SynonymMap.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class SearchIndexerDataSourceConnection(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Represents a datasource connection definition, which can be used to configure an indexer. - - All required parameters must be populated in order to send to Azure. - - :ivar name: Required. The name of the datasource connection. - :vartype name: str - :ivar description: The description of the datasource connection. - :vartype description: str - :ivar type: Required. The type of the datasource connection. Possible values include: "azuresql", - "cosmosdb", "azureblob", "azuretable", "mysql", "adlsgen2", "onelake", "sharepoint". - :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :ivar connection_string: The connection string for the datasource connection. - :vartype connection_string: str - :ivar container: Required. The data container for the datasource connection. - :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :ivar identity: An explicit managed identity to use for this datasource. If not specified and - the connection string is a managed identity, the system-assigned managed identity is used. If - not specified, the value remains unchanged. If "none" is specified, the value of this property - is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar indexer_permission_options: Ingestion options with various types of permission data. - :vartype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :ivar data_change_detection_policy: The data change detection policy for the datasource connection. - :vartype data_change_detection_policy: ~azure.search.documents.models.DataChangeDetectionPolicy - :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource connection. - :vartype data_deletion_detection_policy: - ~azure.search.documents.models.DataDeletionDetectionPolicy - :ivar e_tag: The ETag of the data source. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition in Azure Cognitive Search. Once you have encrypted your data source - definition, it will always remain encrypted. Azure Cognitive Search will ignore attempts to set - this property to null. You can change this property as needed if you want to rotate your - encryption key; Your datasource definition will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + allowed_domains: Optional[list["_models.WebKnowledgeSourceDomain"]] = None, + blocked_domains: Optional[list["_models.WebKnowledgeSourceDomain"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class WebKnowledgeSourceParameters(_Model): + """Parameters for web knowledge source. + + :ivar domains: Domain allow/block configuration for web results. + :vartype domains: ~azure.search.documents.indexes.models.WebKnowledgeSourceDomains """ + domains: Optional["_models.WebKnowledgeSourceDomains"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Domain allow/block configuration for web results.""" + + @overload def __init__( self, *, - name: str, - description: Optional[str] = None, - type: str, - connection_string: str, - container: SearchIndexerDataContainer, - identity: Optional[SearchIndexerDataIdentity] = None, - indexer_permission_options: Optional[List[Union[str, IndexerPermissionOption]]] = None, - data_change_detection_policy: Optional[DataChangeDetectionPolicy] = None, - data_deletion_detection_policy: Optional[DataDeletionDetectionPolicy] = None, - e_tag: Optional[str] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.description = description - self.type = type - self.connection_string = connection_string - self.container = container - self.identity = identity - self.indexer_permission_options = indexer_permission_options - self.data_change_detection_policy = data_change_detection_policy - self.data_deletion_detection_policy = data_deletion_detection_policy - self.e_tag = e_tag - self.encryption_key = encryption_key - - def _to_generated(self): - if self.connection_string is None or self.connection_string == "": - connection_string = "" - else: - connection_string = self.connection_string - credentials = DataSourceCredentials(connection_string=connection_string) - return _SearchIndexerDataSource( - name=self.name, - description=self.description, - type=self.type, - credentials=credentials, - container=self.container, - data_change_detection_policy=self.data_change_detection_policy, - data_deletion_detection_policy=self.data_deletion_detection_policy, - e_tag=self.e_tag, - encryption_key=( - self.encryption_key._to_generated() if self.encryption_key else None # pylint: disable=protected-access - ), - identity=self.identity, - indexer_permission_options=self.indexer_permission_options, - ) - - @classmethod - def _from_generated(cls, search_indexer_data_source) -> Optional[Self]: - if not search_indexer_data_source: - return None - connection_string = ( - search_indexer_data_source.credentials.connection_string if search_indexer_data_source.credentials else "" - ) - return cls( - name=search_indexer_data_source.name, - description=search_indexer_data_source.description, - type=search_indexer_data_source.type, - connection_string=connection_string, - container=search_indexer_data_source.container, - data_change_detection_policy=search_indexer_data_source.data_change_detection_policy, - data_deletion_detection_policy=search_indexer_data_source.data_deletion_detection_policy, - e_tag=search_indexer_data_source.e_tag, - encryption_key=( - SearchResourceEncryptionKey._from_generated( # pylint: disable=protected-access - search_indexer_data_source.encryption_key - ) - if search_indexer_data_source.encryption_key - else None - ), - identity=search_indexer_data_source.identity, - indexer_permission_options=search_indexer_data_source.indexer_permission_options, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndexerDataSourceConnection instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerDataSourceConnection instance - :rtype: SearchIndexerDataSourceConnection - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndexerDataSource.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerDataSourceConnection instance - :rtype: SearchIndexerDataSourceConnection - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchIndexerDataSource.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -def pack_analyzer(analyzer): - if not analyzer: - return None - if isinstance(analyzer, (PatternAnalyzer, CustomAnalyzer)): - return analyzer._to_generated() # pylint:disable=protected-access - return analyzer - - -def unpack_analyzer(analyzer): - if not analyzer: - return None - if isinstance(analyzer, _PatternAnalyzer): - return PatternAnalyzer._from_generated(analyzer) # pylint:disable=protected-access - if isinstance(analyzer, _CustomAnalyzer): - return CustomAnalyzer._from_generated(analyzer) # pylint:disable=protected-access - return analyzer - - -class SearchIndexer(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Represents an indexer. + domains: Optional["_models.WebKnowledgeSourceDomains"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ - All required parameters must be populated in order to send to server. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) - :ivar name: The name of the indexer. Required. + +class WordDelimiterTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.WordDelimiterTokenFilter"): + """Splits words into subwords and performs optional transformations on subword groups. This token + filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. :vartype name: str - :ivar description: The description of the indexer. - :vartype description: str - :ivar data_source_name: The name of the datasource from which this indexer reads data. - Required. - :vartype data_source_name: str - :ivar skillset_name: The name of the skillset executing with this indexer. - :vartype skillset_name: str - :ivar target_index_name: The name of the index to which this indexer writes data. Required. - :vartype target_index_name: str - :ivar schedule: The schedule for this indexer. - :vartype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :ivar parameters: Parameters for indexer execution. - :vartype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :ivar field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :vartype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar output_field_mappings: Output field mappings are applied after enrichment and immediately - before indexing. - :vartype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar is_disabled: A value indicating whether the indexer is disabled. Default is false. - :vartype is_disabled: bool - :ivar e_tag: The ETag of the indexer. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar cache: Adds caching to an enrichment pipeline to allow for incremental modification steps - without having to rebuild the index every time. - :vartype cache: ~azure.search.documents.indexes.models.SearchIndexerCache + :ivar generate_word_parts: A value indicating whether to generate part words. If set, causes + parts of words to be generated; for example "AzureSearch" becomes "Azure" "Search". Default is + true. + :vartype generate_word_parts: bool + :ivar generate_number_parts: A value indicating whether to generate number subwords. Default is + true. + :vartype generate_number_parts: bool + :ivar catenate_words: A value indicating whether maximum runs of word parts will be catenated. + For example, if this is set to true, "Azure-Search" becomes "AzureSearch". Default is false. + :vartype catenate_words: bool + :ivar catenate_numbers: A value indicating whether maximum runs of number parts will be + catenated. For example, if this is set to true, "1-2" becomes "12". Default is false. + :vartype catenate_numbers: bool + :ivar catenate_all: A value indicating whether all subword parts will be catenated. For + example, if this is set to true, "Azure-Search-1" becomes "AzureSearch1". Default is false. + :vartype catenate_all: bool + :ivar split_on_case_change: A value indicating whether to split words on caseChange. For + example, if this is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. + :vartype split_on_case_change: bool + :ivar preserve_original: A value indicating whether original words will be preserved and added + to the subword list. Default is false. + :vartype preserve_original: bool + :ivar split_on_numerics: A value indicating whether to split on numbers. For example, if this + is set to true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. + :vartype split_on_numerics: bool + :ivar stem_english_possessive: A value indicating whether to remove trailing "'s" for each + subword. Default is true. + :vartype stem_english_possessive: bool + :ivar protected_words: A list of tokens to protect from being delimited. + :vartype protected_words: list[str] + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.WordDelimiterTokenFilter". + :vartype odata_type: str """ + generate_word_parts: Optional[bool] = rest_field( + name="generateWordParts", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to generate part words. If set, causes parts of words to be + generated; for example \"AzureSearch\" becomes \"Azure\" \"Search\". Default is true.""" + generate_number_parts: Optional[bool] = rest_field( + name="generateNumberParts", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to generate number subwords. Default is true.""" + catenate_words: Optional[bool] = rest_field( + name="catenateWords", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether maximum runs of word parts will be catenated. For example, if this + is set to true, \"Azure-Search\" becomes \"AzureSearch\". Default is false.""" + catenate_numbers: Optional[bool] = rest_field( + name="catenateNumbers", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether maximum runs of number parts will be catenated. For example, if this + is set to true, \"1-2\" becomes \"12\". Default is false.""" + catenate_all: Optional[bool] = rest_field( + name="catenateAll", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether all subword parts will be catenated. For example, if this is set to + true, \"Azure-Search-1\" becomes \"AzureSearch1\". Default is false.""" + split_on_case_change: Optional[bool] = rest_field( + name="splitOnCaseChange", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to split words on caseChange. For example, if this is set to true, + \"AzureSearch\" becomes \"Azure\" \"Search\". Default is true.""" + preserve_original: Optional[bool] = rest_field( + name="preserveOriginal", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether original words will be preserved and added to the subword list. + Default is false.""" + split_on_numerics: Optional[bool] = rest_field( + name="splitOnNumerics", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to split on numbers. For example, if this is set to true, + \"Azure1Search\" becomes \"Azure\" \"1\" \"Search\". Default is true.""" + stem_english_possessive: Optional[bool] = rest_field( + name="stemEnglishPossessive", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to remove trailing \"'s\" for each subword. Default is true.""" + protected_words: Optional[list[str]] = rest_field( + name="protectedWords", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of tokens to protect from being delimited.""" + odata_type: Literal["#Microsoft.Azure.Search.WordDelimiterTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.WordDelimiterTokenFilter\".""" + + @overload def __init__( self, *, name: str, - data_source_name: str, - target_index_name: str, - description: Optional[str] = None, - skillset_name: Optional[str] = None, - schedule: Optional[IndexingSchedule] = None, - parameters: Optional[IndexingParameters] = None, - field_mappings: Optional[List[FieldMapping]] = None, - output_field_mappings: Optional[List[FieldMapping]] = None, - is_disabled: bool = False, - e_tag: Optional[str] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - cache: Optional[SearchIndexerCache] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the indexer. Required. - :paramtype name: str - :keyword description: The description of the indexer. - :paramtype description: str - :keyword data_source_name: The name of the datasource from which this indexer reads data. - Required. - :paramtype data_source_name: str - :keyword skillset_name: The name of the skillset executing with this indexer. - :paramtype skillset_name: str - :keyword target_index_name: The name of the index to which this indexer writes data. Required. - :paramtype target_index_name: str - :keyword schedule: The schedule for this indexer. - :paramtype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :keyword parameters: Parameters for indexer execution. - :paramtype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :keyword field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :paramtype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword output_field_mappings: Output field mappings are applied after enrichment and - immediately before indexing. - :paramtype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword is_disabled: A value indicating whether the indexer is disabled. Default is false. - :paramtype is_disabled: bool - :keyword e_tag: The ETag of the indexer. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword cache: Adds caching to an enrichment pipeline to allow for incremental modification - steps without having to rebuild the index every time. - :paramtype cache: ~azure.search.documents.indexes.models.SearchIndexerCache - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.data_source_name = data_source_name - self.skillset_name = skillset_name - self.target_index_name = target_index_name - self.schedule = schedule - self.parameters = parameters - self.field_mappings = field_mappings - self.output_field_mappings = output_field_mappings - self.is_disabled = is_disabled - self.e_tag = e_tag - self.encryption_key = encryption_key - self.cache = cache - - def _to_generated(self): - return _SearchIndexer( - name=self.name, - description=self.description, - data_source_name=self.data_source_name, - skillset_name=self.skillset_name, - target_index_name=self.target_index_name, - schedule=self.schedule, - parameters=self.parameters, - field_mappings=self.field_mappings, - output_field_mappings=self.output_field_mappings, - is_disabled=self.is_disabled, - e_tag=self.e_tag, - encryption_key=( - self.encryption_key._to_generated() if self.encryption_key else None # pylint:disable=protected-access - ), - cache=self.cache, - ) - - @classmethod - def _from_generated(cls, search_indexer) -> Optional[Self]: - if not search_indexer: - return None - return cls( - name=search_indexer.name, - description=search_indexer.description, - data_source_name=search_indexer.data_source_name, - skillset_name=search_indexer.skillset_name, - target_index_name=search_indexer.target_index_name, - schedule=search_indexer.schedule, - parameters=search_indexer.parameters, - field_mappings=search_indexer.field_mappings, - output_field_mappings=search_indexer.output_field_mappings, - is_disabled=search_indexer.is_disabled, - e_tag=search_indexer.e_tag, - # pylint:disable=protected-access - encryption_key=SearchResourceEncryptionKey._from_generated(search_indexer.encryption_key), - cache=search_indexer.cache, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndexer instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexer instance - :rtype: SearchIndexer - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndexer.deserialize(data, content_type=content_type)) + generate_word_parts: Optional[bool] = None, + generate_number_parts: Optional[bool] = None, + catenate_words: Optional[bool] = None, + catenate_numbers: Optional[bool] = None, + catenate_all: Optional[bool] = None, + split_on_case_change: Optional[bool] = None, + preserve_original: Optional[bool] = None, + split_on_numerics: Optional[bool] = None, + stem_english_possessive: Optional[bool] = None, + protected_words: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.WordDelimiterTokenFilter" # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py new file mode 100644 index 000000000000..0015fcb40728 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -0,0 +1,444 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Union, overload +from ._models import SearchField as _SearchField +from ._models import SearchIndexerDataSourceConnection as _SearchIndexerDataSourceConnection +from ._models import KnowledgeBase as _KnowledgeBase +from ._enums import ( + LexicalAnalyzerName, + SearchFieldDataType as _SearchFieldDataType, +) +from ...knowledgebases.models import ( + KnowledgeRetrievalReasoningEffort, +) + +if TYPE_CHECKING: + from ._models import ( + DataChangeDetectionPolicy, + DataDeletionDetectionPolicy, + DataSourceCredentials, + SearchIndexerDataContainer, + SearchIndexerDataIdentity, + SearchResourceEncryptionKey, + ) + from ._enums import IndexerPermissionOption, SearchIndexerDataSourceType + + +class SearchField(_SearchField): + """Represents a field in an index definition, which describes the name, data type, and search + behavior of a field. + + This class adds backward compatibility support for the 'hidden' property, which is the inverse + of 'retrievable'. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + # Handle 'hidden' kwarg for backward compatibility + hidden = kwargs.pop("hidden", None) + super().__init__(*args, **kwargs) + # If hidden was explicitly provided, set retrievable to its inverse + if hidden is not None: + self.retrievable = not hidden + + @property + def hidden(self) -> Optional[bool]: + """A value indicating whether the field will be returned in a search result. + This is the inverse of 'retrievable'. Kept for backward compatibility. + + :return: True if the field is hidden (not retrievable), False otherwise. + :rtype: bool or None + """ + if self.retrievable is None: + return None + return not self.retrievable + + @hidden.setter + def hidden(self, value: Optional[bool]) -> None: + """Set whether the field should be hidden (not retrievable). + + :param value: True to hide the field, False to make it retrievable. + :type value: bool or None + """ + if value is None: + self.retrievable = None + else: + self.retrievable = not value + + +class SearchIndexerDataSourceConnection(_SearchIndexerDataSourceConnection): + """Represents a datasource definition, which can be used to configure an indexer. + + This class adds an additional overload to support passing connection_string directly + instead of credentials. + """ + + @overload + def __init__( + self, + *, + name: str, + type: Union[str, "SearchIndexerDataSourceType"], + credentials: "DataSourceCredentials", + container: "SearchIndexerDataContainer", + description: Optional[str] = None, + identity: Optional["SearchIndexerDataIdentity"] = None, + indexer_permission_options: Optional[List[Union[str, "IndexerPermissionOption"]]] = None, + data_change_detection_policy: Optional["DataChangeDetectionPolicy"] = None, + data_deletion_detection_policy: Optional["DataDeletionDetectionPolicy"] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__( + self, + *, + name: str, + type: Union[str, "SearchIndexerDataSourceType"], + connection_string: str, + container: "SearchIndexerDataContainer", + description: Optional[str] = None, + identity: Optional["SearchIndexerDataIdentity"] = None, + indexer_permission_options: Optional[List[Union[str, "IndexerPermissionOption"]]] = None, + data_change_detection_policy: Optional["DataChangeDetectionPolicy"] = None, + data_deletion_detection_policy: Optional["DataDeletionDetectionPolicy"] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBase(_KnowledgeBase): + """Represents a knowledge base definition. + + This class adds proper deserialization of the retrieval_reasoning_effort field + which uses discriminated polymorphism from the knowledgebases models. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + # Properly deserialize retrieval_reasoning_effort if it's a dict + effort = self.retrieval_reasoning_effort + if effort is not None and isinstance(effort, dict): + self.retrieval_reasoning_effort = KnowledgeRetrievalReasoningEffort._deserialize(effort, []) + + +def _collection_helper(typ: Any) -> str: + """Helper function to create a collection type string. + + :param typ: The type to wrap in a collection. Can be a string or an enum value. + :type typ: str or ~azure.search.documents.indexes.models.SearchFieldDataType + :return: A collection type string. + :rtype: str + """ + # If typ is an enum, get its value; otherwise use it as-is + if hasattr(typ, "value"): + typ = typ.value + return "Collection({})".format(typ) + + +# Re-export SearchFieldDataType with Collection method +# The Collection method is added at runtime via monkey-patching +SearchFieldDataType = _SearchFieldDataType +SearchFieldDataType.Collection = staticmethod(_collection_helper) # type: ignore[attr-defined] + + +def Collection(typ: Any) -> str: + """Helper function to create a collection type string. + + :param typ: The type to wrap in a collection. Can be a string or an enum value. + :type typ: str or ~azure.search.documents.indexes.models.SearchFieldDataType + :return: A collection type string. + :rtype: str + """ + # If typ is an enum, get its value; otherwise use it as-is + if hasattr(typ, "value"): + typ = typ.value + return "Collection({})".format(typ) + + +def SimpleField( + *, + name: str, + type: Union[str, _SearchFieldDataType], + key: bool = False, + hidden: bool = False, + filterable: bool = False, + sortable: bool = False, + facetable: bool = False, + **kw, # pylint:disable=unused-argument +) -> SearchField: + """Configure a simple field for an Azure Search Index + + :keyword name: Required. The name of the field, which must be unique within the fields collection + of the index or parent field. + :paramtype name: str + :keyword type: Required. The data type of the field. Possible values include: SearchFieldDataType.STRING, + SearchFieldDataType.INT32, SearchFieldDataType.INT64, SearchFieldDataType.DOUBLE, SearchFieldDataType.BOOLEAN, + SearchFieldDataType.DATETIMEOFFSET, SearchFieldDataType.GEOGRAPHY_POINT, SearchFieldDataType.COMPLEXTYPE, + from `azure.search.documents.SearchFieldDataType`. + :paramtype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType + :keyword key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type SearchFieldDataType.STRING. Key fields can be used to look up documents directly and + update or delete specific documents. Default is False + :paramtype key: bool + :keyword hidden: A value indicating whether the field will be returned in a search result. + Setting this to True is equivalent to setting retrievable to False. You can enable this option + if you want to use a field (for example, margin) as a filter, sorting, or scoring mechanism + but do not want the field to be visible to the end user. This property must be False for key + fields. Default is False. + :paramtype hidden: bool + :keyword filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields of type + SearchFieldDataType.STRING or Collection(SearchFieldDataType.STRING) that are filterable do + not undergo word-breaking, so comparisons are for exact matches only. For example, if you + set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but + $filter=f eq 'sunny day' will. This property must be null for complex fields. Default is False + :paramtype filterable: bool + :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default Azure Cognitive Search sorts results by score, but in many experiences + users will want to sort by fields in the documents. A simple field can be sortable only if it + is single-valued (it has a single value in the scope of the parent document). Simple collection + fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex + collections are also multi-valued, and therefore cannot be sortable. This is true whether it's + an immediate parent field, or an ancestor field, that's the complex collection. The default is + False. + :paramtype sortable: bool + :keyword facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). Fields of type SearchFieldDataType.GEOGRAPHY_POINT or + Collection(SearchFieldDataType.GEOGRAPHY_POINT) cannot be facetable. Default is False. + :paramtype facetable: bool + :return: The search field object. + :rtype: SearchField + """ + # If type is an enum, get its value; otherwise use it as-is + field_type = type.value if hasattr(type, "value") else type + result: Dict[str, Any] = { + "name": name, + "type": field_type, + "key": key, + "searchable": False, + "filterable": filterable, + "facetable": facetable, + "sortable": sortable, + "hidden": hidden, + } + return SearchField(**result) + + +def SearchableField( + *, + name: str, + collection: bool = False, + key: bool = False, + hidden: bool = False, + searchable: bool = True, + filterable: bool = False, + sortable: bool = False, + facetable: bool = False, + analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + synonym_map_names: Optional[List[str]] = None, + **kw, # pylint:disable=unused-argument +) -> SearchField: + """Configure a searchable text field for an Azure Search Index + + :keyword name: Required. The name of the field, which must be unique within the fields collection + of the index or parent field. + :paramtype name: str + :keyword collection: Whether this search field is a collection (default False) + :paramtype collection: bool + :keyword key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type SearchFieldDataType.STRING. Key fields can be used to look up documents directly and update or delete + specific documents. Default is False + :paramtype key: bool + :keyword hidden: A value indicating whether the field will be returned in a search result. + Setting this to True is equivalent to setting retrievable to False. You can enable this option + if you want to use a field (for example, margin) as a filter, sorting, or scoring mechanism + but do not want the field to be visible to the end user. This property must be False for key + fields. Default is False. + :paramtype hidden: bool + :keyword searchable: A value indicating whether the field is full-text searchable. This means it + will undergo analysis such as word-breaking during indexing. If you set a searchable field to a + value like "sunny day", internally it will be split into the individual tokens "sunny" and + "day". This enables full-text searches for these terms. Note: searchable fields + consume extra space in your index since Azure Cognitive Search will store an additional + tokenized version of the field value for full-text searches. If you want to save space in your + index and you don't need a field to be included in searches, set searchable to false. Default + is True. + :paramtype searchable: bool + :keyword filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields that are + filterable do not undergo word-breaking, so comparisons are for exact matches only. For example, + if you set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but + $filter=f eq 'sunny day' will. Default is False. + :paramtype filterable: bool + :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default Azure Cognitive Search sorts results by score, but in many experiences + users will want to sort by fields in the documents. The default is False. + :paramtype sortable: bool + :keyword facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). Default is False. + :paramtype facetable: bool + :keyword analyzer_name: The name of the analyzer to use for the field. This option can't be set together + with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed + for the field. Possible values include: 'ar.microsoft', 'ar.lucene', 'hy.lucene', + 'bn.microsoft', 'eu.lucene', 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh- + Hans.microsoft', 'zh-Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', + 'cs.microsoft', 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', + 'en.microsoft', 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', + 'fr.lucene', 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', + 'gu.microsoft', 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', + 'is.microsoft', 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', + 'ja.microsoft', 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', + 'lv.lucene', 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', + 'no.lucene', 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt- + PT.microsoft', 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', + 'ru.lucene', 'sr-cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', + 'es.microsoft', 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', + 'th.microsoft', 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', + 'vi.microsoft', 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', + 'simple', 'stop', 'whitespace'. + :paramtype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :keyword search_analyzer_name: The name of the analyzer used at search time for the field. It must be + set together with indexAnalyzer and it cannot be set together with the analyzer option. This + property cannot be set to the name of a language analyzer; use the analyzer property instead + if you need a language analyzer. This analyzer can be updated on an existing field. Possible + values include: + 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', 'bg.microsoft', + 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh-Hans.lucene', 'zh- + Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', 'cs.lucene', 'da.microsoft', + 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', 'en.lucene', 'et.microsoft', + 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', 'gl.lucene', 'de.microsoft', + 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', 'he.microsoft', 'hi.microsoft', + 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', 'id.microsoft', 'id.lucene', + 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', 'ja.lucene', 'kn.microsoft', + 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', 'lt.microsoft', 'ml.microsoft', + 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', 'fa.lucene', 'pl.microsoft', + 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', 'pt-PT.lucene', + 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- + cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', + 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', + 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', + 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', + 'whitespace'. + :paramtype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :keyword index_analyzer_name: The name of the analyzer used at indexing time for the field. + It must be set together with searchAnalyzer and it cannot be set together with the analyzer + option. This property cannot be set to the name of a language analyzer; use the analyzer + property instead if you need a language analyzer. Once the analyzer is chosen, it cannot be + changed for the field. Possible values include: + 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', + 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh- + Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', + 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', + 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', + 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', + 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', + 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', + 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', + 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', + 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', + 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- + cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', + 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', + 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', + 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', + 'whitespace'. + :paramtype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :keyword synonym_map_names: A list of the names of synonym maps to associate with this field. Currently + only one synonym map per field is supported. Assigning a synonym map to a field ensures that + query terms targeting that field are expanded at query-time using the rules in the synonym map. + This attribute can be changed on existing fields. + :paramtype synonym_map_names: list[str] + :return: The search field object. + :rtype: SearchField + """ + typ = Collection(SearchFieldDataType.STRING) if collection else SearchFieldDataType.STRING + result: Dict[str, Any] = { + "name": name, + "type": typ, + "key": key, + "searchable": searchable, + "filterable": filterable, + "facetable": facetable, + "sortable": sortable, + "hidden": hidden, + } + if analyzer_name: + result["analyzer_name"] = analyzer_name + if search_analyzer_name: + result["search_analyzer_name"] = search_analyzer_name + if index_analyzer_name: + result["index_analyzer_name"] = index_analyzer_name + if synonym_map_names: + result["synonym_map_names"] = synonym_map_names + return SearchField(**result) + + +def ComplexField( + *, + name: str, + collection: bool = False, + fields: Optional[List[SearchField]] = None, + **kw, # pylint:disable=unused-argument +) -> SearchField: + """Configure a Complex or Complex collection field for an Azure Search Index + + :keyword name: Required. The name of the field, which must be unique within the fields collection + of the index or parent field. + :paramtype name: str + :keyword collection: Whether this complex field is a collection (default False) + :paramtype collection: bool + :keyword fields: A list of sub-fields + :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] + :return: The search field object. + :rtype: SearchField + """ + typ = Collection(SearchFieldDataType.COMPLEX) if collection else SearchFieldDataType.COMPLEX + result: Dict[str, Any] = {"name": name, "type": typ, "fields": fields} + return SearchField(**result) + + +__all__: list[str] = [ + "KnowledgeBase", + "SearchField", + "SearchFieldDataType", + "SearchIndexerDataSourceConnection", + "SimpleField", + "SearchableField", + "ComplexField", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/__init__.py index 321f317a4aae..f721cfb1ed80 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/__init__.py @@ -1,29 +1,32 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._knowledgebase_client import KnowledgeBaseRetrievalClient +from typing import TYPE_CHECKING -__all__ = ("KnowledgeBaseRetrievalClient",) +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import KnowledgeBaseRetrievalClient # type: ignore +from .._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "KnowledgeBaseRetrievalClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_knowledge_base_retrieval_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_client.py similarity index 61% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_knowledge_base_retrieval_client.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_client.py index 4e93613f3d16..fcb1e21616ec 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_knowledge_base_retrieval_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_client.py @@ -1,45 +1,46 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import PipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models +from .._utils.serialization import Deserializer, Serializer from ._configuration import KnowledgeBaseRetrievalClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import KnowledgeRetrievalOperations +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class KnowledgeBaseRetrievalClient: - """Client that can be used to query an knowledge base. - :ivar knowledge_retrieval: KnowledgeRetrievalOperations operations - :vartype knowledge_retrieval: - azure.search.documents.knowledgebases.operations.KnowledgeRetrievalOperations - :param endpoint: The endpoint URL of the search service. Required. +class KnowledgeBaseRetrievalClient(_KnowledgeBaseRetrievalClientOperationsMixin): + """KnowledgeBaseRetrievalClient. + + :param endpoint: Service host. Required. :type endpoint: str - :param knowledge_base_name: The name of the knowledge base. Required. - :type knowledge_base_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, knowledge_base_name: str, **kwargs: Any - ) -> None: - _endpoint = "{endpoint}/knowledgebases('{knowledgeBaseName}')" - self._config = KnowledgeBaseRetrievalClientConfiguration( - endpoint=endpoint, knowledge_base_name=knowledge_base_name, **kwargs - ) + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = KnowledgeBaseRetrievalClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -60,21 +61,17 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.knowledge_retrieval = KnowledgeRetrievalOperations( - self._client, self._config, self._serialize, self._deserialize - ) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -89,9 +86,6 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "knowledgeBaseName": self._serialize.url( - "self._config.knowledge_base_name", self._config.knowledge_base_name, "str" - ), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_configuration.py new file mode 100644 index 000000000000..425408a1c073 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class KnowledgeBaseRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for KnowledgeBaseRetrievalClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/__init__.py deleted file mode 100644 index fcd722b7102c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_base_retrieval_client import KnowledgeBaseRetrievalClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBaseRetrievalClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_configuration.py deleted file mode 100644 index fbe84162cd8c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class KnowledgeBaseRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for KnowledgeBaseRetrievalClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param knowledge_base_name: The name of the knowledge base. Required. - :type knowledge_base_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, knowledge_base_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-11-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if knowledge_base_name is None: - raise ValueError("Parameter 'knowledge_base_name' must not be None.") - - self.endpoint = endpoint - self.knowledge_base_name = knowledge_base_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "knowledgebaseretrievalclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/__init__.py deleted file mode 100644 index fcd722b7102c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_base_retrieval_client import KnowledgeBaseRetrievalClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBaseRetrievalClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_configuration.py deleted file mode 100644 index a96675a3c2ad..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class KnowledgeBaseRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for KnowledgeBaseRetrievalClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param knowledge_base_name: The name of the knowledge base. Required. - :type knowledge_base_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, knowledge_base_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-11-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if knowledge_base_name is None: - raise ValueError("Parameter 'knowledge_base_name' must not be None.") - - self.endpoint = endpoint - self.knowledge_base_name = knowledge_base_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "knowledgebaseretrievalclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_knowledge_retrieval_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_knowledge_retrieval_operations.py deleted file mode 100644 index 73d0b76d7b23..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_knowledge_retrieval_operations.py +++ /dev/null @@ -1,199 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._knowledge_retrieval_operations import build_retrieve_request -from .._configuration import KnowledgeBaseRetrievalClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class KnowledgeRetrievalOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.knowledgebases.aio.KnowledgeBaseRetrievalClient`'s - :attr:`knowledge_retrieval` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: KnowledgeBaseRetrievalClientConfiguration = ( - input_args.pop(0) if input_args else kwargs.pop("config") - ) - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def retrieve( - self, - retrieval_request: _models.KnowledgeBaseRetrievalRequest, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBaseRetrievalResponse: - """KnowledgeBase retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Required. - :type retrieval_request: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.knowledgebases.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBaseRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def retrieve( - self, - retrieval_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeBaseRetrievalResponse: - """KnowledgeBase retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Required. - :type retrieval_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.knowledgebases.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeBaseRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def retrieve( - self, - retrieval_request: Union[_models.KnowledgeBaseRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeBaseRetrievalResponse: - """KnowledgeBase retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Is either a - KnowledgeBaseRetrievalRequest type or a IO[bytes] type. Required. - :type retrieval_request: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest or IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.knowledgebases.models.RequestOptions - :return: KnowledgeBaseRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseRetrievalResponse] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieval_request, (IOBase, bytes)): - _content = retrieval_request - else: - _json = self._serialize.body(retrieval_request, "KnowledgeBaseRetrievalRequest") - - _request = build_retrieve_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "knowledgeBaseName": self._serialize.url( - "self._config.knowledge_base_name", self._config.knowledge_base_name, "str" - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeBaseRetrievalResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/__init__.py deleted file mode 100644 index 6f5c31b6dfde..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/__init__.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AzureBlobKnowledgeSourceParams, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - IndexedOneLakeKnowledgeSourceParams, - IndexedSharePointKnowledgeSourceParams, - KnowledgeBaseActivityRecord, - KnowledgeBaseAgenticReasoningActivityRecord, - KnowledgeBaseAzureBlobActivityArguments, - KnowledgeBaseAzureBlobActivityRecord, - KnowledgeBaseAzureBlobReference, - KnowledgeBaseErrorAdditionalInfo, - KnowledgeBaseErrorDetail, - KnowledgeBaseIndexedOneLakeActivityArguments, - KnowledgeBaseIndexedOneLakeActivityRecord, - KnowledgeBaseIndexedOneLakeReference, - KnowledgeBaseIndexedSharePointActivityArguments, - KnowledgeBaseIndexedSharePointActivityRecord, - KnowledgeBaseIndexedSharePointReference, - KnowledgeBaseMessage, - KnowledgeBaseMessageContent, - KnowledgeBaseMessageImageContent, - KnowledgeBaseMessageImageContentImage, - KnowledgeBaseMessageTextContent, - KnowledgeBaseModelAnswerSynthesisActivityRecord, - KnowledgeBaseModelQueryPlanningActivityRecord, - KnowledgeBaseReference, - KnowledgeBaseRemoteSharePointActivityArguments, - KnowledgeBaseRemoteSharePointActivityRecord, - KnowledgeBaseRemoteSharePointReference, - KnowledgeBaseRetrievalActivityRecord, - KnowledgeBaseRetrievalRequest, - KnowledgeBaseRetrievalResponse, - KnowledgeBaseSearchIndexActivityArguments, - KnowledgeBaseSearchIndexActivityRecord, - KnowledgeBaseSearchIndexReference, - KnowledgeBaseWebActivityArguments, - KnowledgeBaseWebActivityRecord, - KnowledgeBaseWebReference, - KnowledgeRetrievalIntent, - KnowledgeRetrievalLowReasoningEffort, - KnowledgeRetrievalMediumReasoningEffort, - KnowledgeRetrievalMinimalReasoningEffort, - KnowledgeRetrievalReasoningEffort, - KnowledgeRetrievalSemanticIntent, - KnowledgeSourceParams, - RemoteSharePointKnowledgeSourceParams, - RequestOptions, - SearchIndexFieldReference, - SearchIndexKnowledgeSourceParams, - SharePointSensitivityLabelInfo, - WebKnowledgeSourceParams, -) - -from ._knowledge_base_retrieval_client_enums import ( # type: ignore - KnowledgeBaseMessageContentType, - KnowledgeRetrievalIntentType, - KnowledgeRetrievalOutputMode, - KnowledgeRetrievalReasoningEffortKind, - KnowledgeSourceKind, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AzureBlobKnowledgeSourceParams", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "IndexedOneLakeKnowledgeSourceParams", - "IndexedSharePointKnowledgeSourceParams", - "KnowledgeBaseActivityRecord", - "KnowledgeBaseAgenticReasoningActivityRecord", - "KnowledgeBaseAzureBlobActivityArguments", - "KnowledgeBaseAzureBlobActivityRecord", - "KnowledgeBaseAzureBlobReference", - "KnowledgeBaseErrorAdditionalInfo", - "KnowledgeBaseErrorDetail", - "KnowledgeBaseIndexedOneLakeActivityArguments", - "KnowledgeBaseIndexedOneLakeActivityRecord", - "KnowledgeBaseIndexedOneLakeReference", - "KnowledgeBaseIndexedSharePointActivityArguments", - "KnowledgeBaseIndexedSharePointActivityRecord", - "KnowledgeBaseIndexedSharePointReference", - "KnowledgeBaseMessage", - "KnowledgeBaseMessageContent", - "KnowledgeBaseMessageImageContent", - "KnowledgeBaseMessageImageContentImage", - "KnowledgeBaseMessageTextContent", - "KnowledgeBaseModelAnswerSynthesisActivityRecord", - "KnowledgeBaseModelQueryPlanningActivityRecord", - "KnowledgeBaseReference", - "KnowledgeBaseRemoteSharePointActivityArguments", - "KnowledgeBaseRemoteSharePointActivityRecord", - "KnowledgeBaseRemoteSharePointReference", - "KnowledgeBaseRetrievalActivityRecord", - "KnowledgeBaseRetrievalRequest", - "KnowledgeBaseRetrievalResponse", - "KnowledgeBaseSearchIndexActivityArguments", - "KnowledgeBaseSearchIndexActivityRecord", - "KnowledgeBaseSearchIndexReference", - "KnowledgeBaseWebActivityArguments", - "KnowledgeBaseWebActivityRecord", - "KnowledgeBaseWebReference", - "KnowledgeRetrievalIntent", - "KnowledgeRetrievalLowReasoningEffort", - "KnowledgeRetrievalMediumReasoningEffort", - "KnowledgeRetrievalMinimalReasoningEffort", - "KnowledgeRetrievalReasoningEffort", - "KnowledgeRetrievalSemanticIntent", - "KnowledgeSourceParams", - "RemoteSharePointKnowledgeSourceParams", - "RequestOptions", - "SearchIndexFieldReference", - "SearchIndexKnowledgeSourceParams", - "SharePointSensitivityLabelInfo", - "WebKnowledgeSourceParams", - "KnowledgeBaseMessageContentType", - "KnowledgeRetrievalIntentType", - "KnowledgeRetrievalOutputMode", - "KnowledgeRetrievalReasoningEffortKind", - "KnowledgeSourceKind", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_models_py3.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_models_py3.py deleted file mode 100644 index 83ba940d15f6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_models_py3.py +++ /dev/null @@ -1,2875 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from collections.abc import MutableMapping -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models -JSON = MutableMapping[str, Any] - - -class KnowledgeSourceParams(_serialization.Model): - """KnowledgeSourceParams. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureBlobKnowledgeSourceParams, IndexedOneLakeKnowledgeSourceParams, - IndexedSharePointKnowledgeSourceParams, RemoteSharePointKnowledgeSourceParams, - SearchIndexKnowledgeSourceParams, WebKnowledgeSourceParams - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": { - "azureBlob": "AzureBlobKnowledgeSourceParams", - "indexedOneLake": "IndexedOneLakeKnowledgeSourceParams", - "indexedSharePoint": "IndexedSharePointKnowledgeSourceParams", - "remoteSharePoint": "RemoteSharePointKnowledgeSourceParams", - "searchIndex": "SearchIndexKnowledgeSourceParams", - "web": "WebKnowledgeSourceParams", - } - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - """ - super().__init__(**kwargs) - self.knowledge_source_name = knowledge_source_name - self.include_references = include_references - self.include_reference_source_data = include_reference_source_data - self.always_query_source = always_query_source - self.reranker_threshold = reranker_threshold - self.kind: Optional[str] = None - - -class AzureBlobKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a azure blob knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - """ - super().__init__( - knowledge_source_name=knowledge_source_name, - include_references=include_references, - include_reference_source_data=include_reference_source_data, - always_query_source=always_query_source, - reranker_threshold=reranker_threshold, - **kwargs - ) - self.kind: str = "azureBlob" - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.knowledgebases.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.search.documents.knowledgebases.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.search.documents.knowledgebases.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.search.documents.knowledgebases.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class IndexedOneLakeKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a indexed OneLake knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - """ - super().__init__( - knowledge_source_name=knowledge_source_name, - include_references=include_references, - include_reference_source_data=include_reference_source_data, - always_query_source=always_query_source, - reranker_threshold=reranker_threshold, - **kwargs - ) - self.kind: str = "indexedOneLake" - - -class IndexedSharePointKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a indexed SharePoint knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - """ - super().__init__( - knowledge_source_name=knowledge_source_name, - include_references=include_references, - include_reference_source_data=include_reference_source_data, - always_query_source=always_query_source, - reranker_threshold=reranker_threshold, - **kwargs - ) - self.kind: str = "indexedSharePoint" - - -class KnowledgeBaseActivityRecord(_serialization.Model): - """Base type for activity records. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeBaseRetrievalActivityRecord, KnowledgeBaseAgenticReasoningActivityRecord, - KnowledgeBaseModelAnswerSynthesisActivityRecord, KnowledgeBaseModelQueryPlanningActivityRecord - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - } - - _subtype_map = { - "type": { - "KnowledgeBaseRetrievalActivityRecord": "KnowledgeBaseRetrievalActivityRecord", - "agenticReasoning": "KnowledgeBaseAgenticReasoningActivityRecord", - "modelAnswerSynthesis": "KnowledgeBaseModelAnswerSynthesisActivityRecord", - "modelQueryPlanning": "KnowledgeBaseModelQueryPlanningActivityRecord", - } - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - """ - super().__init__(**kwargs) - self.id = id - self.type: Optional[str] = None - self.elapsed_ms = elapsed_ms - self.error = error - - -class KnowledgeBaseAgenticReasoningActivityRecord(KnowledgeBaseActivityRecord): # pylint: disable=name-too-long - """Represents an agentic reasoning activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar reasoning_tokens: The number of input tokens for agentic reasoning. - :vartype reasoning_tokens: int - :ivar retrieval_reasoning_effort: - :vartype retrieval_reasoning_effort: - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "reasoning_tokens": {"key": "reasoningTokens", "type": "int"}, - "retrieval_reasoning_effort": {"key": "retrievalReasoningEffort", "type": "KnowledgeRetrievalReasoningEffort"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - reasoning_tokens: Optional[int] = None, - retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword reasoning_tokens: The number of input tokens for agentic reasoning. - :paramtype reasoning_tokens: int - :keyword retrieval_reasoning_effort: - :paramtype retrieval_reasoning_effort: - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, error=error, **kwargs) - self.type: str = "agenticReasoning" - self.reasoning_tokens = reasoning_tokens - self.retrieval_reasoning_effort = retrieval_reasoning_effort - - -class KnowledgeBaseAzureBlobActivityArguments(_serialization.Model): - """Represents the arguments the azure blob retrieval activity was run with. - - :ivar search: The search string used to query blob contents. - :vartype search: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - } - - def __init__(self, *, search: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword search: The search string used to query blob contents. - :paramtype search: str - """ - super().__init__(**kwargs) - self.search = search - - -class KnowledgeBaseRetrievalActivityRecord(KnowledgeBaseActivityRecord): - """Represents a retrieval activity record. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeBaseAzureBlobActivityRecord, KnowledgeBaseIndexedOneLakeActivityRecord, - KnowledgeBaseIndexedSharePointActivityRecord, KnowledgeBaseRemoteSharePointActivityRecord, - KnowledgeBaseSearchIndexActivityRecord, KnowledgeBaseWebActivityRecord - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - } - - _subtype_map = { - "type": { - "azureBlob": "KnowledgeBaseAzureBlobActivityRecord", - "indexedOneLake": "KnowledgeBaseIndexedOneLakeActivityRecord", - "indexedSharePoint": "KnowledgeBaseIndexedSharePointActivityRecord", - "remoteSharePoint": "KnowledgeBaseRemoteSharePointActivityRecord", - "searchIndex": "KnowledgeBaseSearchIndexActivityRecord", - "web": "KnowledgeBaseWebActivityRecord", - } - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, error=error, **kwargs) - self.type: str = "KnowledgeBaseRetrievalActivityRecord" - self.knowledge_source_name = knowledge_source_name - self.query_time = query_time - self.count = count - - -class KnowledgeBaseAzureBlobActivityRecord(KnowledgeBaseRetrievalActivityRecord): - """Represents a azure blob retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar azure_blob_arguments: The azure blob arguments for the retrieval activity. - :vartype azure_blob_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseAzureBlobActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "azure_blob_arguments": {"key": "azureBlobArguments", "type": "KnowledgeBaseAzureBlobActivityArguments"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - azure_blob_arguments: Optional["_models.KnowledgeBaseAzureBlobActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword azure_blob_arguments: The azure blob arguments for the retrieval activity. - :paramtype azure_blob_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseAzureBlobActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - error=error, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "azureBlob" - self.azure_blob_arguments = azure_blob_arguments - - -class KnowledgeBaseReference(_serialization.Model): - """Base type for references. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeBaseAzureBlobReference, KnowledgeBaseIndexedOneLakeReference, - KnowledgeBaseIndexedSharePointReference, KnowledgeBaseRemoteSharePointReference, - KnowledgeBaseSearchIndexReference, KnowledgeBaseWebReference - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - } - - _subtype_map = { - "type": { - "azureBlob": "KnowledgeBaseAzureBlobReference", - "indexedOneLake": "KnowledgeBaseIndexedOneLakeReference", - "indexedSharePoint": "KnowledgeBaseIndexedSharePointReference", - "remoteSharePoint": "KnowledgeBaseRemoteSharePointReference", - "searchIndex": "KnowledgeBaseSearchIndexReference", - "web": "KnowledgeBaseWebReference", - } - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.id = id - self.activity_source = activity_source - self.source_data = source_data - self.reranker_score = reranker_score - - -class KnowledgeBaseAzureBlobReference(KnowledgeBaseReference): - """Represents an Azure Blob Storage document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar blob_url: The blob URL for the reference. - :vartype blob_url: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "blob_url": {"key": "blobUrl", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - blob_url: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword blob_url: The blob URL for the reference. - :paramtype blob_url: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "azureBlob" - self.blob_url = blob_url - - -class KnowledgeBaseErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class KnowledgeBaseErrorDetail(_serialization.Model): - """The error details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[KnowledgeBaseErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[KnowledgeBaseErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = None - self.additional_info: Optional[list["_models.KnowledgeBaseErrorAdditionalInfo"]] = None - - -class KnowledgeBaseIndexedOneLakeActivityArguments(_serialization.Model): # pylint: disable=name-too-long - """Represents the arguments the indexed OneLake retrieval activity was run with. - - :ivar search: The search string used to query indexed OneLake contents. - :vartype search: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - } - - def __init__(self, *, search: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword search: The search string used to query indexed OneLake contents. - :paramtype search: str - """ - super().__init__(**kwargs) - self.search = search - - -class KnowledgeBaseIndexedOneLakeActivityRecord(KnowledgeBaseRetrievalActivityRecord): # pylint: disable=name-too-long - """Represents a indexed OneLake retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar indexed_one_lake_arguments: The indexed OneLake arguments for the retrieval activity. - :vartype indexed_one_lake_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedOneLakeActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "indexed_one_lake_arguments": { - "key": "indexedOneLakeArguments", - "type": "KnowledgeBaseIndexedOneLakeActivityArguments", - }, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - indexed_one_lake_arguments: Optional["_models.KnowledgeBaseIndexedOneLakeActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword indexed_one_lake_arguments: The indexed OneLake arguments for the retrieval activity. - :paramtype indexed_one_lake_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedOneLakeActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - error=error, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "indexedOneLake" - self.indexed_one_lake_arguments = indexed_one_lake_arguments - - -class KnowledgeBaseIndexedOneLakeReference(KnowledgeBaseReference): - """Represents an Azure Blob Storage document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar doc_url: The document URL for the reference. - :vartype doc_url: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "doc_url": {"key": "docUrl", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - doc_url: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword doc_url: The document URL for the reference. - :paramtype doc_url: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "indexedOneLake" - self.doc_url = doc_url - - -class KnowledgeBaseIndexedSharePointActivityArguments(_serialization.Model): # pylint: disable=name-too-long - """Represents the arguments the indexed SharePoint retrieval activity was run with. - - :ivar search: The search string used to query indexed SharePoint contents. - :vartype search: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - } - - def __init__(self, *, search: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword search: The search string used to query indexed SharePoint contents. - :paramtype search: str - """ - super().__init__(**kwargs) - self.search = search - - -class KnowledgeBaseIndexedSharePointActivityRecord( - KnowledgeBaseRetrievalActivityRecord -): # pylint: disable=name-too-long - """Represents a indexed SharePoint retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar indexed_share_point_arguments: The indexed SharePoint arguments for the retrieval - activity. - :vartype indexed_share_point_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedSharePointActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "indexed_share_point_arguments": { - "key": "indexedSharePointArguments", - "type": "KnowledgeBaseIndexedSharePointActivityArguments", - }, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - indexed_share_point_arguments: Optional["_models.KnowledgeBaseIndexedSharePointActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword indexed_share_point_arguments: The indexed SharePoint arguments for the retrieval - activity. - :paramtype indexed_share_point_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedSharePointActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - error=error, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "indexedSharePoint" - self.indexed_share_point_arguments = indexed_share_point_arguments - - -class KnowledgeBaseIndexedSharePointReference(KnowledgeBaseReference): - """Represents an Azure Blob Storage document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar doc_url: The document URL for the reference. - :vartype doc_url: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "doc_url": {"key": "docUrl", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - doc_url: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword doc_url: The document URL for the reference. - :paramtype doc_url: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "indexedSharePoint" - self.doc_url = doc_url - - -class KnowledgeBaseMessage(_serialization.Model): - """The natural language message style object. - - All required parameters must be populated in order to send to server. - - :ivar role: The role of the tool response. - :vartype role: str - :ivar content: Required. - :vartype content: - list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContent] - """ - - _validation = { - "content": {"required": True}, - } - - _attribute_map = { - "role": {"key": "role", "type": "str"}, - "content": {"key": "content", "type": "[KnowledgeBaseMessageContent]"}, - } - - def __init__( - self, *, content: list["_models.KnowledgeBaseMessageContent"], role: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword role: The role of the tool response. - :paramtype role: str - :keyword content: Required. - :paramtype content: - list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContent] - """ - super().__init__(**kwargs) - self.role = role - self.content = content - - -class KnowledgeBaseMessageContent(_serialization.Model): - """Specifies the type of the message content. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeBaseMessageImageContent, KnowledgeBaseMessageTextContent - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the message. Required. Known values are: "text" and "image". - :vartype type: str or - ~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContentType - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - } - - _subtype_map = {"type": {"image": "KnowledgeBaseMessageImageContent", "text": "KnowledgeBaseMessageTextContent"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - - -class KnowledgeBaseMessageImageContent(KnowledgeBaseMessageContent): - """Text message type. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the message. Required. Known values are: "text" and "image". - :vartype type: str or - ~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContentType - :ivar image: Required. - :vartype image: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageImageContentImage - """ - - _validation = { - "type": {"required": True}, - "image": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "image": {"key": "image", "type": "KnowledgeBaseMessageImageContentImage"}, - } - - def __init__(self, *, image: "_models.KnowledgeBaseMessageImageContentImage", **kwargs: Any) -> None: - """ - :keyword image: Required. - :paramtype image: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageImageContentImage - """ - super().__init__(**kwargs) - self.type: str = "image" - self.image = image - - -class KnowledgeBaseMessageImageContentImage(_serialization.Model): - """KnowledgeBaseMessageImageContentImage. - - All required parameters must be populated in order to send to server. - - :ivar url: The url of the image. Required. - :vartype url: str - """ - - _validation = { - "url": {"required": True}, - } - - _attribute_map = { - "url": {"key": "url", "type": "str"}, - } - - def __init__(self, *, url: str, **kwargs: Any) -> None: - """ - :keyword url: The url of the image. Required. - :paramtype url: str - """ - super().__init__(**kwargs) - self.url = url - - -class KnowledgeBaseMessageTextContent(KnowledgeBaseMessageContent): - """Text message type. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the message. Required. Known values are: "text" and "image". - :vartype type: str or - ~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContentType - :ivar text: Required. - :vartype text: str - """ - - _validation = { - "type": {"required": True}, - "text": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "text": {"key": "text", "type": "str"}, - } - - def __init__(self, *, text: str, **kwargs: Any) -> None: - """ - :keyword text: Required. - :paramtype text: str - """ - super().__init__(**kwargs) - self.type: str = "text" - self.text = text - - -class KnowledgeBaseModelAnswerSynthesisActivityRecord(KnowledgeBaseActivityRecord): # pylint: disable=name-too-long - """Represents an LLM answer synthesis activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar input_tokens: The number of input tokens for the LLM answer synthesis activity. - :vartype input_tokens: int - :ivar output_tokens: The number of output tokens for the LLM answer synthesis activity. - :vartype output_tokens: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "input_tokens": {"key": "inputTokens", "type": "int"}, - "output_tokens": {"key": "outputTokens", "type": "int"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - input_tokens: Optional[int] = None, - output_tokens: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword input_tokens: The number of input tokens for the LLM answer synthesis activity. - :paramtype input_tokens: int - :keyword output_tokens: The number of output tokens for the LLM answer synthesis activity. - :paramtype output_tokens: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, error=error, **kwargs) - self.type: str = "modelAnswerSynthesis" - self.input_tokens = input_tokens - self.output_tokens = output_tokens - - -class KnowledgeBaseModelQueryPlanningActivityRecord(KnowledgeBaseActivityRecord): # pylint: disable=name-too-long - """Represents an LLM query planning activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar input_tokens: The number of input tokens for the LLM query planning activity. - :vartype input_tokens: int - :ivar output_tokens: The number of output tokens for the LLM query planning activity. - :vartype output_tokens: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "input_tokens": {"key": "inputTokens", "type": "int"}, - "output_tokens": {"key": "outputTokens", "type": "int"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - input_tokens: Optional[int] = None, - output_tokens: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword input_tokens: The number of input tokens for the LLM query planning activity. - :paramtype input_tokens: int - :keyword output_tokens: The number of output tokens for the LLM query planning activity. - :paramtype output_tokens: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, error=error, **kwargs) - self.type: str = "modelQueryPlanning" - self.input_tokens = input_tokens - self.output_tokens = output_tokens - - -class KnowledgeBaseRemoteSharePointActivityArguments(_serialization.Model): # pylint: disable=name-too-long - """Represents the arguments the remote SharePoint retrieval activity was run with. - - :ivar search: The search string used to query the remote SharePoint knowledge source. - :vartype search: str - :ivar filter_expression_add_on: The filter expression add-on for the retrieval activity. - :vartype filter_expression_add_on: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - "filter_expression_add_on": {"key": "filterExpressionAddOn", "type": "str"}, - } - - def __init__( - self, *, search: Optional[str] = None, filter_expression_add_on: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword search: The search string used to query the remote SharePoint knowledge source. - :paramtype search: str - :keyword filter_expression_add_on: The filter expression add-on for the retrieval activity. - :paramtype filter_expression_add_on: str - """ - super().__init__(**kwargs) - self.search = search - self.filter_expression_add_on = filter_expression_add_on - - -class KnowledgeBaseRemoteSharePointActivityRecord( - KnowledgeBaseRetrievalActivityRecord -): # pylint: disable=name-too-long - """Represents a remote SharePoint retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar remote_share_point_arguments: The remote SharePoint arguments for the retrieval activity. - :vartype remote_share_point_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseRemoteSharePointActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "remote_share_point_arguments": { - "key": "remoteSharePointArguments", - "type": "KnowledgeBaseRemoteSharePointActivityArguments", - }, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - remote_share_point_arguments: Optional["_models.KnowledgeBaseRemoteSharePointActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword remote_share_point_arguments: The remote SharePoint arguments for the retrieval - activity. - :paramtype remote_share_point_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseRemoteSharePointActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - error=error, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "remoteSharePoint" - self.remote_share_point_arguments = remote_share_point_arguments - - -class KnowledgeBaseRemoteSharePointReference(KnowledgeBaseReference): - """Represents a remote SharePoint document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar web_url: The url the reference data originated from. - :vartype web_url: str - :ivar search_sensitivity_label_info: Information about the sensitivity label applied to a - SharePoint document. - :vartype search_sensitivity_label_info: - ~azure.search.documents.knowledgebases.models.SharePointSensitivityLabelInfo - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "web_url": {"key": "webUrl", "type": "str"}, - "search_sensitivity_label_info": { - "key": "searchSensitivityLabelInfo", - "type": "SharePointSensitivityLabelInfo", - }, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - web_url: Optional[str] = None, - search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword web_url: The url the reference data originated from. - :paramtype web_url: str - :keyword search_sensitivity_label_info: Information about the sensitivity label applied to a - SharePoint document. - :paramtype search_sensitivity_label_info: - ~azure.search.documents.knowledgebases.models.SharePointSensitivityLabelInfo - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "remoteSharePoint" - self.web_url = web_url - self.search_sensitivity_label_info = search_sensitivity_label_info - - -class KnowledgeBaseRetrievalRequest(_serialization.Model): - """The input contract for the retrieval request. - - :ivar messages: A list of chat message style input. - :vartype messages: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessage] - :ivar intents: A list of intended queries to execute without model query planning. - :vartype intents: list[~azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntent] - :ivar max_runtime_in_seconds: The maximum runtime in seconds. - :vartype max_runtime_in_seconds: int - :ivar max_output_size: Limits the maximum size of the content in the output. - :vartype max_output_size: int - :ivar retrieval_reasoning_effort: - :vartype retrieval_reasoning_effort: - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort - :ivar include_activity: Indicates retrieval results should include activity information. - :vartype include_activity: bool - :ivar output_mode: The output configuration for this retrieval. Known values are: - "extractiveData" and "answerSynthesis". - :vartype output_mode: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode - :ivar knowledge_source_params: A list of runtime parameters for the knowledge sources. - :vartype knowledge_source_params: - list[~azure.search.documents.knowledgebases.models.KnowledgeSourceParams] - """ - - _attribute_map = { - "messages": {"key": "messages", "type": "[KnowledgeBaseMessage]"}, - "intents": {"key": "intents", "type": "[KnowledgeRetrievalIntent]"}, - "max_runtime_in_seconds": {"key": "maxRuntimeInSeconds", "type": "int"}, - "max_output_size": {"key": "maxOutputSize", "type": "int"}, - "retrieval_reasoning_effort": {"key": "retrievalReasoningEffort", "type": "KnowledgeRetrievalReasoningEffort"}, - "include_activity": {"key": "includeActivity", "type": "bool"}, - "output_mode": {"key": "outputMode", "type": "str"}, - "knowledge_source_params": {"key": "knowledgeSourceParams", "type": "[KnowledgeSourceParams]"}, - } - - def __init__( - self, - *, - messages: Optional[list["_models.KnowledgeBaseMessage"]] = None, - intents: Optional[list["_models.KnowledgeRetrievalIntent"]] = None, - max_runtime_in_seconds: Optional[int] = None, - max_output_size: Optional[int] = None, - retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, - include_activity: Optional[bool] = None, - output_mode: Optional[Union[str, "_models.KnowledgeRetrievalOutputMode"]] = None, - knowledge_source_params: Optional[list["_models.KnowledgeSourceParams"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword messages: A list of chat message style input. - :paramtype messages: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessage] - :keyword intents: A list of intended queries to execute without model query planning. - :paramtype intents: - list[~azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntent] - :keyword max_runtime_in_seconds: The maximum runtime in seconds. - :paramtype max_runtime_in_seconds: int - :keyword max_output_size: Limits the maximum size of the content in the output. - :paramtype max_output_size: int - :keyword retrieval_reasoning_effort: - :paramtype retrieval_reasoning_effort: - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort - :keyword include_activity: Indicates retrieval results should include activity information. - :paramtype include_activity: bool - :keyword output_mode: The output configuration for this retrieval. Known values are: - "extractiveData" and "answerSynthesis". - :paramtype output_mode: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode - :keyword knowledge_source_params: A list of runtime parameters for the knowledge sources. - :paramtype knowledge_source_params: - list[~azure.search.documents.knowledgebases.models.KnowledgeSourceParams] - """ - super().__init__(**kwargs) - self.messages = messages - self.intents = intents - self.max_runtime_in_seconds = max_runtime_in_seconds - self.max_output_size = max_output_size - self.retrieval_reasoning_effort = retrieval_reasoning_effort - self.include_activity = include_activity - self.output_mode = output_mode - self.knowledge_source_params = knowledge_source_params - - -class KnowledgeBaseRetrievalResponse(_serialization.Model): - """The output contract for the retrieval response. - - :ivar response: - :vartype response: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessage] - :ivar activity: The activity records for tracking progress and billing implications. - :vartype activity: - list[~azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecord] - :ivar references: The references for the retrieval data used in the response. - :vartype references: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseReference] - """ - - _attribute_map = { - "response": {"key": "response", "type": "[KnowledgeBaseMessage]"}, - "activity": {"key": "activity", "type": "[KnowledgeBaseActivityRecord]"}, - "references": {"key": "references", "type": "[KnowledgeBaseReference]"}, - } - - def __init__( - self, - *, - response: Optional[list["_models.KnowledgeBaseMessage"]] = None, - activity: Optional[list["_models.KnowledgeBaseActivityRecord"]] = None, - references: Optional[list["_models.KnowledgeBaseReference"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword response: - :paramtype response: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessage] - :keyword activity: The activity records for tracking progress and billing implications. - :paramtype activity: - list[~azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecord] - :keyword references: The references for the retrieval data used in the response. - :paramtype references: - list[~azure.search.documents.knowledgebases.models.KnowledgeBaseReference] - """ - super().__init__(**kwargs) - self.response = response - self.activity = activity - self.references = references - - -class KnowledgeBaseSearchIndexActivityArguments(_serialization.Model): # pylint: disable=name-too-long - """Represents the arguments the search index retrieval activity was run with. - - :ivar search: The search string used to query the search index. - :vartype search: str - :ivar filter: The filter string. - :vartype filter: str - :ivar source_data_fields: What fields were selected for search. - :vartype source_data_fields: - list[~azure.search.documents.knowledgebases.models.SearchIndexFieldReference] - :ivar search_fields: What fields were searched against. - :vartype search_fields: - list[~azure.search.documents.knowledgebases.models.SearchIndexFieldReference] - :ivar semantic_configuration_name: What semantic configuration was used from the search index. - :vartype semantic_configuration_name: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - "filter": {"key": "filter", "type": "str"}, - "source_data_fields": {"key": "sourceDataFields", "type": "[SearchIndexFieldReference]"}, - "search_fields": {"key": "searchFields", "type": "[SearchIndexFieldReference]"}, - "semantic_configuration_name": {"key": "semanticConfigurationName", "type": "str"}, - } - - def __init__( - self, - *, - search: Optional[str] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - source_data_fields: Optional[list["_models.SearchIndexFieldReference"]] = None, - search_fields: Optional[list["_models.SearchIndexFieldReference"]] = None, - semantic_configuration_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword search: The search string used to query the search index. - :paramtype search: str - :keyword filter: The filter string. - :paramtype filter: str - :keyword source_data_fields: What fields were selected for search. - :paramtype source_data_fields: - list[~azure.search.documents.knowledgebases.models.SearchIndexFieldReference] - :keyword search_fields: What fields were searched against. - :paramtype search_fields: - list[~azure.search.documents.knowledgebases.models.SearchIndexFieldReference] - :keyword semantic_configuration_name: What semantic configuration was used from the search - index. - :paramtype semantic_configuration_name: str - """ - super().__init__(**kwargs) - self.search = search - self.filter = filter - self.source_data_fields = source_data_fields - self.search_fields = search_fields - self.semantic_configuration_name = semantic_configuration_name - - -class KnowledgeBaseSearchIndexActivityRecord(KnowledgeBaseRetrievalActivityRecord): - """Represents a search index retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar search_index_arguments: The search index arguments for the retrieval activity. - :vartype search_index_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseSearchIndexActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "search_index_arguments": {"key": "searchIndexArguments", "type": "KnowledgeBaseSearchIndexActivityArguments"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - search_index_arguments: Optional["_models.KnowledgeBaseSearchIndexActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword search_index_arguments: The search index arguments for the retrieval activity. - :paramtype search_index_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseSearchIndexActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - error=error, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "searchIndex" - self.search_index_arguments = search_index_arguments - - -class KnowledgeBaseSearchIndexReference(KnowledgeBaseReference): - """Represents an Azure Search document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar doc_key: The document key for the reference. - :vartype doc_key: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "doc_key": {"key": "docKey", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - doc_key: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword doc_key: The document key for the reference. - :paramtype doc_key: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "searchIndex" - self.doc_key = doc_key - - -class KnowledgeBaseWebActivityArguments(_serialization.Model): - """Represents the arguments the web retrieval activity was run with. - - :ivar search: The search string used to query the web. - :vartype search: str - :ivar language: The language for the retrieval activity. - :vartype language: str - :ivar market: The market for the retrieval activity. - :vartype market: str - :ivar count: The number of web results returned. - :vartype count: int - :ivar freshness: The freshness for the retrieval activity. - :vartype freshness: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - "language": {"key": "language", "type": "str"}, - "market": {"key": "market", "type": "str"}, - "count": {"key": "count", "type": "int"}, - "freshness": {"key": "freshness", "type": "str"}, - } - - def __init__( - self, - *, - search: Optional[str] = None, - language: Optional[str] = None, - market: Optional[str] = None, - count: Optional[int] = None, - freshness: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword search: The search string used to query the web. - :paramtype search: str - :keyword language: The language for the retrieval activity. - :paramtype language: str - :keyword market: The market for the retrieval activity. - :paramtype market: str - :keyword count: The number of web results returned. - :paramtype count: int - :keyword freshness: The freshness for the retrieval activity. - :paramtype freshness: str - """ - super().__init__(**kwargs) - self.search = search - self.language = language - self.market = market - self.count = count - self.freshness = freshness - - -class KnowledgeBaseWebActivityRecord(KnowledgeBaseRetrievalActivityRecord): - """Represents a web retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar web_arguments: The web arguments for the retrieval activity. - :vartype web_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseWebActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "error": {"key": "error", "type": "KnowledgeBaseErrorDetail"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "web_arguments": {"key": "webArguments", "type": "KnowledgeBaseWebActivityArguments"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - error: Optional["_models.KnowledgeBaseErrorDetail"] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - web_arguments: Optional["_models.KnowledgeBaseWebActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword error: The error detail explaining why the operation failed. This property is only - included when the activity does not succeed. - :paramtype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword web_arguments: The web arguments for the retrieval activity. - :paramtype web_arguments: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseWebActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - error=error, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "web" - self.web_arguments = web_arguments - - -class KnowledgeBaseWebReference(KnowledgeBaseReference): - """Represents a web document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar url: The url the reference data originated from. - :vartype url: str - :ivar title: The title of the web document. - :vartype title: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "url": {"key": "url", "type": "str"}, - "title": {"key": "title", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - url: Optional[str] = None, - title: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword url: The url the reference data originated from. - :paramtype url: str - :keyword title: The title of the web document. - :paramtype title: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "web" - self.url = url - self.title = title - - -class KnowledgeRetrievalIntent(_serialization.Model): - """An intended query to execute without model query planning. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeRetrievalSemanticIntent - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the intent. Required. "semantic" - :vartype type: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntentType - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - } - - _subtype_map = {"type": {"semantic": "KnowledgeRetrievalSemanticIntent"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - - -class KnowledgeRetrievalReasoningEffort(_serialization.Model): - """KnowledgeRetrievalReasoningEffort. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeRetrievalLowReasoningEffort, KnowledgeRetrievalMediumReasoningEffort, - KnowledgeRetrievalMinimalReasoningEffort - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": { - "low": "KnowledgeRetrievalLowReasoningEffort", - "medium": "KnowledgeRetrievalMediumReasoningEffort", - "minimal": "KnowledgeRetrievalMinimalReasoningEffort", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class KnowledgeRetrievalLowReasoningEffort(KnowledgeRetrievalReasoningEffort): - """Run knowledge retrieval with low reasoning effort. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: str = "low" - - -class KnowledgeRetrievalMediumReasoningEffort(KnowledgeRetrievalReasoningEffort): - """Run knowledge retrieval with medium reasoning effort. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: str = "medium" - - -class KnowledgeRetrievalMinimalReasoningEffort(KnowledgeRetrievalReasoningEffort): - """Run knowledge retrieval with minimal reasoning effort. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and - "medium". - :vartype kind: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: str = "minimal" - - -class KnowledgeRetrievalSemanticIntent(KnowledgeRetrievalIntent): - """KnowledgeRetrievalSemanticIntent. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the intent. Required. "semantic" - :vartype type: str or - ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntentType - :ivar search: The semantic query to execute. Required. - :vartype search: str - """ - - _validation = { - "type": {"required": True}, - "search": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "search": {"key": "search", "type": "str"}, - } - - def __init__(self, *, search: str, **kwargs: Any) -> None: - """ - :keyword search: The semantic query to execute. Required. - :paramtype search: str - """ - super().__init__(**kwargs) - self.type: str = "semantic" - self.search = search - - -class RemoteSharePointKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a remote SharePoint knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - :ivar filter_expression_add_on: A filter condition applied to the SharePoint data source. It - must be specified in the Keyword Query Language syntax. It will be combined as a conjunction - with the filter expression specified in the knowledge source definition. - :vartype filter_expression_add_on: str - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - "filter_expression_add_on": {"key": "filterExpressionAddOn", "type": "str"}, - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - filter_expression_add_on: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - :keyword filter_expression_add_on: A filter condition applied to the SharePoint data source. It - must be specified in the Keyword Query Language syntax. It will be combined as a conjunction - with the filter expression specified in the knowledge source definition. - :paramtype filter_expression_add_on: str - """ - super().__init__( - knowledge_source_name=knowledge_source_name, - include_references=include_references, - include_reference_source_data=include_reference_source_data, - always_query_source=always_query_source, - reranker_threshold=reranker_threshold, - **kwargs - ) - self.kind: str = "remoteSharePoint" - self.filter_expression_add_on = filter_expression_add_on - - -class RequestOptions(_serialization.Model): - """Parameter group. - - :ivar x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :vartype x_ms_client_request_id: str - """ - - _attribute_map = { - "x_ms_client_request_id": {"key": "x-ms-client-request-id", "type": "str"}, - } - - def __init__(self, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :paramtype x_ms_client_request_id: str - """ - super().__init__(**kwargs) - self.x_ms_client_request_id = x_ms_client_request_id - - -class SearchIndexFieldReference(_serialization.Model): - """SearchIndexFieldReference. - - All required parameters must be populated in order to send to server. - - :ivar name: Required. - :vartype name: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - - -class SearchIndexKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a search index knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - :ivar filter_add_on: A filter condition applied to the index (e.g., 'State eq VA'). - :vartype filter_add_on: str - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - "filter_add_on": {"key": "filterAddOn", "type": "str"}, - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - filter_add_on: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - :keyword filter_add_on: A filter condition applied to the index (e.g., 'State eq VA'). - :paramtype filter_add_on: str - """ - super().__init__( - knowledge_source_name=knowledge_source_name, - include_references=include_references, - include_reference_source_data=include_reference_source_data, - always_query_source=always_query_source, - reranker_threshold=reranker_threshold, - **kwargs - ) - self.kind: str = "searchIndex" - self.filter_add_on = filter_add_on - - -class SharePointSensitivityLabelInfo(_serialization.Model): - """Information about the sensitivity label applied to a SharePoint document. - - :ivar display_name: The display name for the sensitivity label. - :vartype display_name: str - :ivar sensitivity_label_id: The ID of the sensitivity label. - :vartype sensitivity_label_id: str - :ivar tooltip: The tooltip that should be displayed for the label in a UI. - :vartype tooltip: str - :ivar priority: The priority in which the sensitivity label is applied. - :vartype priority: int - :ivar color: The color that the UI should display for the label, if configured. - :vartype color: str - :ivar is_encrypted: Indicates whether the sensitivity label enforces encryption. - :vartype is_encrypted: bool - """ - - _attribute_map = { - "display_name": {"key": "displayName", "type": "str"}, - "sensitivity_label_id": {"key": "sensitivityLabelId", "type": "str"}, - "tooltip": {"key": "tooltip", "type": "str"}, - "priority": {"key": "priority", "type": "int"}, - "color": {"key": "color", "type": "str"}, - "is_encrypted": {"key": "isEncrypted", "type": "bool"}, - } - - def __init__( - self, - *, - display_name: Optional[str] = None, - sensitivity_label_id: Optional[str] = None, - tooltip: Optional[str] = None, - priority: Optional[int] = None, - color: Optional[str] = None, - is_encrypted: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword display_name: The display name for the sensitivity label. - :paramtype display_name: str - :keyword sensitivity_label_id: The ID of the sensitivity label. - :paramtype sensitivity_label_id: str - :keyword tooltip: The tooltip that should be displayed for the label in a UI. - :paramtype tooltip: str - :keyword priority: The priority in which the sensitivity label is applied. - :paramtype priority: int - :keyword color: The color that the UI should display for the label, if configured. - :paramtype color: str - :keyword is_encrypted: Indicates whether the sensitivity label enforces encryption. - :paramtype is_encrypted: bool - """ - super().__init__(**kwargs) - self.display_name = display_name - self.sensitivity_label_id = sensitivity_label_id - self.tooltip = tooltip - self.priority = priority - self.color = color - self.is_encrypted = is_encrypted - - -class WebKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a web knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", - "azureBlob", "web", "remoteSharePoint", "indexedSharePoint", and "indexedOneLake". - :vartype kind: str or ~azure.search.documents.knowledgebases.models.KnowledgeSourceKind - :ivar language: The language of the web results. - :vartype language: str - :ivar market: The market of the web results. - :vartype market: str - :ivar count: The number of web results to return. - :vartype count: int - :ivar freshness: The freshness of web results. - :vartype freshness: str - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - "kind": {"key": "kind", "type": "str"}, - "language": {"key": "language", "type": "str"}, - "market": {"key": "market", "type": "str"}, - "count": {"key": "count", "type": "int"}, - "freshness": {"key": "freshness", "type": "str"}, - } - - def __init__( - self, - *, - knowledge_source_name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - reranker_threshold: Optional[float] = None, - language: Optional[str] = None, - market: Optional[str] = None, - count: Optional[int] = None, - freshness: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - :keyword language: The language of the web results. - :paramtype language: str - :keyword market: The market of the web results. - :paramtype market: str - :keyword count: The number of web results to return. - :paramtype count: int - :keyword freshness: The freshness of web results. - :paramtype freshness: str - """ - super().__init__( - knowledge_source_name=knowledge_source_name, - include_references=include_references, - include_reference_source_data=include_reference_source_data, - always_query_source=always_query_source, - reranker_threshold=reranker_threshold, - **kwargs - ) - self.kind: str = "web" - self.language = language - self.market = market - self.count = count - self.freshness = freshness diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/py.typed b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_knowledgebase_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_knowledgebase_client.py deleted file mode 100644 index bb6900e773ab..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_knowledgebase_client.py +++ /dev/null @@ -1,101 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Union, Optional, IO - -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from .._api_versions import DEFAULT_VERSION -from ._generated import KnowledgeBaseRetrievalClient as _KnowledgeBaseRetrievalClient -from ._generated.models import ( - KnowledgeBaseRetrievalRequest, - RequestOptions, - KnowledgeBaseRetrievalResponse, -) -from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy -from .._version import SDK_MONIKER - - -class KnowledgeBaseRetrievalClient(HeadersMixin): - """A client that can be used to query a knowledge base. - - :param endpoint: The URL endpoint of an Azure search service. - :type endpoint: str - :param knowledge_base_name: The name of the knowledge base. Required. - :type knowledge_base_name: str - :param credential: A credential to authorize search client requests. - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: Sets the audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: _KnowledgeBaseRetrievalClient - - def __init__( - self, - endpoint: str, - knowledge_base_name: str, - credential: Union[AzureKeyCredential, TokenCredential], - **kwargs: Any, - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = endpoint - self._knowledge_base_name = knowledge_base_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _KnowledgeBaseRetrievalClient( - endpoint=endpoint, - knowledge_base_name=knowledge_base_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = _KnowledgeBaseRetrievalClient( - endpoint=endpoint, - knowledge_base_name=knowledge_base_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self.knowledge_retrieval = self._client.knowledge_retrieval - - def __repr__(self) -> str: - return "".format( - repr(self._endpoint), repr(self._knowledge_base_name) - )[:1024] - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - @distributed_trace - def retrieve( - self, - retrieval_request: Union[KnowledgeBaseRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[RequestOptions] = None, - **kwargs: Any - ) -> KnowledgeBaseRetrievalResponse: - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return self._client.knowledge_retrieval.retrieve( - retrieval_request=retrieval_request, - x_ms_query_source_authorization=x_ms_query_source_authorization, - request_options=request_options, - **kwargs - ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/__init__.py similarity index 64% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/__init__.py index 60ca88c85f3c..6d56cb9d9b3f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._knowledge_retrieval_operations import KnowledgeRetrievalOperations # type: ignore +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "KnowledgeRetrievalOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_knowledge_retrieval_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/_operations.py similarity index 50% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_knowledge_retrieval_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/_operations.py index 636ba80ec25b..efa6e7fb7e28 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/operations/_knowledge_retrieval_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/_operations.py @@ -1,10 +1,13 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from collections.abc import MutableMapping from io import IOBase +import json from typing import Any, Callable, IO, Optional, TypeVar, Union, overload from azure.core import PipelineClient @@ -14,6 +17,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -21,10 +26,14 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models1 +from ... import models as _models2 +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Serializer +from ..._utils.utils import ClientMixinABC from .._configuration import KnowledgeBaseRetrievalClientConfiguration -from .._utils.serialization import Deserializer, Serializer +JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -32,85 +41,69 @@ _SERIALIZER.client_side_validation = False -def build_retrieve_request( - *, - x_ms_client_request_id: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs: Any +def build_knowledge_base_retrieval_retrieve_request( # pylint: disable=name-too-long + knowledge_base_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json;odata.metadata=minimal") # Construct URL - _url = kwargs.pop("template_url", "/retrieve") + _url = "/retrieve/{knowledgeBaseName}" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if query_source_authorization is not None: _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" + "query_source_authorization", query_source_authorization, "str" ) if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class KnowledgeRetrievalOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient`'s - :attr:`knowledge_retrieval` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: KnowledgeBaseRetrievalClientConfiguration = ( - input_args.pop(0) if input_args else kwargs.pop("config") - ) - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _KnowledgeBaseRetrievalClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], KnowledgeBaseRetrievalClientConfiguration] +): @overload def retrieve( self, - retrieval_request: _models.KnowledgeBaseRetrievalRequest, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, + knowledge_base_name: str, + retrieval_request: _models1.KnowledgeBaseRetrievalRequest, *, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.KnowledgeBaseRetrievalResponse: + ) -> _models1.KnowledgeBaseRetrievalResponse: """KnowledgeBase retrieves relevant data from backing stores. + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str :param retrieval_request: The retrieval request to process. Required. :type retrieval_request: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being + :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.knowledgebases.models.RequestOptions + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeBaseRetrievalResponse or the result of cls(response) + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse :raises ~azure.core.exceptions.HttpResponseError: """ @@ -118,27 +111,57 @@ def retrieve( @overload def retrieve( self, + knowledge_base_name: str, + retrieval_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def retrieve( + self, + knowledge_base_name: str, retrieval_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, *, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.KnowledgeBaseRetrievalResponse: + ) -> _models1.KnowledgeBaseRetrievalResponse: """KnowledgeBase retrieves relevant data from backing stores. + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str :param retrieval_request: The retrieval request to process. Required. :type retrieval_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being + :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.knowledgebases.models.RequestOptions + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeBaseRetrievalResponse or the result of cls(response) + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse :raises ~azure.core.exceptions.HttpResponseError: """ @@ -146,24 +169,27 @@ def retrieve( @distributed_trace def retrieve( self, - retrieval_request: Union[_models.KnowledgeBaseRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, + knowledge_base_name: str, + retrieval_request: Union[_models1.KnowledgeBaseRetrievalRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models.KnowledgeBaseRetrievalResponse: + ) -> _models1.KnowledgeBaseRetrievalResponse: """KnowledgeBase retrieves relevant data from backing stores. - :param retrieval_request: The retrieval request to process. Is either a - KnowledgeBaseRetrievalRequest type or a IO[bytes] type. Required. + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Is one of the following types: + KnowledgeBaseRetrievalRequest, JSON, IO[bytes] Required. :type retrieval_request: - ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest or IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being + ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest or JSON or + IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.knowledgebases.models.RequestOptions - :return: KnowledgeBaseRetrievalResponse or the result of cls(response) + :paramtype query_source_authorization: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse :raises ~azure.core.exceptions.HttpResponseError: """ @@ -176,42 +202,33 @@ def retrieve( error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseRetrievalResponse] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeBaseRetrievalResponse] = kwargs.pop("cls", None) - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id content_type = content_type or "application/json" - _json = None _content = None if isinstance(retrieval_request, (IOBase, bytes)): _content = retrieval_request else: - _json = self._serialize.body(retrieval_request, "KnowledgeBaseRetrievalRequest") + _content = json.dumps(retrieval_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_retrieve_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, + _request = build_knowledge_base_retrieval_retrieve_request( + knowledge_base_name=knowledge_base_name, + query_source_authorization=query_source_authorization, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "knowledgeBaseName": self._serialize.url( - "self._config.knowledge_base_name", self._config.knowledge_base_name, "str" - ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -219,14 +236,22 @@ def retrieve( response = pipeline_response.http_response if response.status_code not in [200, 206]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.ErrorResponse, - pipeline_response, + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("KnowledgeBaseRetrievalResponse", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeBaseRetrievalResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/models/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/__init__.py similarity index 52% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_utils/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/__init__.py index 4473821c4ebe..8026245c2abc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/_utils/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/__init__.py @@ -1,4 +1,6 @@ # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/model_base.py new file mode 100644 index 000000000000..c402af2afc63 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/model_base.py @@ -0,0 +1,1337 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/serialization.py similarity index 98% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/serialization.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/serialization.py index 9b8154c91dc2..81ec1de5922b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/serialization.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/serialization.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -819,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1755,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1781,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/__init__.py index 9cf619a92074..e682791dd38b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/__init__.py @@ -1,29 +1,29 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._knowledgebase_client_async import KnowledgeBaseRetrievalClient +from typing import TYPE_CHECKING -__all__ = ("KnowledgeBaseRetrievalClient",) +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import KnowledgeBaseRetrievalClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "KnowledgeBaseRetrievalClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_knowledge_base_retrieval_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_client.py similarity index 63% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_knowledge_base_retrieval_client.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_client.py index 59d9df34245f..0bbbb8cd4366 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/aio/_knowledge_base_retrieval_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_client.py @@ -1,45 +1,48 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer +from ..._utils.serialization import Deserializer, Serializer from ._configuration import KnowledgeBaseRetrievalClientConfiguration -from .operations import KnowledgeRetrievalOperations +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class KnowledgeBaseRetrievalClient: - """Client that can be used to query an knowledge base. - :ivar knowledge_retrieval: KnowledgeRetrievalOperations operations - :vartype knowledge_retrieval: - azure.search.documents.knowledgebases.aio.operations.KnowledgeRetrievalOperations - :param endpoint: The endpoint URL of the search service. Required. +class KnowledgeBaseRetrievalClient(_KnowledgeBaseRetrievalClientOperationsMixin): + """KnowledgeBaseRetrievalClient. + + :param endpoint: Service host. Required. :type endpoint: str - :param knowledge_base_name: The name of the knowledge base. Required. - :type knowledge_base_name: str - :keyword api_version: Api Version. Default value is "2025-11-01-preview". Note that overriding - this default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, knowledge_base_name: str, **kwargs: Any + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - _endpoint = "{endpoint}/knowledgebases('{knowledgeBaseName}')" - self._config = KnowledgeBaseRetrievalClientConfiguration( - endpoint=endpoint, knowledge_base_name=knowledge_base_name, **kwargs - ) + _endpoint = "{endpoint}" + self._config = KnowledgeBaseRetrievalClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -60,15 +63,11 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.knowledge_retrieval = KnowledgeRetrievalOperations( - self._client, self._config, self._serialize, self._deserialize - ) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -76,7 +75,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -91,9 +90,6 @@ def _send_request( request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "knowledgeBaseName": self._serialize.url( - "self._config.knowledge_base_name", self._config.knowledge_base_name, "str" - ), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_configuration.py new file mode 100644 index 000000000000..ec28807286a4 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_configuration.py @@ -0,0 +1,74 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from ..._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class KnowledgeBaseRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for KnowledgeBaseRetrievalClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_knowledgebase_client_async.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_knowledgebase_client_async.py deleted file mode 100644 index e850222dae49..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_knowledgebase_client_async.py +++ /dev/null @@ -1,102 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, Any, Optional, IO - -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator_async import distributed_trace_async -from ..._utils import get_authentication_policy -from .._generated.aio import KnowledgeBaseRetrievalClient as _KnowledgeBaseRetrievalClient -from .._generated.models import ( - KnowledgeBaseRetrievalRequest, - RequestOptions, - KnowledgeBaseRetrievalResponse, -) -from ..._api_versions import DEFAULT_VERSION -from ..._headers_mixin import HeadersMixin -from ..._version import SDK_MONIKER - - -class KnowledgeBaseRetrievalClient(HeadersMixin): - """A client that can be used to query a knowledge base. - - :param endpoint: The URL endpoint of an Azure search service. - :type endpoint: str - :param knowledge_base_name: The name of the knowledge base. Required. - :type knowledge_base_name: str - :param credential: A credential to authorize search client requests. - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: Sets the audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: _KnowledgeBaseRetrievalClient - - def __init__( - self, - endpoint: str, - knowledge_base_name: str, - credential: Union[AzureKeyCredential, AsyncTokenCredential], - **kwargs: Any, - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint: str = endpoint - self._knowledge_base_name: str = knowledge_base_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _KnowledgeBaseRetrievalClient( - endpoint=endpoint, - knowledge_base_name=knowledge_base_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = _KnowledgeBaseRetrievalClient( - endpoint=endpoint, - knowledge_base_name=knowledge_base_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self.knowledge_retrieval = self._client.knowledge_retrieval - - def __repr__(self) -> str: - return "".format( - repr(self._endpoint), repr(self._knowledge_base_name) - )[:1024] - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - @distributed_trace_async - async def retrieve( - self, - retrieval_request: Union[KnowledgeBaseRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[RequestOptions] = None, - **kwargs: Any - ) -> KnowledgeBaseRetrievalResponse: - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return await self._client.knowledge_retrieval.retrieve( - retrieval_request=retrieval_request, - x_ms_query_source_authorization=x_ms_query_source_authorization, - request_options=request_options, - **kwargs - ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/__init__.py similarity index 64% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/__init__.py index 749e5a6ba198..6d56cb9d9b3f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._documents_operations import DocumentsOperations # type: ignore +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "DocumentsOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/_operations.py new file mode 100644 index 000000000000..4ebadf1ddfc9 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/_operations.py @@ -0,0 +1,224 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2 +from .... import models as _models3 +from ...._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ...._utils.utils import ClientMixinABC +from ..._operations._operations import build_knowledge_base_retrieval_retrieve_request +from .._configuration import KnowledgeBaseRetrievalClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class _KnowledgeBaseRetrievalClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], KnowledgeBaseRetrievalClientConfiguration] +): + + @overload + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: _models2.KnowledgeBaseRetrievalRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: + ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: Union[_models2.KnowledgeBaseRetrievalRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Is one of the following types: + KnowledgeBaseRetrievalRequest, JSON, IO[bytes] Required. + :type retrieval_request: + ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest or JSON or + IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeBaseRetrievalResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(retrieval_request, (IOBase, bytes)): + _content = retrieval_request + else: + _content = json.dumps(retrieval_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_base_retrieval_retrieve_request( + knowledge_base_name=knowledge_base_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeBaseRetrievalResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/aio/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/__init__.py index 5914bd52e5cf..d232f3747a10 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/__init__.py @@ -1,146 +1,124 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from .._generated.models import ( +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AIServices, AzureBlobKnowledgeSourceParams, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, + CompletedSynchronizationState, IndexedOneLakeKnowledgeSourceParams, IndexedSharePointKnowledgeSourceParams, KnowledgeBaseActivityRecord, KnowledgeBaseAgenticReasoningActivityRecord, - KnowledgeBaseAzureBlobActivityArguments, - KnowledgeBaseAzureBlobActivityRecord, KnowledgeBaseAzureBlobReference, KnowledgeBaseErrorAdditionalInfo, KnowledgeBaseErrorDetail, - KnowledgeBaseIndexedOneLakeActivityArguments, - KnowledgeBaseIndexedOneLakeActivityRecord, + KnowledgeBaseImageContent, KnowledgeBaseIndexedOneLakeReference, - KnowledgeBaseIndexedSharePointActivityArguments, - KnowledgeBaseIndexedSharePointActivityRecord, KnowledgeBaseIndexedSharePointReference, KnowledgeBaseMessage, KnowledgeBaseMessageContent, - KnowledgeBaseMessageContentType, KnowledgeBaseMessageImageContent, - KnowledgeBaseMessageImageContentImage, KnowledgeBaseMessageTextContent, KnowledgeBaseModelAnswerSynthesisActivityRecord, KnowledgeBaseModelQueryPlanningActivityRecord, KnowledgeBaseReference, - KnowledgeBaseRemoteSharePointActivityArguments, - KnowledgeBaseRemoteSharePointActivityRecord, KnowledgeBaseRemoteSharePointReference, - KnowledgeBaseRetrievalActivityRecord, KnowledgeBaseRetrievalRequest, KnowledgeBaseRetrievalResponse, - KnowledgeBaseSearchIndexActivityArguments, - KnowledgeBaseSearchIndexActivityRecord, KnowledgeBaseSearchIndexReference, - KnowledgeBaseWebActivityArguments, - KnowledgeBaseWebActivityRecord, KnowledgeBaseWebReference, KnowledgeRetrievalIntent, - KnowledgeRetrievalIntentType, KnowledgeRetrievalLowReasoningEffort, KnowledgeRetrievalMediumReasoningEffort, KnowledgeRetrievalMinimalReasoningEffort, - KnowledgeRetrievalOutputMode, KnowledgeRetrievalReasoningEffort, - KnowledgeRetrievalReasoningEffortKind, KnowledgeRetrievalSemanticIntent, - KnowledgeSourceKind, + KnowledgeSourceAzureOpenAIVectorizer, + KnowledgeSourceIngestionParameters, KnowledgeSourceParams, + KnowledgeSourceStatistics, + KnowledgeSourceStatus, + KnowledgeSourceVectorizer, RemoteSharePointKnowledgeSourceParams, - RequestOptions, - SearchIndexFieldReference, SearchIndexKnowledgeSourceParams, SharePointSensitivityLabelInfo, + SynchronizationState, WebKnowledgeSourceParams, ) +from ._enums import ( # type: ignore + KnowledgeBaseActivityRecordType, + KnowledgeBaseMessageContentType, + KnowledgeBaseReferenceType, + KnowledgeRetrievalIntentType, + KnowledgeRetrievalOutputMode, + KnowledgeRetrievalReasoningEffortKind, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk -__all__ = ( +__all__ = [ + "AIServices", "AzureBlobKnowledgeSourceParams", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", + "CompletedSynchronizationState", "IndexedOneLakeKnowledgeSourceParams", "IndexedSharePointKnowledgeSourceParams", "KnowledgeBaseActivityRecord", "KnowledgeBaseAgenticReasoningActivityRecord", - "KnowledgeBaseAzureBlobActivityArguments", - "KnowledgeBaseAzureBlobActivityRecord", "KnowledgeBaseAzureBlobReference", "KnowledgeBaseErrorAdditionalInfo", "KnowledgeBaseErrorDetail", - "KnowledgeBaseIndexedOneLakeActivityArguments", - "KnowledgeBaseIndexedOneLakeActivityRecord", + "KnowledgeBaseImageContent", "KnowledgeBaseIndexedOneLakeReference", - "KnowledgeBaseIndexedSharePointActivityArguments", - "KnowledgeBaseIndexedSharePointActivityRecord", "KnowledgeBaseIndexedSharePointReference", "KnowledgeBaseMessage", "KnowledgeBaseMessageContent", - "KnowledgeBaseMessageContentType", "KnowledgeBaseMessageImageContent", - "KnowledgeBaseMessageImageContentImage", "KnowledgeBaseMessageTextContent", "KnowledgeBaseModelAnswerSynthesisActivityRecord", "KnowledgeBaseModelQueryPlanningActivityRecord", "KnowledgeBaseReference", - "KnowledgeBaseRemoteSharePointActivityArguments", - "KnowledgeBaseRemoteSharePointActivityRecord", "KnowledgeBaseRemoteSharePointReference", - "KnowledgeBaseRetrievalActivityRecord", "KnowledgeBaseRetrievalRequest", "KnowledgeBaseRetrievalResponse", - "KnowledgeBaseSearchIndexActivityArguments", - "KnowledgeBaseSearchIndexActivityRecord", "KnowledgeBaseSearchIndexReference", - "KnowledgeBaseWebActivityArguments", - "KnowledgeBaseWebActivityRecord", "KnowledgeBaseWebReference", "KnowledgeRetrievalIntent", - "KnowledgeRetrievalIntentType", "KnowledgeRetrievalLowReasoningEffort", "KnowledgeRetrievalMediumReasoningEffort", "KnowledgeRetrievalMinimalReasoningEffort", - "KnowledgeRetrievalOutputMode", "KnowledgeRetrievalReasoningEffort", - "KnowledgeRetrievalReasoningEffortKind", "KnowledgeRetrievalSemanticIntent", - "KnowledgeSourceKind", + "KnowledgeSourceAzureOpenAIVectorizer", + "KnowledgeSourceIngestionParameters", "KnowledgeSourceParams", + "KnowledgeSourceStatistics", + "KnowledgeSourceStatus", + "KnowledgeSourceVectorizer", "RemoteSharePointKnowledgeSourceParams", - "RequestOptions", - "SearchIndexFieldReference", "SearchIndexKnowledgeSourceParams", "SharePointSensitivityLabelInfo", + "SynchronizationState", "WebKnowledgeSourceParams", -) + "KnowledgeBaseActivityRecordType", + "KnowledgeBaseMessageContentType", + "KnowledgeBaseReferenceType", + "KnowledgeRetrievalIntentType", + "KnowledgeRetrievalOutputMode", + "KnowledgeRetrievalReasoningEffortKind", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_knowledge_base_retrieval_client_enums.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_enums.py similarity index 55% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_knowledge_base_retrieval_client_enums.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_enums.py index e16ce913c7a3..5aa3bfa8f1bc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/_generated/models/_knowledge_base_retrieval_client_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_enums.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -8,6 +10,29 @@ from azure.core import CaseInsensitiveEnumMeta +class KnowledgeBaseActivityRecordType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of activity record.""" + + SEARCH_INDEX = "searchIndex" + """Search index retrieval activity.""" + AZURE_BLOB = "azureBlob" + """Azure Blob retrieval activity.""" + INDEXED_SHARE_POINT = "indexedSharePoint" + """Indexed SharePoint retrieval activity.""" + INDEXED_ONE_LAKE = "indexedOneLake" + """Indexed OneLake retrieval activity.""" + WEB = "web" + """Web retrieval activity.""" + REMOTE_SHARE_POINT = "remoteSharePoint" + """Remote SharePoint retrieval activity.""" + MODEL_QUERY_PLANNING = "modelQueryPlanning" + """LLM query planning activity.""" + MODEL_ANSWER_SYNTHESIS = "modelAnswerSynthesis" + """LLM answer synthesis activity.""" + AGENTIC_REASONING = "agenticReasoning" + """Agentic reasoning activity.""" + + class KnowledgeBaseMessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of message content.""" @@ -17,6 +42,23 @@ class KnowledgeBaseMessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMe """Image message content kind.""" +class KnowledgeBaseReferenceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of reference.""" + + SEARCH_INDEX = "searchIndex" + """Search index document reference.""" + AZURE_BLOB = "azureBlob" + """Azure Blob document reference.""" + INDEXED_SHARE_POINT = "indexedSharePoint" + """Indexed SharePoint document reference.""" + INDEXED_ONE_LAKE = "indexedOneLake" + """Indexed OneLake document reference.""" + WEB = "web" + """Web document reference.""" + REMOTE_SHARE_POINT = "remoteSharePoint" + """Remote SharePoint document reference.""" + + class KnowledgeRetrievalIntentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The kind of knowledge base configuration to use.""" @@ -42,20 +84,3 @@ class KnowledgeRetrievalReasoningEffortKind(str, Enum, metaclass=CaseInsensitive """Use low reasoning during retrieval.""" MEDIUM = "medium" """Use a moderate amount of reasoning during retrieval.""" - - -class KnowledgeSourceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The kind of the knowledge source.""" - - SEARCH_INDEX = "searchIndex" - """A knowledge source that retrieves data from a Search Index.""" - AZURE_BLOB = "azureBlob" - """A knowledge source that retrieves and ingests data from Azure Blob Storage to a Search Index.""" - WEB = "web" - """A knowledge source that retrieves data from the web.""" - REMOTE_SHARE_POINT = "remoteSharePoint" - """A knowledge source that retrieves data from a remote SharePoint endpoint.""" - INDEXED_SHARE_POINT = "indexedSharePoint" - """A knowledge source that retrieves and ingests data from SharePoint to a Search Index.""" - INDEXED_ONE_LAKE = "indexedOneLake" - """A knowledge source that retrieves and ingests data from OneLake to a Search Index.""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_models.py new file mode 100644 index 000000000000..934420f67cd3 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_models.py @@ -0,0 +1,1995 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from ..._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ...indexes.models._enums import KnowledgeSourceKind, VectorSearchVectorizerKind +from ._enums import ( + KnowledgeBaseActivityRecordType, + KnowledgeBaseMessageContentType, + KnowledgeBaseReferenceType, + KnowledgeRetrievalIntentType, + KnowledgeRetrievalReasoningEffortKind, +) + +if TYPE_CHECKING: + from .. import models as _models + from ...indexes import models as _indexes_models3 + + +class AIServices(_Model): + """Parameters for AI Services. + + :ivar uri: The URI of the AI Services endpoint. Required. + :vartype uri: str + :ivar api_key: The API key for accessing AI Services. + :vartype api_key: str + """ + + uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URI of the AI Services endpoint. Required.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """The API key for accessing AI Services.""" + + @overload + def __init__( + self, + *, + uri: str, + api_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSourceParams(_Model): + """Base type for knowledge source runtime parameters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureBlobKnowledgeSourceParams, IndexedOneLakeKnowledgeSourceParams, + IndexedSharePointKnowledgeSourceParams, RemoteSharePointKnowledgeSourceParams, + SearchIndexKnowledgeSourceParams, WebKnowledgeSourceParams + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", + "azureBlob", "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind + """ + + __mapping__: dict[str, _Model] = {} + knowledge_source_name: str = rest_field( + name="knowledgeSourceName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the index the params apply to. Required.""" + include_references: Optional[bool] = rest_field( + name="includeReferences", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether references should be included for data retrieved from this source.""" + include_reference_source_data: Optional[bool] = rest_field( + name="includeReferenceSourceData", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether references should include the structured data obtained during retrieval in + their payload.""" + always_query_source: Optional[bool] = rest_field( + name="alwaysQuerySource", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates that this knowledge source should bypass source selection and always be queried at + retrieval time.""" + reranker_threshold: Optional[float] = rest_field( + name="rerankerThreshold", visibility=["read", "create", "update", "delete", "query"] + ) + """The reranker threshold all retrieved documents must meet to be included in the response.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The type of the knowledge source. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + kind: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureBlobKnowledgeSourceParams(KnowledgeSourceParams, discriminator="azureBlob"): + """Specifies runtime parameters for a azure blob knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that read and ingest data + from Azure Blob Storage to a Search Index. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_BLOB + """ + + kind: Literal[KnowledgeSourceKind.AZURE_BLOB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that read and ingest data from Azure Blob + Storage to a Search Index.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.AZURE_BLOB # type: ignore + + +class CompletedSynchronizationState(_Model): + """Represents the completed state of the last synchronization. + + :ivar start_time: The start time of the last completed synchronization. Required. + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time of the last completed synchronization. Required. + :vartype end_time: ~datetime.datetime + :ivar items_updates_processed: The number of item updates successfully processed in the last + synchronization. Required. + :vartype items_updates_processed: int + :ivar items_updates_failed: The number of item updates that failed in the last synchronization. + Required. + :vartype items_updates_failed: int + :ivar items_skipped: The number of items skipped in the last synchronization. Required. + :vartype items_skipped: int + """ + + start_time: datetime.datetime = rest_field( + name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start time of the last completed synchronization. Required.""" + end_time: datetime.datetime = rest_field( + name="endTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end time of the last completed synchronization. Required.""" + items_updates_processed: int = rest_field( + name="itemsUpdatesProcessed", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of item updates successfully processed in the last synchronization. Required.""" + items_updates_failed: int = rest_field( + name="itemsUpdatesFailed", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of item updates that failed in the last synchronization. Required.""" + items_skipped: int = rest_field(name="itemsSkipped", visibility=["read", "create", "update", "delete", "query"]) + """The number of items skipped in the last synchronization. Required.""" + + @overload + def __init__( + self, + *, + start_time: datetime.datetime, + end_time: datetime.datetime, + items_updates_processed: int, + items_updates_failed: int, + items_skipped: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexedOneLakeKnowledgeSourceParams(KnowledgeSourceParams, discriminator="indexedOneLake"): + """Specifies runtime parameters for a indexed OneLake knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from indexed + OneLake. + :vartype kind: str or ~azure.search.documents.indexes.models.INDEXED_ONE_LAKE + """ + + kind: Literal[KnowledgeSourceKind.INDEXED_ONE_LAKE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from indexed OneLake.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.INDEXED_ONE_LAKE # type: ignore + + +class IndexedSharePointKnowledgeSourceParams(KnowledgeSourceParams, discriminator="indexedSharePoint"): + """Specifies runtime parameters for a indexed SharePoint knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from indexed + SharePoint. + :vartype kind: str or ~azure.search.documents.indexes.models.INDEXED_SHARE_POINT + """ + + kind: Literal[KnowledgeSourceKind.INDEXED_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from indexed SharePoint.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.INDEXED_SHARE_POINT # type: ignore + + +class KnowledgeBaseActivityRecord(_Model): + """Base type for activity records. Tracks execution details, timing, and errors for knowledge base + operations. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseAgenticReasoningActivityRecord, KnowledgeBaseModelAnswerSynthesisActivityRecord, + KnowledgeBaseModelQueryPlanningActivityRecord + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar type: The type of the activity record. Required. Known values are: "searchIndex", + "azureBlob", "indexedSharePoint", "indexedOneLake", "web", "remoteSharePoint", + "modelQueryPlanning", "modelAnswerSynthesis", and "agenticReasoning". + :vartype type: str or + ~azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecordType + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail + """ + + __mapping__: dict[str, _Model] = {} + id: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the activity record. Required.""" + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the activity record. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", \"remoteSharePoint\", + \"modelQueryPlanning\", \"modelAnswerSynthesis\", and \"agenticReasoning\".""" + elapsed_ms: Optional[int] = rest_field(name="elapsedMs", visibility=["read", "create", "update", "delete", "query"]) + """The elapsed time in milliseconds for the retrieval activity.""" + error: Optional["_models.KnowledgeBaseErrorDetail"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The error detail explaining why the operation failed. This property is only included when the + activity does not succeed.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + type: str, + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseAgenticReasoningActivityRecord( + KnowledgeBaseActivityRecord, discriminator="agenticReasoning" +): # pylint: disable=name-too-long + """Represents an agentic reasoning activity record. + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail + :ivar type: The discriminator value. Required. Agentic reasoning activity. + :vartype type: str or ~azure.search.documents.knowledgebases.models.AGENTIC_REASONING + :ivar reasoning_tokens: The number of input tokens for agentic reasoning. + :vartype reasoning_tokens: int + :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. + :vartype retrieval_reasoning_effort: + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort + """ + + type: Literal[KnowledgeBaseActivityRecordType.AGENTIC_REASONING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Agentic reasoning activity.""" + reasoning_tokens: Optional[int] = rest_field( + name="reasoningTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of input tokens for agentic reasoning.""" + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = rest_field( + name="retrievalReasoningEffort", visibility=["read", "create", "update", "delete", "query"] + ) + """The retrieval reasoning effort configuration.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + reasoning_tokens: Optional[int] = None, + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseActivityRecordType.AGENTIC_REASONING # type: ignore + + +class KnowledgeBaseReference(_Model): + """Base type for references. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseAzureBlobReference, KnowledgeBaseIndexedOneLakeReference, + KnowledgeBaseIndexedSharePointReference, KnowledgeBaseRemoteSharePointReference, + KnowledgeBaseSearchIndexReference, KnowledgeBaseWebReference + + :ivar type: The type of the reference. Required. Known values are: "searchIndex", "azureBlob", + "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". + :vartype type: str or ~azure.search.documents.knowledgebases.models.KnowledgeBaseReferenceType + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the reference. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the reference. Required.""" + activity_source: int = rest_field(name="activitySource", visibility=["read", "create", "update", "delete", "query"]) + """The source activity ID for the reference. Required.""" + source_data: Optional[dict[str, Any]] = rest_field( + name="sourceData", visibility=["read", "create", "update", "delete", "query"] + ) + """The source data for the reference.""" + reranker_score: Optional[float] = rest_field( + name="rerankerScore", visibility=["read", "create", "update", "delete", "query"] + ) + """The reranker score for the document reference.""" + + @overload + def __init__( + self, + *, + type: str, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseAzureBlobReference(KnowledgeBaseReference, discriminator="azureBlob"): + """Represents an Azure Blob Storage document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Azure Blob document reference. + :vartype type: str or ~azure.search.documents.knowledgebases.models.AZURE_BLOB + :ivar blob_url: The blob URL for the reference. + :vartype blob_url: str + """ + + type: Literal[KnowledgeBaseReferenceType.AZURE_BLOB] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Azure Blob document reference.""" + blob_url: Optional[str] = rest_field(name="blobUrl", visibility=["read", "create", "update", "delete", "query"]) + """The blob URL for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + blob_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseReferenceType.AZURE_BLOB # type: ignore + + +class KnowledgeBaseErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: dict[str, any] + """ + + type: Optional[str] = rest_field(visibility=["read"]) + """The additional info type.""" + info: Optional[dict[str, Any]] = rest_field(visibility=["read"]) + """The additional info.""" + + +class KnowledgeBaseErrorDetail(_Model): + """The error details. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The error target.""" + details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = rest_field(visibility=["read"]) + """The error details.""" + additional_info: Optional[list["_models.KnowledgeBaseErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read"] + ) + """The error additional info.""" + + +class KnowledgeBaseImageContent(_Model): + """Image content. + + :ivar url: The url of the image. Required. + :vartype url: str + """ + + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url of the image. Required.""" + + @overload + def __init__( + self, + *, + url: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseIndexedOneLakeReference(KnowledgeBaseReference, discriminator="indexedOneLake"): + """Represents an indexed OneLake document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Indexed OneLake document reference. + :vartype type: str or ~azure.search.documents.knowledgebases.models.INDEXED_ONE_LAKE + :ivar doc_url: The document URL for the reference. + :vartype doc_url: str + """ + + type: Literal[KnowledgeBaseReferenceType.INDEXED_ONE_LAKE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Indexed OneLake document reference.""" + doc_url: Optional[str] = rest_field(name="docUrl", visibility=["read", "create", "update", "delete", "query"]) + """The document URL for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + doc_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseReferenceType.INDEXED_ONE_LAKE # type: ignore + + +class KnowledgeBaseIndexedSharePointReference(KnowledgeBaseReference, discriminator="indexedSharePoint"): + """Represents an indexed SharePoint document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Indexed SharePoint document reference. + :vartype type: str or ~azure.search.documents.knowledgebases.models.INDEXED_SHARE_POINT + :ivar doc_url: The document URL for the reference. + :vartype doc_url: str + """ + + type: Literal[KnowledgeBaseReferenceType.INDEXED_SHARE_POINT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Indexed SharePoint document reference.""" + doc_url: Optional[str] = rest_field(name="docUrl", visibility=["read", "create", "update", "delete", "query"]) + """The document URL for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + doc_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseReferenceType.INDEXED_SHARE_POINT # type: ignore + + +class KnowledgeBaseMessage(_Model): + """The natural language message style object. + + :ivar role: The role of the tool response. + :vartype role: str + :ivar content: The content of the message. Required. + :vartype content: + list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContent] + """ + + role: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The role of the tool response.""" + content: list["_models.KnowledgeBaseMessageContent"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The content of the message. Required.""" + + @overload + def __init__( + self, + *, + content: list["_models.KnowledgeBaseMessageContent"], + role: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseMessageContent(_Model): + """Specifies the type of the message content. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseMessageImageContent, KnowledgeBaseMessageTextContent + + :ivar type: The type of the message. Required. Known values are: "text" and "image". + :vartype type: str or + ~azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContentType + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the message. Required. Known values are: \"text\" and \"image\".""" + + @overload + def __init__( + self, + *, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseMessageImageContent(KnowledgeBaseMessageContent, discriminator="image"): + """Image message type. + + :ivar type: The discriminator value. Required. Image message content kind. + :vartype type: str or ~azure.search.documents.knowledgebases.models.IMAGE + :ivar image: The image content. Required. + :vartype image: ~azure.search.documents.knowledgebases.models.KnowledgeBaseImageContent + """ + + type: Literal[KnowledgeBaseMessageContentType.IMAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Image message content kind.""" + image: "_models.KnowledgeBaseImageContent" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The image content. Required.""" + + @overload + def __init__( + self, + *, + image: "_models.KnowledgeBaseImageContent", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseMessageContentType.IMAGE # type: ignore + + +class KnowledgeBaseMessageTextContent(KnowledgeBaseMessageContent, discriminator="text"): + """Text message type. + + :ivar type: The discriminator value. Required. Text message content kind. + :vartype type: str or ~azure.search.documents.knowledgebases.models.TEXT + :ivar text: The text content. Required. + :vartype text: str + """ + + type: Literal[KnowledgeBaseMessageContentType.TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Text message content kind.""" + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text content. Required.""" + + @overload + def __init__( + self, + *, + text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseMessageContentType.TEXT # type: ignore + + +class KnowledgeBaseModelAnswerSynthesisActivityRecord( + KnowledgeBaseActivityRecord, discriminator="modelAnswerSynthesis" +): # pylint: disable=name-too-long + """Represents an LLM answer synthesis activity record. + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail + :ivar type: The discriminator value. Required. LLM answer synthesis activity. + :vartype type: str or ~azure.search.documents.knowledgebases.models.MODEL_ANSWER_SYNTHESIS + :ivar input_tokens: The number of input tokens for the LLM answer synthesis activity. + :vartype input_tokens: int + :ivar output_tokens: The number of output tokens for the LLM answer synthesis activity. + :vartype output_tokens: int + """ + + type: Literal[KnowledgeBaseActivityRecordType.MODEL_ANSWER_SYNTHESIS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. LLM answer synthesis activity.""" + input_tokens: Optional[int] = rest_field( + name="inputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of input tokens for the LLM answer synthesis activity.""" + output_tokens: Optional[int] = rest_field( + name="outputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of output tokens for the LLM answer synthesis activity.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + input_tokens: Optional[int] = None, + output_tokens: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseActivityRecordType.MODEL_ANSWER_SYNTHESIS # type: ignore + + +class KnowledgeBaseModelQueryPlanningActivityRecord( + KnowledgeBaseActivityRecord, discriminator="modelQueryPlanning" +): # pylint: disable=name-too-long + """Represents an LLM query planning activity record. + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail + :ivar type: The discriminator value. Required. LLM query planning activity. + :vartype type: str or ~azure.search.documents.knowledgebases.models.MODEL_QUERY_PLANNING + :ivar input_tokens: The number of input tokens for the LLM query planning activity. + :vartype input_tokens: int + :ivar output_tokens: The number of output tokens for the LLM query planning activity. + :vartype output_tokens: int + """ + + type: Literal[KnowledgeBaseActivityRecordType.MODEL_QUERY_PLANNING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. LLM query planning activity.""" + input_tokens: Optional[int] = rest_field( + name="inputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of input tokens for the LLM query planning activity.""" + output_tokens: Optional[int] = rest_field( + name="outputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of output tokens for the LLM query planning activity.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + input_tokens: Optional[int] = None, + output_tokens: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseActivityRecordType.MODEL_QUERY_PLANNING # type: ignore + + +class KnowledgeBaseRemoteSharePointReference(KnowledgeBaseReference, discriminator="remoteSharePoint"): + """Represents a remote SharePoint document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Remote SharePoint document reference. + :vartype type: str or ~azure.search.documents.knowledgebases.models.REMOTE_SHARE_POINT + :ivar web_url: The url the reference data originated from. + :vartype web_url: str + :ivar search_sensitivity_label_info: Information about the sensitivity label applied to the + SharePoint document. + :vartype search_sensitivity_label_info: + ~azure.search.documents.knowledgebases.models.SharePointSensitivityLabelInfo + """ + + type: Literal[KnowledgeBaseReferenceType.REMOTE_SHARE_POINT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Remote SharePoint document reference.""" + web_url: Optional[str] = rest_field(name="webUrl", visibility=["read", "create", "update", "delete", "query"]) + """The url the reference data originated from.""" + search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = rest_field( + name="searchSensitivityLabelInfo", visibility=["read", "create", "update", "delete", "query"] + ) + """Information about the sensitivity label applied to the SharePoint document.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + web_url: Optional[str] = None, + search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseReferenceType.REMOTE_SHARE_POINT # type: ignore + + +class KnowledgeBaseRetrievalRequest(_Model): + """The input contract for the retrieval request. + + :ivar messages: A list of chat message style input. + :vartype messages: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessage] + :ivar intents: A list of intended queries to execute without model query planning. + :vartype intents: list[~azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntent] + :ivar max_runtime_in_seconds: The maximum runtime in seconds. + :vartype max_runtime_in_seconds: int + :ivar max_output_size: Limits the maximum size of the content in the output. + :vartype max_output_size: int + :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. + :vartype retrieval_reasoning_effort: + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort + :ivar include_activity: Indicates retrieval results should include activity information. + :vartype include_activity: bool + :ivar output_mode: The output configuration for this retrieval. Known values are: + "extractiveData" and "answerSynthesis". + :vartype output_mode: str or + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode + :ivar knowledge_source_params: A list of runtime parameters for the knowledge sources. + :vartype knowledge_source_params: + list[~azure.search.documents.knowledgebases.models.KnowledgeSourceParams] + """ + + messages: Optional[list["_models.KnowledgeBaseMessage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of chat message style input.""" + intents: Optional[list["_models.KnowledgeRetrievalIntent"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of intended queries to execute without model query planning.""" + max_runtime_in_seconds: Optional[int] = rest_field( + name="maxRuntimeInSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum runtime in seconds.""" + max_output_size: Optional[int] = rest_field( + name="maxOutputSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Limits the maximum size of the content in the output.""" + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = rest_field( + name="retrievalReasoningEffort", visibility=["read", "create", "update", "delete", "query"] + ) + """The retrieval reasoning effort configuration.""" + include_activity: Optional[bool] = rest_field( + name="includeActivity", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates retrieval results should include activity information.""" + output_mode: Optional[Union[str, "_models.KnowledgeRetrievalOutputMode"]] = rest_field( + name="outputMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The output configuration for this retrieval. Known values are: \"extractiveData\" and + \"answerSynthesis\".""" + knowledge_source_params: Optional[list["_models.KnowledgeSourceParams"]] = rest_field( + name="knowledgeSourceParams", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of runtime parameters for the knowledge sources.""" + + @overload + def __init__( + self, + *, + messages: Optional[list["_models.KnowledgeBaseMessage"]] = None, + intents: Optional[list["_models.KnowledgeRetrievalIntent"]] = None, + max_runtime_in_seconds: Optional[int] = None, + max_output_size: Optional[int] = None, + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, + include_activity: Optional[bool] = None, + output_mode: Optional[Union[str, "_models.KnowledgeRetrievalOutputMode"]] = None, + knowledge_source_params: Optional[list["_models.KnowledgeSourceParams"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseRetrievalResponse(_Model): + """The output contract for the retrieval response. + + :ivar response: The response messages. + :vartype response: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseMessage] + :ivar activity: The activity records for tracking progress and billing implications. + :vartype activity: + list[~azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecord] + :ivar references: The references for the retrieval data used in the response. + :vartype references: list[~azure.search.documents.knowledgebases.models.KnowledgeBaseReference] + """ + + response: Optional[list["_models.KnowledgeBaseMessage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The response messages.""" + activity: Optional[list["_models.KnowledgeBaseActivityRecord"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The activity records for tracking progress and billing implications.""" + references: Optional[list["_models.KnowledgeBaseReference"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The references for the retrieval data used in the response.""" + + @overload + def __init__( + self, + *, + response: Optional[list["_models.KnowledgeBaseMessage"]] = None, + activity: Optional[list["_models.KnowledgeBaseActivityRecord"]] = None, + references: Optional[list["_models.KnowledgeBaseReference"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseSearchIndexReference(KnowledgeBaseReference, discriminator="searchIndex"): + """Represents an Azure Search document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Search index document reference. + :vartype type: str or ~azure.search.documents.knowledgebases.models.SEARCH_INDEX + :ivar doc_key: The document key for the reference. + :vartype doc_key: str + """ + + type: Literal[KnowledgeBaseReferenceType.SEARCH_INDEX] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Search index document reference.""" + doc_key: Optional[str] = rest_field(name="docKey", visibility=["read", "create", "update", "delete", "query"]) + """The document key for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + doc_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseReferenceType.SEARCH_INDEX # type: ignore + + +class KnowledgeBaseWebReference(KnowledgeBaseReference, discriminator="web"): + """Represents a web document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, any] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Web document reference. + :vartype type: str or ~azure.search.documents.knowledgebases.models.WEB + :ivar url: The url the reference data originated from. + :vartype url: str + :ivar title: The title of the web document. + :vartype title: str + """ + + type: Literal[KnowledgeBaseReferenceType.WEB] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Web document reference.""" + url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url the reference data originated from.""" + title: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The title of the web document.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, Any]] = None, + reranker_score: Optional[float] = None, + url: Optional[str] = None, + title: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseReferenceType.WEB # type: ignore + + +class KnowledgeRetrievalIntent(_Model): + """An intended query to execute without model query planning. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeRetrievalSemanticIntent + + :ivar type: The type of the intent. Required. "semantic" + :vartype type: str or + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntentType + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the intent. Required. \"semantic\"""" + + @overload + def __init__( + self, + *, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeRetrievalReasoningEffort(_Model): + """Base type for reasoning effort. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeRetrievalLowReasoningEffort, KnowledgeRetrievalMediumReasoningEffort, + KnowledgeRetrievalMinimalReasoningEffort + + :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and + "medium". + :vartype kind: str or + ~azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The kind of reasoning effort. Required. Known values are: \"minimal\", \"low\", and \"medium\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeRetrievalLowReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="low"): + """Run knowledge retrieval with low reasoning effort. + + :ivar kind: The discriminator value. Required. Use low reasoning during retrieval. + :vartype kind: str or ~azure.search.documents.knowledgebases.models.LOW + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.LOW] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Use low reasoning during retrieval.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.LOW # type: ignore + + +class KnowledgeRetrievalMediumReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="medium"): + """Run knowledge retrieval with medium reasoning effort. + + :ivar kind: The discriminator value. Required. Use a moderate amount of reasoning during + retrieval. + :vartype kind: str or ~azure.search.documents.knowledgebases.models.MEDIUM + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.MEDIUM] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Use a moderate amount of reasoning during retrieval.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.MEDIUM # type: ignore + + +class KnowledgeRetrievalMinimalReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="minimal"): + """Run knowledge retrieval with minimal reasoning effort. + + :ivar kind: The discriminator value. Required. Does not perform any source selections, query + planning, or iterative search. + :vartype kind: str or ~azure.search.documents.knowledgebases.models.MINIMAL + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.MINIMAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Does not perform any source selections, query planning, or + iterative search.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.MINIMAL # type: ignore + + +class KnowledgeRetrievalSemanticIntent(KnowledgeRetrievalIntent, discriminator="semantic"): + """A semantic query intent. + + :ivar type: The discriminator value. Required. A natural language semantic query intent. + :vartype type: str or ~azure.search.documents.knowledgebases.models.SEMANTIC + :ivar search: The semantic query to execute. Required. + :vartype search: str + """ + + type: Literal[KnowledgeRetrievalIntentType.SEMANTIC] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A natural language semantic query intent.""" + search: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The semantic query to execute. Required.""" + + @overload + def __init__( + self, + *, + search: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeRetrievalIntentType.SEMANTIC # type: ignore + + +class KnowledgeSourceVectorizer(_Model): + """Specifies the vectorization method to be used for knowledge source embedding model. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeSourceAzureOpenAIVectorizer + + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and + "aml". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The name of the kind of vectorization method being configured for use with vector search. + Required. Known values are: \"azureOpenAI\", \"customWebApi\", \"aiServicesVision\", and + \"aml\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSourceAzureOpenAIVectorizer(KnowledgeSourceVectorizer, discriminator="azureOpenAI"): + """Specifies the Azure OpenAI resource used to vectorize a query string. + + :ivar kind: The discriminator value. Required. Generate embeddings using an Azure OpenAI + resource at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_OPEN_AI + :ivar azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI embedding + vectorization. + :vartype azure_open_ai_parameters: + ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters + """ + + kind: Literal[VectorSearchVectorizerKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Generate embeddings using an Azure OpenAI resource at query + time.""" + azure_open_ai_parameters: Optional["_indexes_models3.AzureOpenAIVectorizerParameters"] = rest_field( + name="azureOpenAIParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to Azure OpenAI embedding vectorization.""" + + @overload + def __init__( + self, + *, + azure_open_ai_parameters: Optional["_indexes_models3.AzureOpenAIVectorizerParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AZURE_OPEN_AI # type: ignore + + +class KnowledgeSourceIngestionParameters(_Model): + """Consolidates all general ingestion settings for knowledge sources. + + :ivar identity: An explicit identity to use for this knowledge source. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar embedding_model: Optional vectorizer configuration for vectorizing content. + :vartype embedding_model: + ~azure.search.documents.knowledgebases.models.KnowledgeSourceVectorizer + :ivar chat_completion_model: Optional chat completion model for image verbalization or context + extraction. + :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeBaseModel + :ivar disable_image_verbalization: Indicates whether image verbalization should be disabled. + Default is false. + :vartype disable_image_verbalization: bool + :ivar ingestion_schedule: Optional schedule for data ingestion. + :vartype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule + :ivar ingestion_permission_options: Optional list of permission types to ingest together with + document content. If specified, it will set the indexer permission options for the data source. + :vartype ingestion_permission_options: list[str or + ~azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption] + :ivar content_extraction_mode: Optional content extraction mode. Default is 'minimal'. Known + values are: "minimal" and "standard". + :vartype content_extraction_mode: str or + ~azure.search.documents.indexes.models.KnowledgeSourceContentExtractionMode + :ivar ai_services: Optional AI Services configuration for content processing. + :vartype ai_services: ~azure.search.documents.knowledgebases.models.AIServices + """ + + identity: Optional["_indexes_models3.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An explicit identity to use for this knowledge source.""" + embedding_model: Optional["_models.KnowledgeSourceVectorizer"] = rest_field( + name="embeddingModel", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional vectorizer configuration for vectorizing content.""" + chat_completion_model: Optional["_indexes_models3.KnowledgeBaseModel"] = rest_field( + name="chatCompletionModel", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional chat completion model for image verbalization or context extraction.""" + disable_image_verbalization: Optional[bool] = rest_field( + name="disableImageVerbalization", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether image verbalization should be disabled. Default is false.""" + ingestion_schedule: Optional["_indexes_models3.IndexingSchedule"] = rest_field( + name="ingestionSchedule", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional schedule for data ingestion.""" + ingestion_permission_options: Optional[ + list[Union[str, "_indexes_models3.KnowledgeSourceIngestionPermissionOption"]] + ] = rest_field(name="ingestionPermissionOptions", visibility=["read", "create", "update", "delete", "query"]) + """Optional list of permission types to ingest together with document content. If specified, it + will set the indexer permission options for the data source.""" + content_extraction_mode: Optional[Union[str, "_indexes_models3.KnowledgeSourceContentExtractionMode"]] = rest_field( + name="contentExtractionMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional content extraction mode. Default is 'minimal'. Known values are: \"minimal\" and + \"standard\".""" + ai_services: Optional["_models.AIServices"] = rest_field( + name="aiServices", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional AI Services configuration for content processing.""" + + @overload + def __init__( + self, + *, + identity: Optional["_indexes_models3.SearchIndexerDataIdentity"] = None, + embedding_model: Optional["_models.KnowledgeSourceVectorizer"] = None, + chat_completion_model: Optional["_indexes_models3.KnowledgeBaseModel"] = None, + disable_image_verbalization: Optional[bool] = None, + ingestion_schedule: Optional["_indexes_models3.IndexingSchedule"] = None, + ingestion_permission_options: Optional[ + list[Union[str, "_indexes_models3.KnowledgeSourceIngestionPermissionOption"]] + ] = None, + content_extraction_mode: Optional[Union[str, "_indexes_models3.KnowledgeSourceContentExtractionMode"]] = None, + ai_services: Optional["_models.AIServices"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSourceStatistics(_Model): + """Statistical information about knowledge source synchronization history. + + :ivar total_synchronization: Total number of synchronizations. Required. + :vartype total_synchronization: int + :ivar average_synchronization_duration: Average synchronization duration in HH:MM:SS format. + Required. + :vartype average_synchronization_duration: str + :ivar average_items_processed_per_synchronization: Average items processed per synchronization. + Required. + :vartype average_items_processed_per_synchronization: int + """ + + total_synchronization: int = rest_field( + name="totalSynchronization", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of synchronizations. Required.""" + average_synchronization_duration: str = rest_field( + name="averageSynchronizationDuration", visibility=["read", "create", "update", "delete", "query"] + ) + """Average synchronization duration in HH:MM:SS format. Required.""" + average_items_processed_per_synchronization: int = rest_field( + name="averageItemsProcessedPerSynchronization", visibility=["read", "create", "update", "delete", "query"] + ) + """Average items processed per synchronization. Required.""" + + @overload + def __init__( + self, + *, + total_synchronization: int, + average_synchronization_duration: str, + average_items_processed_per_synchronization: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSourceStatus(_Model): + """Represents the status and synchronization history of a knowledge source. + + :ivar synchronization_status: The current synchronization status. Required. Known values are: + "creating", "active", and "deleting". + :vartype synchronization_status: str or + ~azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus + :ivar synchronization_interval: The synchronization interval (e.g., '1d' for daily). Null if no + schedule is configured. + :vartype synchronization_interval: str + :ivar current_synchronization_state: Current synchronization state that spans multiple indexer + runs. + :vartype current_synchronization_state: + ~azure.search.documents.knowledgebases.models.SynchronizationState + :ivar last_synchronization_state: Details of the last completed synchronization. Null on first + sync. + :vartype last_synchronization_state: + ~azure.search.documents.knowledgebases.models.CompletedSynchronizationState + :ivar statistics: Statistical information about the knowledge source synchronization history. + Null on first sync. + :vartype statistics: ~azure.search.documents.knowledgebases.models.KnowledgeSourceStatistics + """ + + synchronization_status: Union[str, "_indexes_models3.KnowledgeSourceSynchronizationStatus"] = rest_field( + name="synchronizationStatus", visibility=["read", "create", "update", "delete", "query"] + ) + """The current synchronization status. Required. Known values are: \"creating\", \"active\", and + \"deleting\".""" + synchronization_interval: Optional[str] = rest_field( + name="synchronizationInterval", visibility=["read", "create", "update", "delete", "query"] + ) + """The synchronization interval (e.g., '1d' for daily). Null if no schedule is configured.""" + current_synchronization_state: Optional["_models.SynchronizationState"] = rest_field( + name="currentSynchronizationState", visibility=["read", "create", "update", "delete", "query"] + ) + """Current synchronization state that spans multiple indexer runs.""" + last_synchronization_state: Optional["_models.CompletedSynchronizationState"] = rest_field( + name="lastSynchronizationState", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the last completed synchronization. Null on first sync.""" + statistics: Optional["_models.KnowledgeSourceStatistics"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Statistical information about the knowledge source synchronization history. Null on first sync.""" + + @overload + def __init__( + self, + *, + synchronization_status: Union[str, "_indexes_models3.KnowledgeSourceSynchronizationStatus"], + synchronization_interval: Optional[str] = None, + current_synchronization_state: Optional["_models.SynchronizationState"] = None, + last_synchronization_state: Optional["_models.CompletedSynchronizationState"] = None, + statistics: Optional["_models.KnowledgeSourceStatistics"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RemoteSharePointKnowledgeSourceParams(KnowledgeSourceParams, discriminator="remoteSharePoint"): + """Specifies runtime parameters for a remote SharePoint knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from remote + SharePoint. + :vartype kind: str or ~azure.search.documents.indexes.models.REMOTE_SHARE_POINT + :ivar filter_expression_add_on: A filter condition applied to the SharePoint data source. It + must be specified in the Keyword Query Language syntax. It will be combined as a conjunction + with the filter expression specified in the knowledge source definition. + :vartype filter_expression_add_on: str + """ + + kind: Literal[KnowledgeSourceKind.REMOTE_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from remote SharePoint.""" + filter_expression_add_on: Optional[str] = rest_field( + name="filterExpressionAddOn", visibility=["read", "create", "update", "delete", "query"] + ) + """A filter condition applied to the SharePoint data source. It must be specified in the Keyword + Query Language syntax. It will be combined as a conjunction with the filter expression + specified in the knowledge source definition.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + filter_expression_add_on: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.REMOTE_SHARE_POINT # type: ignore + + +class SearchIndexKnowledgeSourceParams(KnowledgeSourceParams, discriminator="searchIndex"): + """Specifies runtime parameters for a search index knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from a Search + Index. + :vartype kind: str or ~azure.search.documents.indexes.models.SEARCH_INDEX + :ivar filter_add_on: A filter condition applied to the index (e.g., 'State eq VA'). + :vartype filter_add_on: str + """ + + kind: Literal[KnowledgeSourceKind.SEARCH_INDEX] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from a Search Index.""" + filter_add_on: Optional[str] = rest_field( + name="filterAddOn", visibility=["read", "create", "update", "delete", "query"] + ) + """A filter condition applied to the index (e.g., 'State eq VA').""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + filter_add_on: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.SEARCH_INDEX # type: ignore + + +class SharePointSensitivityLabelInfo(_Model): + """Information about the sensitivity label applied to a SharePoint document. + + :ivar display_name: The display name for the sensitivity label. + :vartype display_name: str + :ivar sensitivity_label_id: The ID of the sensitivity label. + :vartype sensitivity_label_id: str + :ivar tooltip: The tooltip that should be displayed for the label in a UI. + :vartype tooltip: str + :ivar priority: The priority in which the sensitivity label is applied. + :vartype priority: int + :ivar color: The color that the UI should display for the label, if configured. + :vartype color: str + :ivar is_encrypted: Indicates whether the sensitivity label enforces encryption. + :vartype is_encrypted: bool + """ + + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """The display name for the sensitivity label.""" + sensitivity_label_id: Optional[str] = rest_field( + name="sensitivityLabelId", visibility=["read", "create", "update", "delete", "query"] + ) + """The ID of the sensitivity label.""" + tooltip: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The tooltip that should be displayed for the label in a UI.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The priority in which the sensitivity label is applied.""" + color: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The color that the UI should display for the label, if configured.""" + is_encrypted: Optional[bool] = rest_field( + name="isEncrypted", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether the sensitivity label enforces encryption.""" + + @overload + def __init__( + self, + *, + display_name: Optional[str] = None, + sensitivity_label_id: Optional[str] = None, + tooltip: Optional[str] = None, + priority: Optional[int] = None, + color: Optional[str] = None, + is_encrypted: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SynchronizationState(_Model): + """Represents the current state of an ongoing synchronization that spans multiple indexer runs. + + :ivar start_time: The start time of the current synchronization. Required. + :vartype start_time: ~datetime.datetime + :ivar items_updates_processed: The number of item updates successfully processed in the current + synchronization. Required. + :vartype items_updates_processed: int + :ivar items_updates_failed: The number of item updates that failed in the current + synchronization. Required. + :vartype items_updates_failed: int + :ivar items_skipped: The number of items skipped in the current synchronization. Required. + :vartype items_skipped: int + """ + + start_time: datetime.datetime = rest_field( + name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start time of the current synchronization. Required.""" + items_updates_processed: int = rest_field( + name="itemsUpdatesProcessed", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of item updates successfully processed in the current synchronization. Required.""" + items_updates_failed: int = rest_field( + name="itemsUpdatesFailed", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of item updates that failed in the current synchronization. Required.""" + items_skipped: int = rest_field(name="itemsSkipped", visibility=["read", "create", "update", "delete", "query"]) + """The number of items skipped in the current synchronization. Required.""" + + @overload + def __init__( + self, + *, + start_time: datetime.datetime, + items_updates_processed: int, + items_updates_failed: int, + items_skipped: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class WebKnowledgeSourceParams(KnowledgeSourceParams, discriminator="web"): + """Specifies runtime parameters for a web knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from the web. + :vartype kind: str or ~azure.search.documents.indexes.models.WEB + :ivar language: The language of the web results. + :vartype language: str + :ivar market: The market of the web results. + :vartype market: str + :ivar count: The number of web results to return. + :vartype count: int + :ivar freshness: The freshness of web results. + :vartype freshness: str + """ + + kind: Literal[KnowledgeSourceKind.WEB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from the web.""" + language: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The language of the web results.""" + market: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The market of the web results.""" + count: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of web results to return.""" + freshness: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The freshness of web results.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + language: Optional[str] = None, + market: Optional[str] = None, + count: Optional[int] = None, + freshness: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.WEB # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebases/models/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 3ca7c8d417d7..78fd13d0ebcd 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -1,40 +1,62 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from .._generated.models import ( - AutocompleteMode, +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AutocompleteItem, DebugInfo, - HybridCountAndFacetMode, + DocumentDebugInfo, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + FacetResult, HybridSearch, IndexAction, + IndexDocumentsBatch, IndexingResult, + LookupDocument, QueryAnswerResult, - QueryAnswerType, QueryCaptionResult, QueryResultDocumentInnerHit, + QueryResultDocumentRerankerInput, + QueryResultDocumentSemanticField, + QueryResultDocumentSubscores, + QueryRewritesDebugInfo, + QueryRewritesValuesDebugInfo, + SearchDocumentsResult, + SearchRequest, + SearchResult, + SearchScoreThreshold, + SemanticDebugInfo, + SingleVectorFieldResult, + SuggestResult, + TextResult, + VectorQuery, + VectorSimilarityThreshold, + VectorThreshold, + VectorizableImageBinaryQuery, + VectorizableImageUrlQuery, + VectorizableTextQuery, + VectorizedQuery, + VectorsDebugInfo, +) + +from ._enums import ( # type: ignore + AutocompleteMode, + HybridCountAndFacetMode, + IndexActionType, + QueryAnswerType, QueryCaptionType, QueryDebugMode, QueryLanguage, @@ -43,33 +65,60 @@ QueryType, ScoringStatistics, SearchMode, - SearchScoreThreshold, SemanticErrorMode, SemanticErrorReason, + SemanticFieldState, + SemanticQueryRewritesResultType, SemanticSearchResultsType, VectorFilterMode, - VectorSimilarityThreshold, - VectorThreshold, + VectorQueryKind, VectorThresholdKind, - VectorizableImageBinaryQuery, - VectorizableImageUrlQuery, - VectorizedQuery, - VectorizableTextQuery, - VectorQuery, ) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk - -__all__ = ( - "AutocompleteMode", +__all__ = [ + "AutocompleteItem", "DebugInfo", - "HybridCountAndFacetMode", + "DocumentDebugInfo", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "FacetResult", "HybridSearch", "IndexAction", + "IndexDocumentsBatch", "IndexingResult", + "LookupDocument", "QueryAnswerResult", - "QueryAnswerType", "QueryCaptionResult", "QueryResultDocumentInnerHit", + "QueryResultDocumentRerankerInput", + "QueryResultDocumentSemanticField", + "QueryResultDocumentSubscores", + "QueryRewritesDebugInfo", + "QueryRewritesValuesDebugInfo", + "SearchDocumentsResult", + "SearchRequest", + "SearchResult", + "SearchScoreThreshold", + "SemanticDebugInfo", + "SingleVectorFieldResult", + "SuggestResult", + "TextResult", + "VectorQuery", + "VectorSimilarityThreshold", + "VectorThreshold", + "VectorizableImageBinaryQuery", + "VectorizableImageUrlQuery", + "VectorizableTextQuery", + "VectorizedQuery", + "VectorsDebugInfo", + "AutocompleteMode", + "HybridCountAndFacetMode", + "IndexActionType", + "QueryAnswerType", "QueryCaptionType", "QueryDebugMode", "QueryLanguage", @@ -78,17 +127,14 @@ "QueryType", "ScoringStatistics", "SearchMode", - "SearchScoreThreshold", "SemanticErrorMode", "SemanticErrorReason", + "SemanticFieldState", + "SemanticQueryRewritesResultType", "SemanticSearchResultsType", "VectorFilterMode", - "VectorSimilarityThreshold", - "VectorThreshold", + "VectorQueryKind", "VectorThresholdKind", - "VectorizableImageBinaryQuery", - "VectorizableImageUrlQuery", - "VectorizedQuery", - "VectorizableTextQuery", - "VectorQuery", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_search_index_client_enums.py b/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py similarity index 95% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/models/_search_index_client_enums.py rename to sdk/search/azure-search-documents/azure/search/documents/models/_enums.py index 4fcd7d8d579c..faaace017aa6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_search_index_client_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py @@ -1,6 +1,9 @@ -# coding=utf-8 +# pylint: disable=enum-must-be-uppercase +# # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.10.8, generator: @autorest/python@6.42.1) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -69,7 +72,7 @@ class QueryAnswerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): appending the pipe character ``|`` followed by the ``threshold-`` option after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is 0.7. The maximum character length of answers can be configured by appending the pipe character - '|' followed by the 'count-\\ :code:``', such as + '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. """ @@ -83,11 +86,11 @@ class QueryAnswerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class QueryCaptionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This parameter is only valid if the query type is ``semantic``. If set, the query returns captions extracted from key passages in the highest ranked documents. When Captions is set to - ``extractive``\\ , highlighting is enabled by default, and can be configured by appending the - pipe character ``|`` followed by the ``highlight-`` option, such as + ``extractive``, highlighting is enabled by default, and can be configured by appending the pipe + character ``|`` followed by the ``highlight-`` option, such as ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of captions - can be configured by appending the pipe character '|' followed by the 'count-\\ :code:``', such as 'extractive|maxcharlength-600'. + can be configured by appending the pipe character '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. """ NONE = "none" @@ -269,7 +272,7 @@ class QueryLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): class QueryRewritesType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This parameter is only valid if the query type is ``semantic``. When QueryRewrites is set to - ``generative``\\ , the query terms are sent to a generate model which will produce 10 (default) + ``generative``, the query terms are sent to a generate model which will produce 10 (default) rewrites to help increase the recall of the request. The requested count can be configured by appending the pipe character ``|`` followed by the ``count-`` option, such as ``generative|count-3``. Defaults to ``None``. @@ -319,9 +322,7 @@ class ScoringStatistics(str, Enum, metaclass=CaseInsensitiveEnumMeta): LOCAL = "local" """The scoring statistics will be calculated locally for lower latency.""" - GLOBAL = "global" - """The scoring statistics will be calculated globally for more consistent scoring.""" - GLOBAL_ENUM = "global" + GLOBALEnum = "global" """The scoring statistics will be calculated globally for more consistent scoring.""" @@ -419,7 +420,7 @@ class VectorQueryKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): class VectorThresholdKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The kind of vector query being performed.""" + """The kind of threshold used to filter vector queries.""" VECTOR_SIMILARITY = "vectorSimilarity" """The results of the vector query will be filtered based on the vector similarity metric. Note diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py new file mode 100644 index 000000000000..aea242bf9ed1 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -0,0 +1,1680 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import VectorQueryKind, VectorThresholdKind + +if TYPE_CHECKING: + from .. import models as _models + + +class AutocompleteItem(_Model): + """The result of Autocomplete requests. + + :ivar text: The completed term. Required. + :vartype text: str + :ivar query_plus_text: The query along with the completed term. Required. + :vartype query_plus_text: str + """ + + text: str = rest_field(visibility=["read"]) + """The completed term. Required.""" + query_plus_text: str = rest_field(name="queryPlusText", visibility=["read"]) + """The query along with the completed term. Required.""" + + +class AutocompleteResult(_Model): + """The result of Autocomplete query. + + :ivar coverage: A value indicating the percentage of the index that was considered by the + autocomplete request, or null if minimumCoverage was not specified in the request. + :vartype coverage: float + :ivar results: The list of returned Autocompleted items. Required. + :vartype results: list[~azure.search.documents.models.AutocompleteItem] + """ + + coverage: Optional[float] = rest_field(name="@search.coverage", visibility=["read"]) + """A value indicating the percentage of the index that was considered by the autocomplete request, + or null if minimumCoverage was not specified in the request.""" + results: list["_models.AutocompleteItem"] = rest_field(name="value", visibility=["read"]) + """The list of returned Autocompleted items. Required.""" + + +class DebugInfo(_Model): + """Contains debugging information that can be used to further explore your search results. + + :ivar query_rewrites: Contains debugging information specific to query rewrites. + :vartype query_rewrites: ~azure.search.documents.models.QueryRewritesDebugInfo + """ + + query_rewrites: Optional["_models.QueryRewritesDebugInfo"] = rest_field(name="queryRewrites", visibility=["read"]) + """Contains debugging information specific to query rewrites.""" + + +class DocumentDebugInfo(_Model): + """Contains debugging information that can be used to further explore your search results. + + :ivar semantic: Contains debugging information specific to semantic ranking requests. + :vartype semantic: ~azure.search.documents.models.SemanticDebugInfo + :ivar vectors: Contains debugging information specific to vector and hybrid search. + :vartype vectors: ~azure.search.documents.models.VectorsDebugInfo + :ivar inner_hits: Contains debugging information specific to vectors matched within a + collection of complex types. + :vartype inner_hits: dict[str, + list[~azure.search.documents.models.QueryResultDocumentInnerHit]] + """ + + semantic: Optional["_models.SemanticDebugInfo"] = rest_field(visibility=["read"]) + """Contains debugging information specific to semantic ranking requests.""" + vectors: Optional["_models.VectorsDebugInfo"] = rest_field(visibility=["read"]) + """Contains debugging information specific to vector and hybrid search.""" + inner_hits: Optional[dict[str, list["_models.QueryResultDocumentInnerHit"]]] = rest_field( + name="innerHits", visibility=["read"] + ) + """Contains debugging information specific to vectors matched within a collection of complex + types.""" + + +class ErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: dict[str, any] + """ + + type: Optional[str] = rest_field(visibility=["read"]) + """The additional info type.""" + info: Optional[dict[str, Any]] = rest_field(visibility=["read"]) + """The additional info.""" + + +class ErrorDetail(_Model): + """The error detail. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.search.documents.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.search.documents.models.ErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The error target.""" + details: Optional[list["_models.ErrorDetail"]] = rest_field(visibility=["read"]) + """The error details.""" + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read"] + ) + """The error additional info.""" + + +class ErrorResponse(_Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.search.documents.models.ErrorDetail + """ + + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error object.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FacetResult(_Model): + """A single bucket of a facet query result. Reports the number of documents with a field value + falling within a particular range or having a particular value or interval. + + :ivar count: The approximate count of documents falling within the bucket described by this + facet. + :vartype count: int + :ivar avg: The resulting total avg for the facet when a avg metric is requested. + :vartype avg: float + :ivar min: The resulting total min for the facet when a min metric is requested. + :vartype min: float + :ivar max: The resulting total max for the facet when a max metric is requested. + :vartype max: float + :ivar sum: The resulting total sum for the facet when a sum metric is requested. + :vartype sum: float + :ivar cardinality: The resulting total cardinality for the facet when a cardinality metric is + requested. + :vartype cardinality: int + :ivar facets: The nested facet query results for the search operation, organized as a + collection of buckets for each faceted field; null if the query did not contain any nested + facets. + :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] + """ + + count: Optional[int] = rest_field(visibility=["read"]) + """The approximate count of documents falling within the bucket described by this facet.""" + avg: Optional[float] = rest_field(visibility=["read"]) + """The resulting total avg for the facet when a avg metric is requested.""" + min: Optional[float] = rest_field(visibility=["read"]) + """The resulting total min for the facet when a min metric is requested.""" + max: Optional[float] = rest_field(visibility=["read"]) + """The resulting total max for the facet when a max metric is requested.""" + sum: Optional[float] = rest_field(visibility=["read"]) + """The resulting total sum for the facet when a sum metric is requested.""" + cardinality: Optional[int] = rest_field(visibility=["read"]) + """The resulting total cardinality for the facet when a cardinality metric is requested.""" + facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field(name="@search.facets", visibility=["read"]) + """The nested facet query results for the search operation, organized as a collection of buckets + for each faceted field; null if the query did not contain any nested facets.""" + + +class HybridSearch(_Model): + """TThe query parameters to configure hybrid search behaviors. + + :ivar max_text_recall_size: Determines the maximum number of documents to be retrieved by the + text query portion of a hybrid search request. Those documents will be combined with the + documents matching the vector queries to produce a single final list of results. Choosing a + larger maxTextRecallSize value will allow retrieving and paging through more documents (using + the top and skip parameters), at the cost of higher resource utilization and higher latency. + The value needs to be between 1 and 10,000. Default is 1000. + :vartype max_text_recall_size: int + :ivar count_and_facet_mode: Determines whether the count and facets should includes all + documents that matched the search query, or only the documents that are retrieved within the + 'maxTextRecallSize' window. Known values are: "countRetrievableResults" and "countAllResults". + :vartype count_and_facet_mode: str or ~azure.search.documents.models.HybridCountAndFacetMode + """ + + max_text_recall_size: Optional[int] = rest_field( + name="maxTextRecallSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines the maximum number of documents to be retrieved by the text query portion of a + hybrid search request. Those documents will be combined with the documents matching the vector + queries to produce a single final list of results. Choosing a larger maxTextRecallSize value + will allow retrieving and paging through more documents (using the top and skip parameters), at + the cost of higher resource utilization and higher latency. The value needs to be between 1 and + 10,000. Default is 1000.""" + count_and_facet_mode: Optional[Union[str, "_models.HybridCountAndFacetMode"]] = rest_field( + name="countAndFacetMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether the count and facets should includes all documents that matched the search + query, or only the documents that are retrieved within the 'maxTextRecallSize' window. Known + values are: \"countRetrievableResults\" and \"countAllResults\".""" + + @overload + def __init__( + self, + *, + max_text_recall_size: Optional[int] = None, + count_and_facet_mode: Optional[Union[str, "_models.HybridCountAndFacetMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexAction(_Model): + """Represents an index action that operates on a document. + + :ivar action_type: The operation to perform on a document in an indexing batch. Known values + are: "upload", "merge", "mergeOrUpload", and "delete". + :vartype action_type: str or ~azure.search.documents.models.IndexActionType + """ + + action_type: Optional[Union[str, "_models.IndexActionType"]] = rest_field( + name="@search.action", visibility=["read", "create", "update", "delete", "query"] + ) + """The operation to perform on a document in an indexing batch. Known values are: \"upload\", + \"merge\", \"mergeOrUpload\", and \"delete\".""" + + @overload + def __init__( + self, + *, + action_type: Optional[Union[str, "_models.IndexActionType"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexDocumentsBatch(_Model): + """Contains a batch of document write actions to send to the index. + + :ivar actions: The actions in the batch. Required. + :vartype actions: list[~azure.search.documents.models.IndexAction] + """ + + actions: list["_models.IndexAction"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The actions in the batch. Required.""" + + @overload + def __init__( + self, + *, + actions: list["_models.IndexAction"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexDocumentsResult(_Model): + """Response containing the status of operations for all documents in the indexing request. + + :ivar results: The list of status information for each document in the indexing request. + Required. + :vartype results: list[~azure.search.documents.models.IndexingResult] + """ + + results: list["_models.IndexingResult"] = rest_field(name="value", visibility=["read"]) + """The list of status information for each document in the indexing request. Required.""" + + +class IndexingResult(_Model): + """Status of an indexing operation for a single document. + + :ivar key: The key of a document that was in the indexing request. Required. + :vartype key: str + :ivar error_message: The error message explaining why the indexing operation failed for the + document identified by the key; null if indexing succeeded. + :vartype error_message: str + :ivar succeeded: A value indicating whether the indexing operation succeeded for the document + identified by the key. Required. + :vartype succeeded: bool + :ivar status_code: The status code of the indexing operation. Possible values include: 200 for + a successful update or delete, 201 for successful document creation, 400 for a malformed input + document, 404 for document not found, 409 for a version conflict, 422 when the index is + temporarily unavailable, or 503 for when the service is too busy. Required. + :vartype status_code: int + """ + + key: str = rest_field(visibility=["read"]) + """The key of a document that was in the indexing request. Required.""" + error_message: Optional[str] = rest_field(name="errorMessage", visibility=["read"]) + """The error message explaining why the indexing operation failed for the document identified by + the key; null if indexing succeeded.""" + succeeded: bool = rest_field(name="status", visibility=["read"]) + """A value indicating whether the indexing operation succeeded for the document identified by the + key. Required.""" + status_code: int = rest_field(name="statusCode", visibility=["read"]) + """The status code of the indexing operation. Possible values include: 200 for a successful update + or delete, 201 for successful document creation, 400 for a malformed input document, 404 for + document not found, 409 for a version conflict, 422 when the index is temporarily unavailable, + or 503 for when the service is too busy. Required.""" + + +class LookupDocument(_Model): + """A document retrieved via a document lookup operation.""" + + +class QueryAnswerResult(_Model): + """An answer is a text passage extracted from the contents of the most relevant documents that + matched the query. Answers are extracted from the top search results. Answer candidates are + scored and the top answers are selected. + + :ivar score: The score value represents how relevant the answer is to the query relative to + other answers returned for the query. + :vartype score: float + :ivar key: The key of the document the answer was extracted from. + :vartype key: str + :ivar text: The text passage extracted from the document contents as the answer. + :vartype text: str + :ivar highlights: Same text passage as in the Text property with highlighted text phrases most + relevant to the query. + :vartype highlights: str + """ + + score: Optional[float] = rest_field(visibility=["read"]) + """The score value represents how relevant the answer is to the query relative to other answers + returned for the query.""" + key: Optional[str] = rest_field(visibility=["read"]) + """The key of the document the answer was extracted from.""" + text: Optional[str] = rest_field(visibility=["read"]) + """The text passage extracted from the document contents as the answer.""" + highlights: Optional[str] = rest_field(visibility=["read"]) + """Same text passage as in the Text property with highlighted text phrases most relevant to the + query.""" + + +class QueryCaptionResult(_Model): + """Captions are the most representative passages from the document relatively to the search query. + They are often used as document summary. Captions are only returned for queries of type + ``semantic``. + + :ivar text: A representative text passage extracted from the document most relevant to the + search query. + :vartype text: str + :ivar highlights: Same text passage as in the Text property with highlighted phrases most + relevant to the query. + :vartype highlights: str + """ + + text: Optional[str] = rest_field(visibility=["read"]) + """A representative text passage extracted from the document most relevant to the search query.""" + highlights: Optional[str] = rest_field(visibility=["read"]) + """Same text passage as in the Text property with highlighted phrases most relevant to the query.""" + + +class QueryResultDocumentInnerHit(_Model): + """Detailed scoring information for an individual element of a complex collection. + + :ivar ordinal: Position of this specific matching element within it's original collection. + Position starts at 0. + :vartype ordinal: int + :ivar vectors: Detailed scoring information for an individual element of a complex collection + that matched a vector query. + :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] + """ + + ordinal: Optional[int] = rest_field(visibility=["read"]) + """Position of this specific matching element within it's original collection. Position starts at + 0.""" + vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = rest_field(visibility=["read"]) + """Detailed scoring information for an individual element of a complex collection that matched a + vector query.""" + + +class QueryResultDocumentRerankerInput(_Model): + """The raw concatenated strings that were sent to the semantic enrichment process. + + :ivar title: The raw string for the title field that was used for semantic enrichment. + :vartype title: str + :ivar content: The raw concatenated strings for the content fields that were used for semantic + enrichment. + :vartype content: str + :ivar keywords: The raw concatenated strings for the keyword fields that were used for semantic + enrichment. + :vartype keywords: str + """ + + title: Optional[str] = rest_field(visibility=["read"]) + """The raw string for the title field that was used for semantic enrichment.""" + content: Optional[str] = rest_field(visibility=["read"]) + """The raw concatenated strings for the content fields that were used for semantic enrichment.""" + keywords: Optional[str] = rest_field(visibility=["read"]) + """The raw concatenated strings for the keyword fields that were used for semantic enrichment.""" + + +class QueryResultDocumentSemanticField(_Model): + """Description of fields that were sent to the semantic enrichment process, as well as how they + were used. + + :ivar name: The name of the field that was sent to the semantic enrichment process. + :vartype name: str + :ivar state: The way the field was used for the semantic enrichment process (fully used, + partially used, or unused). Known values are: "used", "unused", and "partial". + :vartype state: str or ~azure.search.documents.models.SemanticFieldState + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the field that was sent to the semantic enrichment process.""" + state: Optional[Union[str, "_models.SemanticFieldState"]] = rest_field(visibility=["read"]) + """The way the field was used for the semantic enrichment process (fully used, partially used, or + unused). Known values are: \"used\", \"unused\", and \"partial\".""" + + +class QueryResultDocumentSubscores(_Model): + """The breakdown of subscores between the text and vector query components of the search query for + this document. Each vector query is shown as a separate object in the same order they were + received. + + :ivar text: The BM25 or Classic score for the text portion of the query. + :vartype text: ~azure.search.documents.models.TextResult + :ivar vectors: The vector similarity and. + :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] + :ivar document_boost: The BM25 or Classic score for the text portion of the query. + :vartype document_boost: float + """ + + text: Optional["_models.TextResult"] = rest_field(visibility=["read"]) + """The BM25 or Classic score for the text portion of the query.""" + vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = rest_field(visibility=["read"]) + """The vector similarity and.""" + document_boost: Optional[float] = rest_field(name="documentBoost", visibility=["read"]) + """The BM25 or Classic score for the text portion of the query.""" + + +class QueryRewritesDebugInfo(_Model): + """Contains debugging information specific to query rewrites. + + :ivar text: List of query rewrites generated for the text query. + :vartype text: ~azure.search.documents.models.QueryRewritesValuesDebugInfo + :ivar vectors: List of query rewrites generated for the vectorizable text queries. + :vartype vectors: list[~azure.search.documents.models.QueryRewritesValuesDebugInfo] + """ + + text: Optional["_models.QueryRewritesValuesDebugInfo"] = rest_field(visibility=["read"]) + """List of query rewrites generated for the text query.""" + vectors: Optional[list["_models.QueryRewritesValuesDebugInfo"]] = rest_field(visibility=["read"]) + """List of query rewrites generated for the vectorizable text queries.""" + + +class QueryRewritesValuesDebugInfo(_Model): + """Contains debugging information specific to query rewrites. + + :ivar input_query: The input text to the generative query rewriting model. There may be cases + where the user query and the input to the generative model are not identical. + :vartype input_query: str + :ivar rewrites: List of query rewrites. + :vartype rewrites: list[str] + """ + + input_query: Optional[str] = rest_field(name="inputQuery", visibility=["read"]) + """The input text to the generative query rewriting model. There may be cases where the user query + and the input to the generative model are not identical.""" + rewrites: Optional[list[str]] = rest_field(visibility=["read"]) + """List of query rewrites.""" + + +class SearchDocumentsResult(_Model): + """Response containing search results from an index. + + :ivar count: The total count of results found by the search operation, or null if the count was + not requested. If present, the count may be greater than the number of results in this + response. This can happen if you use the $top or $skip parameters, or if the query can't return + all the requested documents in a single response. + :vartype count: int + :ivar coverage: A value indicating the percentage of the index that was included in the query, + or null if minimumCoverage was not specified in the request. + :vartype coverage: float + :ivar facets: The facet query results for the search operation, organized as a collection of + buckets for each faceted field; null if the query did not include any facet expressions. + :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] + :ivar answers: The answers query results for the search operation; null if the answers query + parameter was not specified or set to 'none'. + :vartype answers: list[~azure.search.documents.models.QueryAnswerResult] + :ivar debug_info: Debug information that applies to the search results as a whole. + :vartype debug_info: ~azure.search.documents.models.DebugInfo + :ivar next_page_parameters: Continuation JSON payload returned when the query can't return all + the requested results in a single response. You can use this JSON along with. + :vartype next_page_parameters: ~azure.search.documents.models.SearchRequest + :ivar results: The sequence of results returned by the query. Required. + :vartype results: list[~azure.search.documents.models.SearchResult] + :ivar next_link: Continuation URL returned when the query can't return all the requested + results in a single response. You can use this URL to formulate another GET or POST Search + request to get the next part of the search response. Make sure to use the same verb (GET or + POST) as the request that produced this response. + :vartype next_link: str + :ivar semantic_partial_response_reason: Reason that a partial response was returned for a + semantic ranking request. Known values are: "maxWaitExceeded", "capacityOverloaded", and + "transient". + :vartype semantic_partial_response_reason: str or + ~azure.search.documents.models.SemanticErrorReason + :ivar semantic_partial_response_type: Type of partial response that was returned for a semantic + ranking request. Known values are: "baseResults" and "rerankedResults". + :vartype semantic_partial_response_type: str or + ~azure.search.documents.models.SemanticSearchResultsType + :ivar semantic_query_rewrites_result_type: Type of query rewrite that was used to retrieve + documents. "originalQueryOnly" + :vartype semantic_query_rewrites_result_type: str or + ~azure.search.documents.models.SemanticQueryRewritesResultType + """ + + count: Optional[int] = rest_field(name="@odata.count", visibility=["read"]) + """The total count of results found by the search operation, or null if the count was not + requested. If present, the count may be greater than the number of results in this response. + This can happen if you use the $top or $skip parameters, or if the query can't return all the + requested documents in a single response.""" + coverage: Optional[float] = rest_field(name="@search.coverage", visibility=["read"]) + """A value indicating the percentage of the index that was included in the query, or null if + minimumCoverage was not specified in the request.""" + facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field(name="@search.facets", visibility=["read"]) + """The facet query results for the search operation, organized as a collection of buckets for each + faceted field; null if the query did not include any facet expressions.""" + answers: Optional[list["_models.QueryAnswerResult"]] = rest_field(name="@search.answers", visibility=["read"]) + """The answers query results for the search operation; null if the answers query parameter was not + specified or set to 'none'.""" + debug_info: Optional["_models.DebugInfo"] = rest_field(name="@search.debug", visibility=["read"]) + """Debug information that applies to the search results as a whole.""" + next_page_parameters: Optional["_models.SearchRequest"] = rest_field( + name="@search.nextPageParameters", visibility=["read"] + ) + """Continuation JSON payload returned when the query can't return all the requested results in a + single response. You can use this JSON along with.""" + results: list["_models.SearchResult"] = rest_field(name="value", visibility=["read"]) + """The sequence of results returned by the query. Required.""" + next_link: Optional[str] = rest_field(name="@odata.nextLink", visibility=["read"]) + """Continuation URL returned when the query can't return all the requested results in a single + response. You can use this URL to formulate another GET or POST Search request to get the next + part of the search response. Make sure to use the same verb (GET or POST) as the request that + produced this response.""" + semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = rest_field( + name="@search.semanticPartialResponseReason", visibility=["read"] + ) + """Reason that a partial response was returned for a semantic ranking request. Known values are: + \"maxWaitExceeded\", \"capacityOverloaded\", and \"transient\".""" + semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = rest_field( + name="@search.semanticPartialResponseType", visibility=["read"] + ) + """Type of partial response that was returned for a semantic ranking request. Known values are: + \"baseResults\" and \"rerankedResults\".""" + semantic_query_rewrites_result_type: Optional[Union[str, "_models.SemanticQueryRewritesResultType"]] = rest_field( + name="@search.semanticQueryRewritesResultType", visibility=["read"] + ) + """Type of query rewrite that was used to retrieve documents. \"originalQueryOnly\"""" + + +class SearchRequest(_Model): + """Parameters for filtering, sorting, faceting, paging, and other search query behaviors. + + :ivar include_total_count: A value that specifies whether to fetch the total count of results. + Default is false. Setting this value to true may have a performance impact. Note that the count + returned is an approximation. + :vartype include_total_count: bool + :ivar facets: The list of facet expressions to apply to the search query. Each facet expression + contains a field name, optionally followed by a comma-separated list of name:value pairs. + :vartype facets: list[str] + :ivar filter: The OData $filter expression to apply to the search query. + :vartype filter: str + :ivar highlight_fields: The comma-separated list of field names to use for hit highlights. Only + searchable fields can be used for hit highlighting. + :vartype highlight_fields: list[str] + :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. + :vartype highlight_post_tag: str + :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. + :vartype highlight_pre_tag: str + :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. + :vartype minimum_coverage: float + :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :vartype order_by: list[str] + :ivar query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". + :vartype query_type: str or ~azure.search.documents.models.QueryType + :ivar scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". + :vartype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :ivar session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. + :vartype session_id: str + :ivar scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). + :vartype scoring_parameters: list[str] + :ivar scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. + :vartype scoring_profile: str + :ivar debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". + :vartype debug: str or ~azure.search.documents.models.QueryDebugMode + :ivar search_text: A full-text search query expression; Use "*" or omit this parameter to match + all documents. + :vartype search_text: str + :ivar search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. + :vartype search_fields: list[str] + :ivar search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". + :vartype search_mode: str or ~azure.search.documents.models.SearchMode + :ivar query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". + :vartype query_language: str or ~azure.search.documents.models.QueryLanguage + :ivar query_speller: A value that specifies the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". + :vartype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :ivar select: The comma-separated list of fields to retrieve. If unspecified, all fields marked + as retrievable in the schema are included. + :vartype select: list[str] + :ivar skip: The number of search results to skip. This value cannot be greater than 100,000. If + you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. + :vartype skip: int + :ivar top: The number of search results to retrieve. This can be used in conjunction with $skip + to implement client-side paging of search results. If results are truncated due to server-side + paging, the response will include a continuation token that can be used to issue another Search + request for the next page of results. + :vartype top: int + :ivar semantic_configuration_name: The name of a semantic configuration that will be used when + processing documents for queries of type semantic. + :vartype semantic_configuration_name: str + :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". + :vartype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :ivar semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of + time it takes for semantic enrichment to finish processing before the request fails. + :vartype semantic_max_wait_in_milliseconds: int + :ivar semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. + :vartype semantic_query: str + :ivar answers: A value that specifies whether answers should be returned as part of the search + response. Known values are: "none" and "extractive". + :vartype answers: str or ~azure.search.documents.models.QueryAnswerType + :ivar captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". + :vartype captions: str or ~azure.search.documents.models.QueryCaptionType + :ivar query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". + :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :ivar semantic_fields: The comma-separated list of field names used for semantic ranking. + :vartype semantic_fields: list[str] + :ivar vector_queries: The query parameters for vector and hybrid search queries. + :vartype vector_queries: list[~azure.search.documents.models.VectorQuery] + :ivar vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". + :vartype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :ivar hybrid_search: The query parameters to configure hybrid search behaviors. + :vartype hybrid_search: ~azure.search.documents.models.HybridSearch + """ + + include_total_count: Optional[bool] = rest_field( + name="count", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether to fetch the total count of results. Default is false. Setting + this value to true may have a performance impact. Note that the count returned is an + approximation.""" + facets: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of facet expressions to apply to the search query. Each facet expression contains a + field name, optionally followed by a comma-separated list of name:value pairs.""" + filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The OData $filter expression to apply to the search query.""" + highlight_fields: Optional[list[str]] = rest_field( + name="highlight", visibility=["read", "create", "update", "delete", "query"], format="commaDelimited" + ) + """The comma-separated list of field names to use for hit highlights. Only searchable fields can + be used for hit highlighting.""" + highlight_post_tag: Optional[str] = rest_field( + name="highlightPostTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is + </em>.""" + highlight_pre_tag: Optional[str] = rest_field( + name="highlightPreTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is prepended to hit highlights. Must be set with highlightPostTag. Default is + <em>.""" + minimum_coverage: Optional[float] = rest_field( + name="minimumCoverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A number between 0 and 100 indicating the percentage of the index that must be covered by a + search query in order for the query to be reported as a success. This parameter can be useful + for ensuring search availability even for services with only one replica. The default is 100.""" + order_by: Optional[list[str]] = rest_field( + name="orderby", visibility=["read", "create", "update", "delete", "query"], format="commaDelimited" + ) + """The comma-separated list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses.""" + query_type: Optional[Union[str, "_models.QueryType"]] = rest_field( + name="queryType", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if + your query uses the Lucene query syntax. Known values are: \"simple\", \"full\", and + \"semantic\".""" + scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = rest_field( + name="scoringStatistics", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether we want to calculate scoring statistics (such as document + frequency) globally for more consistent scoring, or locally, for lower latency. The default is + 'local'. Use 'global' to aggregate scoring statistics globally before scoring. Using global + scoring statistics can increase latency of search queries. Known values are: \"local\" and + \"global\".""" + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """A value to be used to create a sticky session, which can help getting more consistent results. + As long as the same sessionId is used, a best-effort attempt will be made to target the same + replica set. Be wary that reusing the same sessionID values repeatedly can interfere with the + load balancing of the requests across replicas and adversely affect the performance of the + search service. The value used as sessionId cannot start with a '_' character.""" + scoring_parameters: Optional[list[str]] = rest_field( + name="scoringParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of parameter values to be used in scoring functions (for example, + referencePointParameter) using the format name-values. For example, if the scoring profile + defines a function with a parameter called 'mylocation' the parameter string would be + \"mylocation--122.2,44.8\" (without the quotes).""" + scoring_profile: Optional[str] = rest_field( + name="scoringProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of a scoring profile to evaluate match scores for matching documents in order to sort + the results.""" + debug: Optional[Union[str, "_models.QueryDebugMode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Enables a debugging tool that can be used to further explore your reranked results. Known + values are: \"disabled\", \"semantic\", \"vector\", \"queryRewrites\", \"innerHits\", and + \"all\".""" + search_text: Optional[str] = rest_field(name="search", visibility=["read", "create", "update", "delete", "query"]) + """A full-text search query expression; Use \"*\" or omit this parameter to match all documents.""" + search_fields: Optional[list[str]] = rest_field( + name="searchFields", visibility=["read", "create", "update", "delete", "query"], format="commaDelimited" + ) + """The comma-separated list of field names to which to scope the full-text search. When using + fielded search (fieldName:searchExpression) in a full Lucene query, the field names of each + fielded search expression take precedence over any field names listed in this parameter.""" + search_mode: Optional[Union[str, "_models.SearchMode"]] = rest_field( + name="searchMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether any or all of the search terms must be matched in order to count + the document as a match. Known values are: \"any\" and \"all\".""" + query_language: Optional[Union[str, "_models.QueryLanguage"]] = rest_field( + name="queryLanguage", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies the language of the search query. Known values are: \"none\", \"en-us\", + \"en-gb\", \"en-in\", \"en-ca\", \"en-au\", \"fr-fr\", \"fr-ca\", \"de-de\", \"es-es\", + \"es-mx\", \"zh-cn\", \"zh-tw\", \"pt-br\", \"pt-pt\", \"it-it\", \"ja-jp\", \"ko-kr\", + \"ru-ru\", \"cs-cz\", \"nl-be\", \"nl-nl\", \"hu-hu\", \"pl-pl\", \"sv-se\", \"tr-tr\", + \"hi-in\", \"ar-sa\", \"ar-eg\", \"ar-ma\", \"ar-kw\", \"ar-jo\", \"da-dk\", \"no-no\", + \"bg-bg\", \"hr-hr\", \"hr-ba\", \"ms-my\", \"ms-bn\", \"sl-sl\", \"ta-in\", \"vi-vn\", + \"el-gr\", \"ro-ro\", \"is-is\", \"id-id\", \"th-th\", \"lt-lt\", \"uk-ua\", \"lv-lv\", + \"et-ee\", \"ca-es\", \"fi-fi\", \"sr-ba\", \"sr-me\", \"sr-rs\", \"sk-sk\", \"nb-no\", + \"hy-am\", \"bn-in\", \"eu-es\", \"gl-es\", \"gu-in\", \"he-il\", \"ga-ie\", \"kn-in\", + \"ml-in\", \"mr-in\", \"fa-ae\", \"pa-in\", \"te-in\", and \"ur-pk\".""" + query_speller: Optional[Union[str, "_models.QuerySpellerType"]] = rest_field( + name="speller", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies the type of the speller to use to spell-correct individual search query + terms. Known values are: \"none\" and \"lexicon\".""" + select: Optional[list[str]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="commaDelimited" + ) + """The comma-separated list of fields to retrieve. If unspecified, all fields marked as + retrievable in the schema are included.""" + skip: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of search results to skip. This value cannot be greater than 100,000. If you need to + scan documents in sequence, but cannot use skip due to this limitation, consider using orderby + on a totally-ordered key and filter with a range query instead.""" + top: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of search results to retrieve. This can be used in conjunction with $skip to + implement client-side paging of search results. If results are truncated due to server-side + paging, the response will include a continuation token that can be used to issue another Search + request for the next page of results.""" + semantic_configuration_name: Optional[str] = rest_field( + name="semanticConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of a semantic configuration that will be used when processing documents for queries of + type semantic.""" + semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = rest_field( + name="semanticErrorHandling", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows the user to choose whether a semantic call should fail completely (default / current + behavior), or to return partial results. Known values are: \"partial\" and \"fail\".""" + semantic_max_wait_in_milliseconds: Optional[int] = rest_field( + name="semanticMaxWaitInMilliseconds", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows the user to set an upper bound on the amount of time it takes for semantic enrichment to + finish processing before the request fails.""" + semantic_query: Optional[str] = rest_field( + name="semanticQuery", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows setting a separate search query that will be solely used for semantic reranking, + semantic captions and semantic answers. Is useful for scenarios where there is a need to use + different queries between the base retrieval and ranking phase, and the L2 semantic phase.""" + answers: Optional[Union[str, "_models.QueryAnswerType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether answers should be returned as part of the search response. Known + values are: \"none\" and \"extractive\".""" + captions: Optional[Union[str, "_models.QueryCaptionType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether captions should be returned as part of the search response. + Known values are: \"none\" and \"extractive\".""" + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = rest_field( + name="queryRewrites", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether query rewrites should be generated to augment the search query. + Known values are: \"none\" and \"generative\".""" + semantic_fields: Optional[list[str]] = rest_field( + name="semanticFields", visibility=["read", "create", "update", "delete", "query"], format="commaDelimited" + ) + """The comma-separated list of field names used for semantic ranking.""" + vector_queries: Optional[list["_models.VectorQuery"]] = rest_field( + name="vectorQueries", visibility=["read", "create", "update", "delete", "query"] + ) + """The query parameters for vector and hybrid search queries.""" + vector_filter_mode: Optional[Union[str, "_models.VectorFilterMode"]] = rest_field( + name="vectorFilterMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether or not filters are applied before or after the vector search is performed. + Default is 'preFilter' for new indexes. Known values are: \"postFilter\", \"preFilter\", and + \"strictPostFilter\".""" + hybrid_search: Optional["_models.HybridSearch"] = rest_field( + name="hybridSearch", visibility=["read", "create", "update", "delete", "query"] + ) + """The query parameters to configure hybrid search behaviors.""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, # pylint: disable=redefined-builtin + highlight_fields: Optional[list[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[list[str]] = None, + query_type: Optional[Union[str, "_models.QueryType"]] = None, + scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, "_models.QueryDebugMode"]] = None, + search_text: Optional[str] = None, + search_fields: Optional[list[str]] = None, + search_mode: Optional[Union[str, "_models.SearchMode"]] = None, + query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, + query_speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, + select: Optional[list[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, "_models.QueryAnswerType"]] = None, + captions: Optional[Union[str, "_models.QueryCaptionType"]] = None, + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, + semantic_fields: Optional[list[str]] = None, + vector_queries: Optional[list["_models.VectorQuery"]] = None, + vector_filter_mode: Optional[Union[str, "_models.VectorFilterMode"]] = None, + hybrid_search: Optional["_models.HybridSearch"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchResult(_Model): + """Contains a document found by a search query, plus associated metadata. + + :ivar score: The relevance score of the document compared to other documents returned by the + query. Required. + :vartype score: float + :ivar reranker_score: The relevance score computed by the semantic ranker for the top search + results. Search results are sorted by the RerankerScore first and then by the Score. + RerankerScore is only returned for queries of type 'semantic'. + :vartype reranker_score: float + :ivar reranker_boosted_score: The relevance score computed by boosting the Reranker Score. + Search results are sorted by the RerankerScore/RerankerBoostedScore based on + useScoringProfileBoostedRanking in the Semantic Config. RerankerBoostedScore is only returned + for queries of type 'semantic'. + :vartype reranker_boosted_score: float + :ivar highlights: Text fragments from the document that indicate the matching search terms, + organized by each applicable field; null if hit highlighting was not enabled for the query. + :vartype highlights: dict[str, list[str]] + :ivar captions: Captions are the most representative passages from the document relatively to + the search query. They are often used as document summary. Captions are only returned for + queries of type 'semantic'. + :vartype captions: list[~azure.search.documents.models.QueryCaptionResult] + :ivar document_debug_info: Contains debugging information that can be used to further explore + your search results. + :vartype document_debug_info: ~azure.search.documents.models.DocumentDebugInfo + """ + + score: float = rest_field(name="@search.score", visibility=["read"]) + """The relevance score of the document compared to other documents returned by the query. + Required.""" + reranker_score: Optional[float] = rest_field(name="@search.rerankerScore", visibility=["read"]) + """The relevance score computed by the semantic ranker for the top search results. Search results + are sorted by the RerankerScore first and then by the Score. RerankerScore is only returned for + queries of type 'semantic'.""" + reranker_boosted_score: Optional[float] = rest_field(name="@search.rerankerBoostedScore", visibility=["read"]) + """The relevance score computed by boosting the Reranker Score. Search results are sorted by the + RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic + Config. RerankerBoostedScore is only returned for queries of type 'semantic'.""" + highlights: Optional[dict[str, list[str]]] = rest_field(name="@search.highlights", visibility=["read"]) + """Text fragments from the document that indicate the matching search terms, organized by each + applicable field; null if hit highlighting was not enabled for the query.""" + captions: Optional[list["_models.QueryCaptionResult"]] = rest_field(name="@search.captions", visibility=["read"]) + """Captions are the most representative passages from the document relatively to the search query. + They are often used as document summary. Captions are only returned for queries of type + 'semantic'.""" + document_debug_info: Optional["_models.DocumentDebugInfo"] = rest_field( + name="@search.documentDebugInfo", visibility=["read"] + ) + """Contains debugging information that can be used to further explore your search results.""" + + +class VectorThreshold(_Model): + """The threshold used for vector queries. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + SearchScoreThreshold, VectorSimilarityThreshold + + :ivar kind: Type of threshold. Required. Known values are: "vectorSimilarity" and + "searchScore". + :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of threshold. Required. Known values are: \"vectorSimilarity\" and \"searchScore\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchScoreThreshold(VectorThreshold, discriminator="searchScore"): + """The results of the vector query will filter based on the '. + + :ivar value: The threshold will filter based on the '. Required. + :vartype value: float + :ivar kind: The kind of threshold used to filter vector queries. Required. The results of the + vector query will filter based on the '@search.score' value. Note this is the @search.score + returned as part of the search response. The threshold direction will be chosen for higher + @search.score. + :vartype kind: str or ~azure.search.documents.models.SEARCH_SCORE + """ + + value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The threshold will filter based on the '. Required.""" + kind: Literal[VectorThresholdKind.SEARCH_SCORE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of threshold used to filter vector queries. Required. The results of the vector query + will filter based on the '@search.score' value. Note this is the @search.score returned as part + of the search response. The threshold direction will be chosen for higher @search.score.""" + + @overload + def __init__( + self, + *, + value: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorThresholdKind.SEARCH_SCORE # type: ignore + + +class SemanticDebugInfo(_Model): + """Contains debugging information specific to semantic ranking requests. + + :ivar title_field: The title field that was sent to the semantic enrichment process, as well as + how it was used. + :vartype title_field: ~azure.search.documents.models.QueryResultDocumentSemanticField + :ivar content_fields: The content fields that were sent to the semantic enrichment process, as + well as how they were used. + :vartype content_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] + :ivar keyword_fields: The keyword fields that were sent to the semantic enrichment process, as + well as how they were used. + :vartype keyword_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] + :ivar reranker_input: The raw concatenated strings that were sent to the semantic enrichment + process. + :vartype reranker_input: ~azure.search.documents.models.QueryResultDocumentRerankerInput + """ + + title_field: Optional["_models.QueryResultDocumentSemanticField"] = rest_field( + name="titleField", visibility=["read"] + ) + """The title field that was sent to the semantic enrichment process, as well as how it was used.""" + content_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = rest_field( + name="contentFields", visibility=["read"] + ) + """The content fields that were sent to the semantic enrichment process, as well as how they were + used.""" + keyword_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = rest_field( + name="keywordFields", visibility=["read"] + ) + """The keyword fields that were sent to the semantic enrichment process, as well as how they were + used.""" + reranker_input: Optional["_models.QueryResultDocumentRerankerInput"] = rest_field( + name="rerankerInput", visibility=["read"] + ) + """The raw concatenated strings that were sent to the semantic enrichment process.""" + + +class SingleVectorFieldResult(_Model): + """A single vector field result. Both. + + :ivar search_score: The. + :vartype search_score: float + :ivar vector_similarity: The vector similarity score for this document. Note this is the + canonical definition of similarity metric, not the 'distance' version. For example, cosine + similarity instead of cosine distance. + :vartype vector_similarity: float + """ + + search_score: Optional[float] = rest_field(name="searchScore", visibility=["read"]) + """The.""" + vector_similarity: Optional[float] = rest_field(name="vectorSimilarity", visibility=["read"]) + """The vector similarity score for this document. Note this is the canonical definition of + similarity metric, not the 'distance' version. For example, cosine similarity instead of cosine + distance.""" + + +class SuggestDocumentsResult(_Model): + """Response containing suggestion query results from an index. + + :ivar results: The sequence of results returned by the query. Required. + :vartype results: list[~azure.search.documents.models.SuggestResult] + :ivar coverage: A value indicating the percentage of the index that was included in the query, + or null if minimumCoverage was not set in the request. + :vartype coverage: float + """ + + results: list["_models.SuggestResult"] = rest_field(name="value", visibility=["read"]) + """The sequence of results returned by the query. Required.""" + coverage: Optional[float] = rest_field(name="@search.coverage", visibility=["read"]) + """A value indicating the percentage of the index that was included in the query, or null if + minimumCoverage was not set in the request.""" + + +class SuggestResult(_Model): + """A result containing a document found by a suggestion query, plus associated metadata. + + :ivar text: The text of the suggestion result. Required. + :vartype text: str + """ + + text: str = rest_field(name="@search.text", visibility=["read"]) + """The text of the suggestion result. Required.""" + + +class TextResult(_Model): + """The BM25 or Classic score for the text portion of the query. + + :ivar search_score: The BM25 or Classic score for the text portion of the query. + :vartype search_score: float + """ + + search_score: Optional[float] = rest_field(name="searchScore", visibility=["read"]) + """The BM25 or Classic score for the text portion of the query.""" + + +class VectorQuery(_Model): + """The query parameters for vector and hybrid search queries. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + VectorizableImageBinaryQuery, VectorizableImageUrlQuery, VectorizableTextQuery, VectorizedQuery + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. + :vartype per_document_vector_limit: int + :ivar kind: Type of query. Required. Known values are: "vector", "text", "imageUrl", and + "imageBinary". + :vartype kind: str or ~azure.search.documents.models.VectorQueryKind + """ + + __mapping__: dict[str, _Model] = {} + k_nearest_neighbors: Optional[int] = rest_field( + name="k", visibility=["read", "create", "update", "delete", "query"] + ) + """Number of nearest neighbors to return as top hits.""" + fields: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Vector Fields of type Collection(Edm.Single) to be included in the vector searched.""" + exhaustive: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """When true, triggers an exhaustive k-nearest neighbor search across all vectors within the + vector index. Useful for scenarios where exact matches are critical, such as determining ground + truth values.""" + oversampling: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Oversampling factor. Minimum value is 1. It overrides the 'defaultOversampling' parameter + configured in the index definition. It can be set only when 'rerankWithOriginalVectors' is + true. This parameter is only permitted when a compression method is used on the underlying + vector field.""" + weight: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Relative weight of the vector query when compared to other vector query and/or the text query + within the same search request. This value is used when combining the results of multiple + ranking lists produced by the different vector queries and/or the results retrieved through the + text query. The higher the weight, the higher the documents that matched that query will be in + the final ranking. Default is 1.0 and the value needs to be a positive number larger than zero.""" + threshold: Optional["_models.VectorThreshold"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The threshold used for vector queries. Note this can only be set if all 'fields' use the same + similarity metric.""" + filter_override: Optional[str] = rest_field( + name="filterOverride", visibility=["read", "create", "update", "delete", "query"] + ) + """The OData filter expression to apply to this specific vector query. If no filter expression is + defined at the vector level, the expression defined in the top level filter parameter is used + instead.""" + per_document_vector_limit: Optional[int] = rest_field( + name="perDocumentVectorLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls how many vectors can be matched from each document in a vector search query. Setting + it to 1 ensures at most one vector per document is matched, guaranteeing results come from + distinct documents. Setting it to 0 (unlimited) allows multiple relevant vectors from the same + document to be matched. Default is 0.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of query. Required. Known values are: \"vector\", \"text\", \"imageUrl\", and + \"imageBinary\".""" + + @overload + def __init__( + self, + *, + kind: str, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorizableImageBinaryQuery(VectorQuery, discriminator="imageBinary"): + """The query parameters to use for vector search when a base 64 encoded binary of an image that + needs to be vectorized is provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. + :vartype per_document_vector_limit: int + :ivar base64_image: The base 64 encoded binary of an image to be vectorized to perform a vector + search query. + :vartype base64_image: str + :ivar kind: The kind of vector query being performed. Required. Vector query where a base 64 + encoded binary of an image that needs to be vectorized is provided. + :vartype kind: str or ~azure.search.documents.models.IMAGE_BINARY + """ + + base64_image: Optional[str] = rest_field( + name="base64Image", visibility=["read", "create", "update", "delete", "query"] + ) + """The base 64 encoded binary of an image to be vectorized to perform a vector search query.""" + kind: Literal[VectorQueryKind.IMAGE_BINARY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where a base 64 encoded binary + of an image that needs to be vectorized is provided.""" + + @overload + def __init__( + self, + *, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + base64_image: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.IMAGE_BINARY # type: ignore + + +class VectorizableImageUrlQuery(VectorQuery, discriminator="imageUrl"): + """The query parameters to use for vector search when an url that represents an image value that + needs to be vectorized is provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. + :vartype per_document_vector_limit: int + :ivar url: The URL of an image to be vectorized to perform a vector search query. + :vartype url: str + :ivar kind: The kind of vector query being performed. Required. Vector query where an url that + represents an image value that needs to be vectorized is provided. + :vartype kind: str or ~azure.search.documents.models.IMAGE_URL + """ + + url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URL of an image to be vectorized to perform a vector search query.""" + kind: Literal[VectorQueryKind.IMAGE_URL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where an url that represents + an image value that needs to be vectorized is provided.""" + + @overload + def __init__( + self, + *, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.IMAGE_URL # type: ignore + + +class VectorizableTextQuery(VectorQuery, discriminator="text"): + """The query parameters to use for vector search when a text value that needs to be vectorized is + provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. + :vartype per_document_vector_limit: int + :ivar text: The text to be vectorized to perform a vector search query. Required. + :vartype text: str + :ivar query_rewrites: Can be configured to let a generative model rewrite the query before + sending it to be vectorized. Known values are: "none" and "generative". + :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :ivar kind: The kind of vector query being performed. Required. Vector query where a text value + that needs to be vectorized is provided. + :vartype kind: str or ~azure.search.documents.models.TEXT + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text to be vectorized to perform a vector search query. Required.""" + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = rest_field( + name="queryRewrites", visibility=["read", "create", "update", "delete", "query"] + ) + """Can be configured to let a generative model rewrite the query before sending it to be + vectorized. Known values are: \"none\" and \"generative\".""" + kind: Literal[VectorQueryKind.TEXT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where a text value that needs + to be vectorized is provided.""" + + @overload + def __init__( + self, + *, + text: str, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.TEXT # type: ignore + + +class VectorizedQuery(VectorQuery, discriminator="vector"): + """The query parameters to use for vector search when a raw vector value is provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. + :vartype per_document_vector_limit: int + :ivar vector: The vector representation of a search query. Required. + :vartype vector: list[float] + :ivar kind: The kind of vector query being performed. Required. Vector query where a raw vector + value is provided. + :vartype kind: str or ~azure.search.documents.models.VECTOR + """ + + vector: list[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The vector representation of a search query. Required.""" + kind: Literal[VectorQueryKind.VECTOR] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where a raw vector value is + provided.""" + + @overload + def __init__( + self, + *, + vector: list[float], + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.VECTOR # type: ignore + + +class VectorsDebugInfo(_Model): + """ "Contains debugging information specific to vector and hybrid search."). + + :ivar subscores: The breakdown of subscores of the document prior to the chosen result set + fusion/combination method such as RRF. + :vartype subscores: ~azure.search.documents.models.QueryResultDocumentSubscores + """ + + subscores: Optional["_models.QueryResultDocumentSubscores"] = rest_field(visibility=["read"]) + """The breakdown of subscores of the document prior to the chosen result set fusion/combination + method such as RRF.""" + + +class VectorSimilarityThreshold(VectorThreshold, discriminator="vectorSimilarity"): + """The results of the vector query will be filtered based on the vector similarity metric. Note + this is the canonical definition of similarity metric, not the 'distance' version. The + threshold direction (larger or smaller) will be chosen automatically according to the metric + used by the field. + + :ivar value: The threshold will filter based on the similarity metric value. Note this is the + canonical definition of similarity metric, not the 'distance' version. The threshold direction + (larger or smaller) will be chosen automatically according to the metric used by the field. + Required. + :vartype value: float + :ivar kind: The kind of threshold used to filter vector queries. Required. The results of the + vector query will be filtered based on the vector similarity metric. Note this is the canonical + definition of similarity metric, not the 'distance' version. The threshold direction (larger or + smaller) will be chosen automatically according to the metric used by the field. + :vartype kind: str or ~azure.search.documents.models.VECTOR_SIMILARITY + """ + + value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The threshold will filter based on the similarity metric value. Note this is the canonical + definition of similarity metric, not the 'distance' version. The threshold direction (larger or + smaller) will be chosen automatically according to the metric used by the field. Required.""" + kind: Literal[VectorThresholdKind.VECTOR_SIMILARITY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of threshold used to filter vector queries. Required. The results of the vector query + will be filtered based on the vector similarity metric. Note this is the canonical definition + of similarity metric, not the 'distance' version. The threshold direction (larger or smaller) + will be chosen automatically according to the metric used by the field.""" + + @overload + def __init__( + self, + *, + value: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorThresholdKind.VECTOR_SIMILARITY # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py similarity index 51% rename from sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py rename to sdk/search/azure-search-documents/azure/search/documents/models/_patch.py index db107813fd63..264ae9ac9a63 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py @@ -1,37 +1,59 @@ -# ------------------------------------------------------------------------- +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- -from typing import Union, List, Dict, Any, Tuple, cast -from threading import Lock +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Dict, List, Tuple, Union, cast, Optional +from azure.core.exceptions import HttpResponseError -from ._generated.models import IndexAction +from ._models import IndexDocumentsBatch as IndexDocumentsBatchGenerated +from ._models import IndexAction +from ._enums import IndexActionType def _flatten_args(args: Tuple[Union[List[Dict[Any, Any]], List[List[Dict[Any, Any]]]], ...]) -> List[Dict]: + """Flatten variadic arguments into a single list of documents. + + Supports both: + - add_upload_actions([doc1, doc2]) # single list + - add_upload_actions(doc1, doc2) # multiple args + + :param args: Variadic arguments containing documents or lists of documents. + :type args: Tuple[Union[List[Dict[Any, Any]], List[List[Dict[Any, Any]]]], ...] + :return: A flattened list of document dictionaries. + :rtype: List[Dict] + """ if len(args) == 1 and isinstance(args[0], (list, tuple)): return cast(List[Dict], args[0]) return cast(List[Dict], args) -class IndexDocumentsBatch: +class RequestEntityTooLargeError(HttpResponseError): + """An error response with status code 413 - Request Entity Too Large""" + + +class IndexDocumentsBatch(IndexDocumentsBatchGenerated): """Represent a batch of update operations for documents in an Azure Search index. Index operations are performed in the order in which they are added to the batch. - """ - def __init__(self) -> None: - self._actions: List[IndexAction] = [] - self._lock = Lock() + def __init__(self, *, actions: Optional[List[IndexAction]] = None) -> None: + super().__init__(actions=actions if actions is not None else []) + self._actions: List[IndexAction] = self["value"] def __repr__(self) -> str: - return "".format(len(self.actions))[:1024] + return "".format(len(self.actions) if self.actions else 0)[:1024] - def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: + def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any) -> List[IndexAction]: + # pylint: disable=unused-argument """Add documents to upload to the Azure search index. An upload action is similar to an "upsert" where the document will be @@ -42,13 +64,13 @@ def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> a single list of documents, or documents as individual parameters. :type documents: dict or list[dict] :return: the added actions - :rtype: list[IndexAction] + :rtype: list[~azure.search.documents.models.IndexAction] """ - return self._extend_batch(_flatten_args(documents), "upload") + return self._extend_batch(_flatten_args(documents), IndexActionType.UPLOAD) def add_delete_actions(self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any) -> List[IndexAction]: # pylint: disable=unused-argument - """Add documents to delete to the Azure search index. + """Add documents to delete from the Azure search index. Delete removes the specified document from the index. Any field you specify in a delete operation, other than the key field, will be @@ -63,9 +85,9 @@ def add_delete_actions(self, *documents: Union[List[Dict], List[List[Dict]]], ** a single list of documents, or documents as individual parameters. :type documents: dict or list[dict] :return: the added actions - :rtype: list[IndexAction] + :rtype: list[~azure.search.documents.models.IndexAction] """ - return self._extend_batch(_flatten_args(documents), "delete") + return self._extend_batch(_flatten_args(documents), IndexActionType.DELETE) def add_merge_actions(self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any) -> List[IndexAction]: # pylint: disable=unused-argument @@ -81,9 +103,9 @@ def add_merge_actions(self, *documents: Union[List[Dict], List[List[Dict]]], **k a single list of documents, or documents as individual parameters. :type documents: dict or list[dict] :return: the added actions - :rtype: list[IndexAction] + :rtype: list[~azure.search.documents.models.IndexAction] """ - return self._extend_batch(_flatten_args(documents), "merge") + return self._extend_batch(_flatten_args(documents), IndexActionType.MERGE) def add_merge_or_upload_actions( self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any @@ -101,27 +123,40 @@ def add_merge_or_upload_actions( parameters. :type documents: dict or list[dict] :return: the added actions - :rtype: list[IndexAction] + :rtype: list[~azure.search.documents.models.IndexAction] """ - return self._extend_batch(_flatten_args(documents), "mergeOrUpload") + return self._extend_batch(_flatten_args(documents), IndexActionType.MERGE_OR_UPLOAD) @property def actions(self) -> List[IndexAction]: """The list of currently index actions to index. - :rtype: list[IndexAction] + :rtype: list[~azure.search.documents.models.IndexAction] """ + if not hasattr(self, "_actions") or self._actions is None: + self._actions = [] return list(self._actions) - def dequeue_actions(self, **kwargs: Any) -> List[IndexAction]: # pylint: disable=unused-argument + @actions.setter + def actions(self, value: List[IndexAction]) -> None: + """Set the list of index actions. + + :param value: The list of index actions + :type value: list[~azure.search.documents.models.IndexAction] + """ + self._actions = value if value is not None else [] + + def dequeue_actions(self, **kwargs: Any) -> List[IndexAction]: + # pylint: disable=unused-argument """Get the list of currently configured index actions and clear it. :return: the current actions - :rtype: list[IndexAction] + :rtype: list[~azure.search.documents.models.IndexAction] """ - with self._lock: - result = list(self._actions) - self._actions = [] + if not hasattr(self, "_actions") or self._actions is None: + return [] + result = list(self._actions) + self._actions = [] return result def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction]], **kwargs: Any) -> None: @@ -129,17 +164,53 @@ def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction]], ** """Enqueue a list of index actions to index. :param new_actions: the actions to enqueue - :type new_actions: IndexAction or list[IndexAction] + :type new_actions: ~azure.search.documents.models.IndexAction or list[~azure.search.documents.models.IndexAction] """ + if not hasattr(self, "_actions") or self._actions is None: + self._actions = [] + if isinstance(new_actions, IndexAction): - with self._lock: - self._actions.append(new_actions) + self._actions.append(new_actions) else: - with self._lock: - self._actions.extend(new_actions) + self._actions.extend(new_actions) def _extend_batch(self, documents: List[Dict], action_type: str) -> List[IndexAction]: - new_actions = [IndexAction(additional_properties=document, action_type=action_type) for document in documents] - with self._lock: - self._actions.extend(new_actions) + """Internal helper to extend the batch with new actions. + + :param documents: The documents to add + :type documents: list[dict] + :param action_type: The action type for these documents + :type action_type: str + :return: The list of actions added + :rtype: list[~azure.search.documents.models.IndexAction] + """ + if not hasattr(self, "_actions") or self._actions is None: + self._actions = [] + + new_actions = [] + for doc in documents: + action_dict = {"@search.action": action_type} + action_dict.update(doc) + action = IndexAction(action_dict) + new_actions.append(action) + + self._actions.extend(new_actions) return new_actions + + +# Set __module__ so Sphinx documents IndexDocumentsBatch under the public namespace, +# avoiding duplicate object description warnings. +IndexDocumentsBatch.__module__ = "azure.search.documents" + +__all__: list[str] = [ + "IndexDocumentsBatch", +] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/search/azure-search-documents/azure/search/documents/py.typed b/sdk/search/azure-search-documents/azure/search/documents/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/py.typed +++ b/sdk/search/azure-search-documents/azure/search/documents/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/pyproject.toml b/sdk/search/azure-search-documents/pyproject.toml index dfbf5ac7a46c..04403f6d9741 100644 --- a/sdk/search/azure-search-documents/pyproject.toml +++ b/sdk/search/azure-search-documents/pyproject.toml @@ -1,3 +1,65 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-search-documents" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Corporation Azure Search Documents Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.search.documents._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.search", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] pyright = false verifytypes = true diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_agentic_retrieval_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_agentic_retrieval_async.py index 16b76d380a48..9573c9902204 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_agentic_retrieval_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_agentic_retrieval_async.py @@ -31,11 +31,11 @@ from azure.search.documents.knowledgebases.models import ( KnowledgeBaseRetrievalRequest, KnowledgeRetrievalSemanticIntent, + KnowledgeRetrievalMinimalReasoningEffort, ) from azure.search.documents.indexes.models import ( KnowledgeBase, KnowledgeSourceReference, - KnowledgeRetrievalMinimalReasoningEffort, SearchIndexFieldReference, SearchIndexKnowledgeSource, SearchIndexKnowledgeSourceParameters, @@ -55,15 +55,11 @@ async def create_knowledge_source_async(): knowledge_source = SearchIndexKnowledgeSource( name=knowledge_source_name, - search_index_parameters=SearchIndexKnowledgeSourceParameters( - search_index_name=index_name - ), + search_index_parameters=SearchIndexKnowledgeSourceParameters(search_index_name=index_name), ) async with index_client: - await index_client.create_or_update_knowledge_source( - knowledge_source=knowledge_source - ) + await index_client.create_or_update_knowledge_source(knowledge_source=knowledge_source) print(f"Created: knowledge source '{knowledge_source_name}'") # [END create_knowledge_source_async] @@ -73,9 +69,7 @@ async def get_knowledge_source_async(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) async with index_client: - knowledge_source = await index_client.get_knowledge_source( - knowledge_source_name - ) + knowledge_source = await index_client.get_knowledge_source(knowledge_source_name) print(f"Retrieved: knowledge source '{knowledge_source.name}'") # [END get_knowledge_source_async] @@ -99,9 +93,7 @@ async def update_knowledge_source_async(): ) async with index_client: - await index_client.create_or_update_knowledge_source( - knowledge_source=knowledge_source - ) + await index_client.create_or_update_knowledge_source(knowledge_source=knowledge_source) print(f"Updated: knowledge source '{knowledge_source_name}'") # [END update_knowledge_source_async] @@ -163,16 +155,13 @@ async def retrieve_knowledge_base_async(): # [START retrieve_knowledge_base_async] retrieval_client = KnowledgeBaseRetrievalClient( service_endpoint, - knowledge_base_name=knowledge_base_name, credential=AzureKeyCredential(key), ) - request = KnowledgeBaseRetrievalRequest( - intents=[KnowledgeRetrievalSemanticIntent(search="hotels with free wifi")] - ) + request = KnowledgeBaseRetrievalRequest(intents=[KnowledgeRetrievalSemanticIntent(search="hotels with free wifi")]) try: - result = await retrieval_client.retrieve(request) + result = await retrieval_client.retrieve(knowledge_base_name=knowledge_base_name, retrieval_request=request) finally: await retrieval_client.close() diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_documents_buffered_sender_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_documents_buffered_sender_async.py index 8ff623d4df17..ceb692ec7b34 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_documents_buffered_sender_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_documents_buffered_sender_async.py @@ -53,17 +53,13 @@ async def sample_batching_client_async(): "Location": {"type": "Point", "coordinates": [-122.131577, 47.678581]}, } - async with SearchIndexingBufferedSender( - service_endpoint, index_name, AzureKeyCredential(key) - ) as buffered_sender: + async with SearchIndexingBufferedSender(service_endpoint, index_name, AzureKeyCredential(key)) as buffered_sender: # add upload actions await buffered_sender.upload_documents(documents=[document]) print(f"Uploaded: document {document['HotelId']}") # add merge actions - await buffered_sender.merge_documents( - documents=[{"HotelId": "100", "Rating": 4.5}] - ) + await buffered_sender.merge_documents(documents=[{"HotelId": "100", "Rating": 4.5}]) print(f"Merged: document {document['HotelId']}") # add delete actions diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_documents_crud_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_documents_crud_async.py index 39d9db3e3d14..411813d0fcd2 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_documents_crud_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_documents_crud_async.py @@ -108,6 +108,22 @@ async def delete_document_async(): # [END delete_document_async] +async def merge_or_upload_document_async(): + # [START merge_or_upload_document_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + result = await search_client.merge_or_upload_documents( + documents=[{"HotelId": "100", "HotelName": "Azure Sanctuary & Spa"}] + ) + + print(f"Merge or upload: document 100 (succeeded={result[0].succeeded})") + # [END merge_or_upload_document_async] + + if __name__ == "__main__": asyncio.run(upload_document_async()) asyncio.run(merge_document_async()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_async.py index 7206721ffb9d..3bc3fe353d30 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_async.py @@ -78,18 +78,16 @@ async def update_alias_async(): # Create a new index with a different schema or settings # In a real scenario, this would be your updated index version (e.g., v2) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), - SearchableField(name="HotelName", type=SearchFieldDataType.String), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), + SearchableField(name="HotelName", type=SearchFieldDataType.STRING), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), - SimpleField(name="State", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), + SimpleField(name="State", type=SearchFieldDataType.STRING), ], collection=True, ), diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_analyze_text_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_analyze_text_async.py index e5ca9a20cb9d..f3056d237f22 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_index_analyze_text_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_index_analyze_text_async.py @@ -35,18 +35,14 @@ async def simple_analyze_text_async(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - analyze_request = AnalyzeTextOptions( - text="One's ", analyzer_name="standard.lucene" - ) + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") async with index_client: analysis_result = await index_client.analyze_text(index_name, analyze_request) print("Results:") for token in analysis_result.tokens: - print( - f" Token: {token.token}, Start: {token.start_offset}, End: {token.end_offset}" - ) + print(f" Token: {token.token}, Start: {token.start_offset}, End: {token.end_offset}") # [END simple_analyze_text_async] diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_async.py index f0bab5497144..f01c2f21bf02 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_async.py @@ -44,17 +44,15 @@ async def create_index_async(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="HotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="HotelName", type=SearchFieldDataType.STRING, searchable=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), ], collection=True, ), @@ -103,18 +101,16 @@ async def update_index_async(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="HotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="HotelName", type=SearchFieldDataType.STRING, searchable=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), - SimpleField(name="State", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), + SimpleField(name="State", type=SearchFieldDataType.STRING), ], collection=True, ), diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_crud_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_crud_async.py index 2f338e5e3989..362140213eef 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_crud_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_crud_async.py @@ -52,8 +52,8 @@ async def create_indexer_async(): # create an index fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), ] index = SearchIndex(name=index_name, fields=fields) async with index_client: diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_datasource_crud_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_datasource_crud_async.py index 4a817dbe7309..1e2154284848 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_datasource_crud_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_indexer_datasource_crud_async.py @@ -48,9 +48,7 @@ async def create_data_source_connection_async(): container=container, ) async with indexer_client: - result = await indexer_client.create_data_source_connection( - data_source_connection - ) + result = await indexer_client.create_data_source_connection(data_source_connection) print(f"Created: data source '{result.name}'") # [END create_data_source_connection_async] @@ -77,9 +75,7 @@ async def get_data_source_connection_async(): indexer_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) async with indexer_client: - result = await indexer_client.get_data_source_connection( - data_source_connection_name - ) + result = await indexer_client.get_data_source_connection(data_source_connection_name) print(f"Retrieved: data source '{result.name}'") return result # [END get_data_source_connection_async] diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_query_autocomplete_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_query_autocomplete_async.py index 70b3eb5d5121..454d19538e74 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_query_autocomplete_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_query_autocomplete_async.py @@ -36,9 +36,7 @@ async def autocomplete_query_async(): search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) async with search_client: - results = await search_client.autocomplete( - search_text="bo", suggester_name="sg" - ) + results = await search_client.autocomplete(search_text="bo", suggester_name="sg") print("Results: autocomplete for 'bo'") for result in results: diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_query_facets_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_query_facets_async.py index 5dacbf5b2a8b..39a98cc94f0b 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_query_facets_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_query_facets_async.py @@ -36,9 +36,7 @@ async def facet_query_async(): search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) async with search_client: - results = await search_client.search( - search_text="WiFi", facets=["Category,count:3", "ParkingIncluded"] - ) + results = await search_client.search(search_text="WiFi", facets=["Category,count:3", "ParkingIncluded"]) facets = await results.get_facets() diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_query_semantic_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_query_semantic_async.py index e8ac4c536b04..5354552b090e 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_query_semantic_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_query_semantic_async.py @@ -51,9 +51,7 @@ async def create_semantic_configuration_async(): index.semantic_search = SemanticSearch(configurations=[semantic_config]) await index_client.create_or_update_index(index) - print( - f"Updated: index '{index_name}' (semantic config '{semantic_configuration_name}')" - ) + print(f"Updated: index '{index_name}' (semantic config '{semantic_configuration_name}')") async def speller_async(): @@ -62,13 +60,9 @@ async def speller_async(): from azure.search.documents.aio import SearchClient credential = AzureKeyCredential(key) - search_client = SearchClient( - endpoint=service_endpoint, index_name=index_name, credential=credential - ) + search_client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) async with search_client: - results = await search_client.search( - search_text="luxury", query_language="en-us", query_speller="lexicon" - ) + results = await search_client.search(search_text="luxury", query_language="en-us", query_speller="lexicon") print("Results: speller") async for result in results: @@ -83,9 +77,7 @@ async def semantic_ranking_async(): from azure.search.documents.aio import SearchClient credential = AzureKeyCredential(key) - search_client = SearchClient( - endpoint=service_endpoint, index_name=index_name, credential=credential - ) + search_client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) async with search_client: results = await search_client.search( search_text="luxury", diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_query_vector_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_query_vector_async.py index 0f742646e0f7..76f8c8b13aeb 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_query_vector_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_query_vector_async.py @@ -72,30 +72,26 @@ async def create_index_async(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField( - name="HotelId", type=SearchFieldDataType.String, key=True, filterable=True - ), - SearchableField( - name="HotelName", type=SearchFieldDataType.String, sortable=True - ), - SearchableField(name="Description", type=SearchFieldDataType.String), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True, filterable=True), + SearchableField(name="HotelName", type=SearchFieldDataType.STRING, sortable=True), + SearchableField(name="Description", type=SearchFieldDataType.STRING), SearchField( name="DescriptionVector", - type=SearchFieldDataType.Collection(SearchFieldDataType.Single), + type=SearchFieldDataType.Collection(SearchFieldDataType.SINGLE), # type: ignore[operator] searchable=True, vector_search_dimensions=1536, vector_search_profile_name="my-vector-profile", ), SearchableField( name="Category", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, sortable=True, filterable=True, facetable=True, ), SearchField( name="Tags", - type=SearchFieldDataType.Collection(SearchFieldDataType.String), + type=SearchFieldDataType.Collection(SearchFieldDataType.STRING), # type: ignore[operator] searchable=True, filterable=True, facetable=True, @@ -104,10 +100,8 @@ async def create_index_async(): vector_search = VectorSearch( algorithms=[ - HnswAlgorithmConfiguration(name="my-hnsw-vector-config-1", kind="hnsw"), - ExhaustiveKnnAlgorithmConfiguration( - name="my-eknn-vector-config", kind="exhaustiveKnn" - ), + HnswAlgorithmConfiguration(name="my-hnsw-vector-config-1"), + ExhaustiveKnnAlgorithmConfiguration(name="my-eknn-vector-config"), ], profiles=[ VectorSearchProfile( @@ -166,7 +160,7 @@ async def single_vector_search_async(): vector_query = VectorizedQuery( vector=vector, - k=5, + k_nearest_neighbors=5, fields="DescriptionVector", ) @@ -193,7 +187,7 @@ async def single_vector_search_with_filter_async(): vector_query = VectorizedQuery( vector=vector, - k=5, + k_nearest_neighbors=5, fields="DescriptionVector", ) @@ -207,10 +201,7 @@ async def single_vector_search_with_filter_async(): print("Results: vector search with filter") async for result in results: - print( - f" HotelId: {result['HotelId']}, HotelName: {result['HotelName']}, " - f"Tags: {result.get('Tags')}" - ) + print(f" HotelId: {result['HotelId']}, HotelName: {result['HotelName']}, " f"Tags: {result.get('Tags')}") # [END single_vector_search_with_filter_async] @@ -221,7 +212,7 @@ async def simple_hybrid_search_async(): vector_query = VectorizedQuery( vector=vector, - k=5, + k_nearest_neighbors=5, fields="DescriptionVector", ) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_custom_request_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_custom_request_async.py index 24fe1a28be00..42e169943465 100644 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_custom_request_async.py +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_custom_request_async.py @@ -40,9 +40,7 @@ async def sample_send_request_async(): # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, # while adding convenience for endpoint construction. - request = HttpRequest( - method="GET", url=f"/docs/$count?api-version={AZURE_SEARCH_API_VERSION}" - ) + request = HttpRequest(method="GET", url=f"/docs/$count?api-version={AZURE_SEARCH_API_VERSION}") async with search_client: response = await search_client.send_request(request) response.raise_for_status() diff --git a/sdk/search/azure-search-documents/samples/sample_agentic_retrieval.py b/sdk/search/azure-search-documents/samples/sample_agentic_retrieval.py index 45177246e5a5..97d0d05a57b5 100644 --- a/sdk/search/azure-search-documents/samples/sample_agentic_retrieval.py +++ b/sdk/search/azure-search-documents/samples/sample_agentic_retrieval.py @@ -30,11 +30,11 @@ from azure.search.documents.knowledgebases.models import ( KnowledgeBaseRetrievalRequest, KnowledgeRetrievalSemanticIntent, + KnowledgeRetrievalMinimalReasoningEffort, ) from azure.search.documents.indexes.models import ( KnowledgeBase, KnowledgeSourceReference, - KnowledgeRetrievalMinimalReasoningEffort, SearchIndexFieldReference, SearchIndexKnowledgeSource, SearchIndexKnowledgeSourceParameters, @@ -54,9 +54,7 @@ def create_knowledge_source(): knowledge_source = SearchIndexKnowledgeSource( name=knowledge_source_name, - search_index_parameters=SearchIndexKnowledgeSourceParameters( - search_index_name=index_name - ), + search_index_parameters=SearchIndexKnowledgeSourceParameters(search_index_name=index_name), ) index_client.create_or_update_knowledge_source(knowledge_source=knowledge_source) @@ -149,15 +147,12 @@ def retrieve_knowledge_base(): # [START retrieve_knowledge_base] retrieval_client = KnowledgeBaseRetrievalClient( service_endpoint, - knowledge_base_name=knowledge_base_name, credential=AzureKeyCredential(key), ) - request = KnowledgeBaseRetrievalRequest( - intents=[KnowledgeRetrievalSemanticIntent(search="hotels with free wifi")] - ) + request = KnowledgeBaseRetrievalRequest(intents=[KnowledgeRetrievalSemanticIntent(search="hotels with free wifi")]) - result = retrieval_client.retrieve(request) + result = retrieval_client.retrieve(knowledge_base_name=knowledge_base_name, retrieval_request=request) print("Results: knowledge base retrieval") response_parts = [] diff --git a/sdk/search/azure-search-documents/samples/sample_documents_buffered_sender.py b/sdk/search/azure-search-documents/samples/sample_documents_buffered_sender.py index f514de4b2837..331708bcdfb7 100644 --- a/sdk/search/azure-search-documents/samples/sample_documents_buffered_sender.py +++ b/sdk/search/azure-search-documents/samples/sample_documents_buffered_sender.py @@ -52,9 +52,7 @@ def sample_batching_client(): "Location": {"type": "Point", "coordinates": [-122.131577, 47.678581]}, } - with SearchIndexingBufferedSender( - service_endpoint, index_name, AzureKeyCredential(key) - ) as buffered_sender: + with SearchIndexingBufferedSender(service_endpoint, index_name, AzureKeyCredential(key)) as buffered_sender: # add upload actions buffered_sender.upload_documents(documents=[document]) print(f"Uploaded: document {document['HotelId']}") diff --git a/sdk/search/azure-search-documents/samples/sample_documents_crud.py b/sdk/search/azure-search-documents/samples/sample_documents_crud.py index 2b7fe2ce17c7..f72f16aac281 100644 --- a/sdk/search/azure-search-documents/samples/sample_documents_crud.py +++ b/sdk/search/azure-search-documents/samples/sample_documents_crud.py @@ -67,9 +67,7 @@ def merge_document(): search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - result = search_client.merge_documents( - documents=[{"HotelId": "100", "HotelName": "Azure Sanctuary & Spa"}] - ) + result = search_client.merge_documents(documents=[{"HotelId": "100", "HotelName": "Azure Sanctuary & Spa"}]) print(f"Merged: document 100 (succeeded={result[0].succeeded})") # [END merge_document] @@ -103,6 +101,21 @@ def delete_document(): # [END delete_document] +def merge_or_upload_document(): + # [START merge_or_upload_document] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + result = search_client.merge_or_upload_documents( + documents=[{"HotelId": "100", "HotelName": "Azure Sanctuary & Spa"}] + ) + + print(f"Merge or upload: document 100 (succeeded={result[0].succeeded})") + # [END merge_or_upload_document] + + if __name__ == "__main__": upload_document() merge_document() diff --git a/sdk/search/azure-search-documents/samples/sample_index_alias_crud.py b/sdk/search/azure-search-documents/samples/sample_index_alias_crud.py index 4851509a2523..af53ed7c37d4 100644 --- a/sdk/search/azure-search-documents/samples/sample_index_alias_crud.py +++ b/sdk/search/azure-search-documents/samples/sample_index_alias_crud.py @@ -75,18 +75,16 @@ def update_alias(): # Create a new index with a different schema or settings # In a real scenario, this would be your updated index version (e.g., v2) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), - SearchableField(name="HotelName", type=SearchFieldDataType.String), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), + SearchableField(name="HotelName", type=SearchFieldDataType.STRING), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), - SimpleField(name="State", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), + SimpleField(name="State", type=SearchFieldDataType.STRING), ], collection=True, ), diff --git a/sdk/search/azure-search-documents/samples/sample_index_analyze_text.py b/sdk/search/azure-search-documents/samples/sample_index_analyze_text.py index ff5fd6d0110c..5c8557fc3af1 100644 --- a/sdk/search/azure-search-documents/samples/sample_index_analyze_text.py +++ b/sdk/search/azure-search-documents/samples/sample_index_analyze_text.py @@ -34,17 +34,13 @@ def simple_analyze_text(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - analyze_request = AnalyzeTextOptions( - text="One's ", analyzer_name="standard.lucene" - ) + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") analysis_result = index_client.analyze_text(index_name, analyze_request) print("Results:") for token in analysis_result.tokens: - print( - f" Token: {token.token}, Start: {token.start_offset}, End: {token.end_offset}" - ) + print(f" Token: {token.token}, Start: {token.start_offset}, End: {token.end_offset}") # [END simple_analyze_text] diff --git a/sdk/search/azure-search-documents/samples/sample_index_crud.py b/sdk/search/azure-search-documents/samples/sample_index_crud.py index 6d0b13aad31a..f918dd4771bd 100644 --- a/sdk/search/azure-search-documents/samples/sample_index_crud.py +++ b/sdk/search/azure-search-documents/samples/sample_index_crud.py @@ -43,17 +43,15 @@ def create_index(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="HotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="HotelName", type=SearchFieldDataType.STRING, searchable=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), ], collection=True, ), @@ -99,18 +97,16 @@ def update_index(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="HotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), - SearchableField( - name="Description", type=SearchFieldDataType.String, collection=True - ), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="HotelName", type=SearchFieldDataType.STRING, searchable=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="Description", type=SearchFieldDataType.STRING, collection=True), ComplexField( name="Address", fields=[ - SimpleField(name="StreetAddress", type=SearchFieldDataType.String), - SimpleField(name="City", type=SearchFieldDataType.String), - SimpleField(name="State", type=SearchFieldDataType.String), + SimpleField(name="StreetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="City", type=SearchFieldDataType.STRING), + SimpleField(name="State", type=SearchFieldDataType.STRING), ], collection=True, ), @@ -131,6 +127,19 @@ def update_index(): # [END update_index] +def list_index_names(): + # [START list_index_names] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.indexes import SearchIndexClient + + index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + print("Listing all index names:") + for name in index_client.list_index_names(): + print(f" - {name}") + # [END list_index_names] + + def delete_index(): # [START delete_index] from azure.core.credentials import AzureKeyCredential @@ -145,5 +154,6 @@ def delete_index(): if __name__ == "__main__": create_index() get_index() + list_index_names() update_index() delete_index() diff --git a/sdk/search/azure-search-documents/samples/sample_indexer_crud.py b/sdk/search/azure-search-documents/samples/sample_indexer_crud.py index 33741a9be30e..9c6282434590 100644 --- a/sdk/search/azure-search-documents/samples/sample_indexer_crud.py +++ b/sdk/search/azure-search-documents/samples/sample_indexer_crud.py @@ -48,8 +48,8 @@ def create_indexer(): # create an index fields = [ - SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="BaseRate", type=SearchFieldDataType.Double), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="BaseRate", type=SearchFieldDataType.DOUBLE), ] index = SearchIndex(name=index_name, fields=fields) index_client.create_index(index) diff --git a/sdk/search/azure-search-documents/samples/sample_indexer_workflow.py b/sdk/search/azure-search-documents/samples/sample_indexer_workflow.py index 12e3bb668c9a..86155da3596f 100644 --- a/sdk/search/azure-search-documents/samples/sample_indexer_workflow.py +++ b/sdk/search/azure-search-documents/samples/sample_indexer_workflow.py @@ -43,7 +43,7 @@ def sample_indexer_workflow(): SearchIndexer, SimpleField, SearchFieldDataType, - EntityRecognitionSkill, + EntityRecognitionSkillV3, InputFieldMappingEntry, OutputFieldMappingEntry, SearchIndexerSkillset, @@ -62,24 +62,20 @@ def sample_indexer_workflow(): fields = [ SimpleField( name="HotelId", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, filterable=True, sortable=True, key=True, ), - SearchableField(name="HotelName", type=SearchFieldDataType.String), - SimpleField(name="Description", type=SearchFieldDataType.String), - SimpleField(name="Description_fr", type=SearchFieldDataType.String), - SimpleField(name="Category", type=SearchFieldDataType.String), - SimpleField( - name="ParkingIncluded", type=SearchFieldDataType.Boolean, filterable=True - ), - SimpleField( - name="SmokingAllowed", type=SearchFieldDataType.Boolean, filterable=True - ), - SimpleField(name="LastRenovationDate", type=SearchFieldDataType.String), - SimpleField(name="Rating", type=SearchFieldDataType.Double, sortable=True), - SimpleField(name="Location", type=SearchFieldDataType.GeographyPoint), + SearchableField(name="HotelName", type=SearchFieldDataType.STRING), + SimpleField(name="Description", type=SearchFieldDataType.STRING), + SimpleField(name="Description_fr", type=SearchFieldDataType.STRING), + SimpleField(name="Category", type=SearchFieldDataType.STRING), + SimpleField(name="ParkingIncluded", type=SearchFieldDataType.BOOLEAN, filterable=True), + SimpleField(name="SmokingAllowed", type=SearchFieldDataType.BOOLEAN, filterable=True), + SimpleField(name="LastRenovationDate", type=SearchFieldDataType.STRING), + SimpleField(name="Rating", type=SearchFieldDataType.DOUBLE, sortable=True), + SimpleField(name="Location", type=SearchFieldDataType.GEOGRAPHY_POINT), ] cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) index = SearchIndex(name=index_name, fields=fields, cors_options=cors_options) @@ -100,10 +96,8 @@ def sample_indexer_workflow(): # 3. Create a skillset inp = InputFieldMappingEntry(name="text", source="/document/lastRenovationDate") output = OutputFieldMappingEntry(name="dateTimes", target_name="RenovatedDate") - skill = EntityRecognitionSkill(name="merge-skill", inputs=[inp], outputs=[output]) - skillset = SearchIndexerSkillset( - name=skillset_name, skills=[skill], description="example skillset" - ) + skill = EntityRecognitionSkillV3(name="merge-skill", inputs=[inp], outputs=[output]) + skillset = SearchIndexerSkillset(name=skillset_name, skills=[skill], description="example skillset") indexer_client.create_skillset(skillset) print(f"Created: skillset '{skillset_name}'") diff --git a/sdk/search/azure-search-documents/samples/sample_query_facets.py b/sdk/search/azure-search-documents/samples/sample_query_facets.py index 4ff9245422c0..e9c402aa40c4 100644 --- a/sdk/search/azure-search-documents/samples/sample_query_facets.py +++ b/sdk/search/azure-search-documents/samples/sample_query_facets.py @@ -33,9 +33,7 @@ def facet_query(): search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - results = search_client.search( - search_text="WiFi", facets=["Category,count:3", "ParkingIncluded"] - ) + results = search_client.search(search_text="WiFi", facets=["Category,count:3", "ParkingIncluded"]) facets = results.get_facets() diff --git a/sdk/search/azure-search-documents/samples/sample_query_semantic.py b/sdk/search/azure-search-documents/samples/sample_query_semantic.py index bffdf3f8f3fc..49dbbd6997b3 100644 --- a/sdk/search/azure-search-documents/samples/sample_query_semantic.py +++ b/sdk/search/azure-search-documents/samples/sample_query_semantic.py @@ -49,9 +49,7 @@ def create_semantic_configuration(): index.semantic_search = SemanticSearch(configurations=[semantic_config]) index_client.create_or_update_index(index) - print( - f"Updated: index '{index_name}' (semantic config '{semantic_configuration_name}')" - ) + print(f"Updated: index '{index_name}' (semantic config '{semantic_configuration_name}')") def speller(): @@ -60,14 +58,8 @@ def speller(): from azure.search.documents import SearchClient credential = AzureKeyCredential(key) - search_client = SearchClient( - endpoint=service_endpoint, index_name=index_name, credential=credential - ) - results = list( - search_client.search( - search_text="luxury", query_language="en-us", query_speller="lexicon" - ) - ) + search_client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) + results = list(search_client.search(search_text="luxury", query_language="en-us", query_speller="lexicon")) print("Results: speller") for result in results: @@ -82,9 +74,7 @@ def semantic_ranking(): from azure.search.documents import SearchClient credential = AzureKeyCredential(key) - search_client = SearchClient( - endpoint=service_endpoint, index_name=index_name, credential=credential - ) + search_client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) results = list( search_client.search( search_text="luxury", diff --git a/sdk/search/azure-search-documents/samples/sample_query_vector.py b/sdk/search/azure-search-documents/samples/sample_query_vector.py index 043b5484d331..b88ad6855a4c 100644 --- a/sdk/search/azure-search-documents/samples/sample_query_vector.py +++ b/sdk/search/azure-search-documents/samples/sample_query_vector.py @@ -69,30 +69,26 @@ def create_index(): index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) fields = [ - SimpleField( - name="HotelId", type=SearchFieldDataType.String, key=True, filterable=True - ), - SearchableField( - name="HotelName", type=SearchFieldDataType.String, sortable=True - ), - SearchableField(name="Description", type=SearchFieldDataType.String), + SimpleField(name="HotelId", type=SearchFieldDataType.STRING, key=True, filterable=True), + SearchableField(name="HotelName", type=SearchFieldDataType.STRING, sortable=True), + SearchableField(name="Description", type=SearchFieldDataType.STRING), SearchField( name="DescriptionVector", - type=SearchFieldDataType.Collection(SearchFieldDataType.Single), + type=SearchFieldDataType.Collection(SearchFieldDataType.SINGLE), # type: ignore[operator] searchable=True, vector_search_dimensions=1536, vector_search_profile_name="my-vector-profile", ), SearchableField( name="Category", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, sortable=True, filterable=True, facetable=True, ), SearchField( name="Tags", - type=SearchFieldDataType.Collection(SearchFieldDataType.String), + type=SearchFieldDataType.Collection(SearchFieldDataType.STRING), # type: ignore[operator] searchable=True, filterable=True, facetable=True, @@ -101,10 +97,8 @@ def create_index(): vector_search = VectorSearch( algorithms=[ - HnswAlgorithmConfiguration(name="my-hnsw-vector-config-1", kind="hnsw"), - ExhaustiveKnnAlgorithmConfiguration( - name="my-eknn-vector-config", kind="exhaustiveKnn" - ), + HnswAlgorithmConfiguration(name="my-hnsw-vector-config-1"), + ExhaustiveKnnAlgorithmConfiguration(name="my-eknn-vector-config"), ], profiles=[ VectorSearchProfile( @@ -161,7 +155,7 @@ def single_vector_search(): vector_query = VectorizedQuery( vector=vector, - k=5, + k_nearest_neighbors=5, fields="DescriptionVector", ) @@ -174,8 +168,7 @@ def single_vector_search(): print("Results: single vector search") for result in results: print( - f" HotelId: {result['HotelId']}, HotelName: {result['HotelName']}, " - f"Category: {result.get('Category')}" + f" HotelId: {result['HotelId']}, HotelName: {result['HotelName']}, " f"Category: {result.get('Category')}" ) # [END single_vector_search] @@ -187,7 +180,7 @@ def single_vector_search_with_filter(): vector_query = VectorizedQuery( vector=vector, - k=5, + k_nearest_neighbors=5, fields="DescriptionVector", ) @@ -200,10 +193,7 @@ def single_vector_search_with_filter(): print("Results: vector search with filter") for result in results: - print( - f" HotelId: {result['HotelId']}, HotelName: {result['HotelName']}, " - f"Tags: {result.get('Tags')}" - ) + print(f" HotelId: {result['HotelId']}, HotelName: {result['HotelName']}, " f"Tags: {result.get('Tags')}") # [END single_vector_search_with_filter] @@ -214,7 +204,7 @@ def simple_hybrid_search(): vector_query = VectorizedQuery( vector=vector, - k=5, + k_nearest_neighbors=5, fields="DescriptionVector", ) diff --git a/sdk/search/azure-search-documents/samples/sample_search_client_custom_request.py b/sdk/search/azure-search-documents/samples/sample_search_client_custom_request.py index 43040de55cbf..63318cceb79f 100644 --- a/sdk/search/azure-search-documents/samples/sample_search_client_custom_request.py +++ b/sdk/search/azure-search-documents/samples/sample_search_client_custom_request.py @@ -35,9 +35,7 @@ def sample_send_request(): # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, # while adding convenience for endpoint construction. - request = HttpRequest( - method="GET", url=f"/docs/$count?api-version={AZURE_SEARCH_API_VERSION}" - ) + request = HttpRequest(method="GET", url=f"/docs/$count?api-version={AZURE_SEARCH_API_VERSION}") response = search_client.send_request(request) response.raise_for_status() response_body = response.json() diff --git a/sdk/search/azure-search-documents/setup.py b/sdk/search/azure-search-documents/setup.py deleted file mode 100644 index df9a2295a11a..000000000000 --- a/sdk/search/azure-search-documents/setup.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/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 os -import re - -from setuptools import setup, find_packages - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-search-documents" -PACKAGE_PPRINT_NAME = "Azure Cognitive Search" - -# a-b-c => a/b/c -PACKAGE_FOLDER_PATH = PACKAGE_NAME.replace("-", "/") -# a-b-c => a.b.c -NAMESPACE_NAME = PACKAGE_NAME.replace("-", ".") - -# 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*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError("Cannot find version information") - -setup( - name=PACKAGE_NAME, - version=version, - include_package_data=True, - description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), - long_description=open("README.md", "r").read(), - long_description_content_type="text/markdown", - license="MIT License", - author="Microsoft Corporation", - author_email="ascl@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/search/azure-search-documents", - keywords="azure, azure sdk", - classifiers=[ - "Development Status :: 4 - Beta", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "License :: OSI Approved :: MIT License", - ], - zip_safe=False, - packages=find_packages( - exclude=[ - "samples", - "tests", - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - "azure.search", - ] - ), - python_requires=">=3.8", - install_requires=[ - "azure-core>=1.28.0", - "azure-common>=1.1", - "isodate>=0.6.0", - "typing-extensions>=4.6.0", - ], -) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py index 7c292e09e25e..6d49a99a181b 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -18,9 +19,7 @@ class TestSearchBatchingClientAsync: @await_prepared_test async def test_search_indexing_buffered_sender_kwargs(self): - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, window=100 - ) as client: + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, window=100) as client: assert client._batch_action_count == 512 assert client._max_retries_per_action == 3 assert client._auto_flush_interval == 60 @@ -28,42 +27,32 @@ async def test_search_indexing_buffered_sender_kwargs(self): @await_prepared_test async def test_batch_queue(self): - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False - ) as client: - assert client._index_documents_batch - await client.upload_documents(["upload1"]) - await client.delete_documents(["delete1", "delete2"]) - await client.merge_documents(["merge1", "merge2", "merge3"]) - await client.merge_or_upload_documents(["merge_or_upload1"]) + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + assert not (client._index_documents_batch is None) + await client.upload_documents([{"upload1": "doc"}]) + await client.delete_documents([{"delete1": "doc"}, {"delete2": "doc"}]) + await client.merge_documents([{"merge1": "doc"}, {"merge2": "doc"}, {"merge3": "doc"}]) + await client.merge_or_upload_documents([{"merge_or_upload1": "doc"}]) assert len(client.actions) == 7 - actions = await client._index_documents_batch.dequeue_actions() + actions = client._index_documents_batch.dequeue_actions() assert len(client.actions) == 0 - await client._index_documents_batch.enqueue_actions(actions) + client._index_documents_batch.enqueue_actions(actions) assert len(client.actions) == 7 @await_prepared_test - @mock.patch( - "azure.search.documents.aio._search_indexing_buffered_sender_async.SearchIndexingBufferedSender._process_if_needed" - ) + @mock.patch("azure.search.documents.aio._patch.SearchIndexingBufferedSender._process_if_needed") async def test_process_if_needed(self, mock_process_if_needed): - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL - ) as client: - await client.upload_documents(["upload1"]) - await client.delete_documents(["delete1", "delete2"]) + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL) as client: + await client.upload_documents([{"upload1": "doc"}]) + await client.delete_documents([{"delete1": "doc"}, {"delete2": "doc"}]) assert mock_process_if_needed.called @await_prepared_test - @mock.patch( - "azure.search.documents.aio._search_indexing_buffered_sender_async.SearchIndexingBufferedSender._cleanup" - ) + @mock.patch("azure.search.documents.aio._patch.SearchIndexingBufferedSender._cleanup") async def test_context_manager(self, mock_cleanup): - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False - ) as client: - await client.upload_documents(["upload1"]) - await client.delete_documents(["delete1", "delete2"]) + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + await client.upload_documents([{"upload1": "doc"}]) + await client.delete_documents([{"delete1": "doc"}, {"delete2": "doc"}]) assert mock_cleanup.called @await_prepared_test @@ -80,9 +69,7 @@ async def test_flush(self): "_index_documents_actions", side_effect=HttpResponseError("Error"), ): - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False - ) as client: + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: client._index_key = "hotelId" await client.upload_documents([DOCUMENT]) await client.flush() @@ -94,7 +81,7 @@ async def test_callback_new(self): async with SearchIndexingBufferedSender( "endpoint", "index name", CREDENTIAL, auto_flush=False, on_new=on_new ) as client: - await client.upload_documents(["upload1"]) + await client.upload_documents([{"upload1": "doc"}]) assert on_new.called @await_prepared_test @@ -102,10 +89,9 @@ async def test_callback_error(self): async def mock_fail_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 400 result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 return [result] on_error = mock.AsyncMock() @@ -114,7 +100,7 @@ async def mock_fail_index_documents(actions, timeout=86400): ) as client: client._index_documents_actions = mock_fail_index_documents client._index_key = "id" - await client.upload_documents({"id": 0}) + await client.upload_documents([{"id": 0}]) await client.flush() assert on_error.called @@ -123,10 +109,9 @@ async def test_callback_error_on_timeout(self): async def mock_fail_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 400 result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 time.sleep(1) return [result] @@ -146,7 +131,7 @@ async def test_callback_progress(self): async def mock_successful_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 200 result.succeeded = True return [result] @@ -163,7 +148,7 @@ async def mock_successful_index_documents(actions, timeout=86400): ) as client: client._index_documents_actions = mock_successful_index_documents client._index_key = "id" - await client.upload_documents({"id": 0}) + await client.upload_documents([{"id": 0}]) await client.flush() assert on_progress.called assert on_remove.called diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_configuration_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_configuration_live_async.py index ab8981ba605c..5f77ccf60cc9 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_configuration_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_configuration_live_async.py @@ -15,13 +15,20 @@ from azure.search.documents.indexes.aio import SearchIndexClient from azure.search.documents.indexes.models import ( KnowledgeBase, + KnowledgeSourceReference, + SearchField, + SearchFieldDataType, + SearchIndex, + SearchIndexKnowledgeSource, + SearchIndexKnowledgeSourceParameters, + SemanticConfiguration, + SemanticField, + SemanticPrioritizedFields, + SemanticSearch, +) +from azure.search.documents.knowledgebases.models import ( KnowledgeRetrievalMediumReasoningEffort, KnowledgeRetrievalMinimalReasoningEffort, - KnowledgeSourceReference, - WebKnowledgeSource, - WebKnowledgeSourceDomain, - WebKnowledgeSourceDomains, - WebKnowledgeSourceParameters, ) from search_service_preparer import SearchEnvVarPreparer, search_decorator @@ -31,12 +38,14 @@ class _AsyncTestContext: def __init__( self, index_client: SearchIndexClient, + index_name: str, source_name: str, - created_source: WebKnowledgeSource, + created_source: SearchIndexKnowledgeSource, base_name: str, created_base: KnowledgeBase, ) -> None: self.index_client = index_client + self.index_name = index_name self.source_name = source_name self.created_source = created_source self.base_name = base_name @@ -48,21 +57,8 @@ async def _create_context(self, endpoint: str) -> "_AsyncTestContext": credential = get_credential(is_async=True) index_client = SearchIndexClient(endpoint, credential, retry_backoff_factor=60) + index_name = self.get_resource_name("cfgidx") source_name = self.get_resource_name("cfgks") - create_source = WebKnowledgeSource( - name=source_name, - description="configuration source", - web_parameters=WebKnowledgeSourceParameters( - domains=WebKnowledgeSourceDomains( - allowed_domains=[ - WebKnowledgeSourceDomain( - address="https://learn.microsoft.com", - include_subpages=True, - ) - ] - ) - ), - ) base_name = self.get_resource_name("cfgkb") # best-effort cleanup in case a previous run failed before teardown @@ -74,7 +70,38 @@ async def _create_context(self, endpoint: str) -> "_AsyncTestContext": await index_client.delete_knowledge_source(source_name) except HttpResponseError: pass + try: + await index_client.delete_index(index_name) + except HttpResponseError: + pass + + # Create a search index with semantic configuration (required for SearchIndexKnowledgeSource) + index = SearchIndex( + name=index_name, + fields=[ + SearchField(name="id", type=SearchFieldDataType.String, key=True), + SearchField(name="content", type=SearchFieldDataType.String, searchable=True), + ], + semantic_search=SemanticSearch( + default_configuration_name="default", + configurations=[ + SemanticConfiguration( + name="default", + prioritized_fields=SemanticPrioritizedFields( + content_fields=[SemanticField(field_name="content")] + ), + ) + ], + ), + ) + await index_client.create_index(index) + # Create knowledge source pointing to the index + create_source = SearchIndexKnowledgeSource( + name=source_name, + description="configuration source", + search_index_parameters=SearchIndexKnowledgeSourceParameters(search_index_name=index_name), + ) created_source = await index_client.create_knowledge_source(create_source) create_base = KnowledgeBase( @@ -92,11 +119,13 @@ async def _create_context(self, endpoint: str) -> "_AsyncTestContext": await index_client.delete_knowledge_source(created_source) except HttpResponseError: pass + try: + await index_client.delete_index(index_name) + except HttpResponseError: + pass raise - return _AsyncTestContext( - index_client, source_name, created_source, base_name, created_base - ) + return _AsyncTestContext(index_client, index_name, source_name, created_source, base_name, created_base) async def _cleanup(self, ctx: "_AsyncTestContext") -> None: try: @@ -114,6 +143,10 @@ async def _cleanup(self, ctx: "_AsyncTestContext") -> None: ) except HttpResponseError: pass + try: + await ctx.index_client.delete_index(ctx.index_name) + except HttpResponseError: + pass finally: await ctx.index_client.close() diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_live_async.py index 40b7efa414b9..541543b882dd 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_base_live_async.py @@ -16,12 +16,17 @@ from azure.search.documents.indexes.models import ( KnowledgeBase, KnowledgeSourceReference, + SearchField, + SearchFieldDataType, + SearchIndex, + SearchIndexKnowledgeSource, + SearchIndexKnowledgeSourceParameters, SearchServiceStatistics, + SemanticConfiguration, + SemanticField, + SemanticPrioritizedFields, + SemanticSearch, ServiceIndexersRuntime, - WebKnowledgeSource, - WebKnowledgeSourceDomain, - WebKnowledgeSourceDomains, - WebKnowledgeSourceParameters, ) from search_service_preparer import SearchEnvVarPreparer, search_decorator @@ -31,12 +36,14 @@ class _AsyncTestContext: def __init__( self, index_client: SearchIndexClient, + index_name: str, source_name: str, - created_source: WebKnowledgeSource, + created_source: SearchIndexKnowledgeSource, base_name: str, created_base: KnowledgeBase, ) -> None: self.index_client = index_client + self.index_name = index_name self.source_name = source_name self.created_source = created_source self.base_name = base_name @@ -48,21 +55,36 @@ async def _create_context(self, endpoint: str) -> "_AsyncTestContext": credential = get_credential(is_async=True) index_client = SearchIndexClient(endpoint, credential, retry_backoff_factor=60) + index_name = self.get_resource_name("kbidx") source_name = self.get_resource_name("ksrc") base_name = self.get_resource_name("kb") - create_source = WebKnowledgeSource( + + # Create a search index with semantic configuration (required for SearchIndexKnowledgeSource) + index = SearchIndex( + name=index_name, + fields=[ + SearchField(name="id", type=SearchFieldDataType.String, key=True), + SearchField(name="content", type=SearchFieldDataType.String, searchable=True), + ], + semantic_search=SemanticSearch( + default_configuration_name="default", + configurations=[ + SemanticConfiguration( + name="default", + prioritized_fields=SemanticPrioritizedFields( + content_fields=[SemanticField(field_name="content")] + ), + ) + ], + ), + ) + await index_client.create_index(index) + + # Create knowledge source pointing to the index + create_source = SearchIndexKnowledgeSource( name=source_name, description="knowledge base dependent source", - web_parameters=WebKnowledgeSourceParameters( - domains=WebKnowledgeSourceDomains( - allowed_domains=[ - WebKnowledgeSourceDomain( - address="https://learn.microsoft.com", - include_subpages=True, - ) - ] - ) - ), + search_index_parameters=SearchIndexKnowledgeSourceParameters(search_index_name=index_name), ) created_source = await index_client.create_knowledge_source(create_source) @@ -72,9 +94,7 @@ async def _create_context(self, endpoint: str) -> "_AsyncTestContext": knowledge_sources=[KnowledgeSourceReference(name=source_name)], ) created_base = await index_client.create_knowledge_base(create_base) - return _AsyncTestContext( - index_client, source_name, created_source, base_name, created_base - ) + return _AsyncTestContext(index_client, index_name, source_name, created_source, base_name, created_base) async def _cleanup(self, ctx: "_AsyncTestContext") -> None: try: @@ -92,6 +112,10 @@ async def _cleanup(self, ctx: "_AsyncTestContext") -> None: ) except HttpResponseError: pass + try: + await ctx.index_client.delete_index(ctx.index_name) + except HttpResponseError: + pass finally: await ctx.index_client.close() @@ -156,10 +180,7 @@ async def test_knowledge_base_read(self, endpoint: str) -> None: listed = [item async for item in ctx.index_client.list_knowledge_bases()] assert fetched.name == ctx.base_name - assert ( - fetched.knowledge_sources - and fetched.knowledge_sources[0].name == ctx.source_name - ) + assert fetched.knowledge_sources and fetched.knowledge_sources[0].name == ctx.source_name assert any(item.name == ctx.base_name for item in listed) finally: await self._cleanup(ctx) @@ -212,9 +233,7 @@ async def test_service_indexer_runtime_statistics(self, endpoint: str) -> None: snapshots = await self._poll_status_snapshots(ctx) assert snapshots, "Expected at least one status snapshot" - service_stats = ( - await ctx.index_client._client.get_service_statistics() - ) # pylint:disable=protected-access + service_stats = await ctx.index_client.get_service_statistics() # pylint:disable=protected-access assert isinstance(service_stats, SearchServiceStatistics) runtime = service_stats.indexers_runtime diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_remote_sharepoint_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_remote_sharepoint_live_async.py index a5c678e07822..7b000bbf63a5 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_remote_sharepoint_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_remote_sharepoint_live_async.py @@ -63,9 +63,7 @@ async def _cleanup(self, ctx: "_AsyncTestContext") -> None: @SearchEnvVarPreparer() @search_decorator(schema=None, index_batch=None) @recorded_by_proxy_async - async def test_remote_sharepoint_knowledge_source_create( - self, endpoint: str - ) -> None: + async def test_remote_sharepoint_knowledge_source_create(self, endpoint: str) -> None: ctx = await self._create_context(endpoint) try: assert ctx.created_revision.name == ctx.source_name @@ -81,9 +79,7 @@ async def test_remote_sharepoint_knowledge_source_create( @SearchEnvVarPreparer() @search_decorator(schema=None, index_batch=None) @recorded_by_proxy_async - async def test_remote_sharepoint_knowledge_source_update( - self, endpoint: str - ) -> None: + async def test_remote_sharepoint_knowledge_source_update(self, endpoint: str) -> None: ctx = await self._create_context(endpoint) try: update_model = RemoteSharePointKnowledgeSource( @@ -121,18 +117,14 @@ async def test_remote_sharepoint_knowledge_source_read(self, endpoint: str) -> N @SearchEnvVarPreparer() @search_decorator(schema=None, index_batch=None) @recorded_by_proxy_async - async def test_remote_sharepoint_knowledge_source_delete( - self, endpoint: str - ) -> None: + async def test_remote_sharepoint_knowledge_source_delete(self, endpoint: str) -> None: ctx = await self._create_context(endpoint) try: await ctx.index_client.delete_knowledge_source( ctx.created_revision, match_condition=MatchConditions.IfNotModified, ) - remaining = [ - item async for item in ctx.index_client.list_knowledge_sources() - ] + remaining = [item async for item in ctx.index_client.list_knowledge_sources()] assert all(item.name != ctx.source_name for item in remaining) finally: await ctx.index_client.close() diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_web_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_web_live_async.py index 840718b35a9c..941c43133707 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_web_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_knowledge_source_web_live_async.py @@ -131,9 +131,7 @@ async def test_web_knowledge_source_delete(self, endpoint: str) -> None: ctx.created_revision, match_condition=MatchConditions.IfNotModified, ) - remaining = [ - item async for item in ctx.index_client.list_knowledge_sources() - ] + remaining = [item async for item in ctx.index_client.list_knowledge_sources()] assert all(item.name != ctx.source_name for item in remaining) finally: await ctx.index_client.close() diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py index 39fb7f32a4ed..5ee4c0503ce3 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py @@ -4,13 +4,13 @@ # ------------------------------------ from unittest import mock from azure.core.credentials import AzureKeyCredential -from azure.search.documents._generated.models import ( +from azure.search.documents.aio._operations._patch import AsyncSearchPageIterator +from azure.search.documents.models import ( FacetResult, SearchDocumentsResult, SearchResult, ) from azure.search.documents.aio import SearchClient -from azure.search.documents.aio._search_client_async import AsyncSearchPageIterator from test_search_index_client_async import await_prepared_test CREDENTIAL = AzureKeyCredential(key="test_api_key") @@ -18,15 +18,13 @@ class TestSearchClientAsync: @await_prepared_test - @mock.patch( - "azure.search.documents._generated.aio.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents.aio._operations._operations._SearchClientOperationsMixin._search_post") async def test_get_count_reset_continuation_token(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = await client.search(search_text="search text") assert result._page_iterator_class is AsyncSearchPageIterator search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result await result.__anext__() result._first_page_iterator_instance.continuation_token = "fake token" @@ -34,9 +32,7 @@ async def test_get_count_reset_continuation_token(self, mock_search_post): assert not result._first_page_iterator_instance.continuation_token @await_prepared_test - @mock.patch( - "azure.search.documents._generated.aio.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents.aio._operations._operations._SearchClientOperationsMixin._search_post") async def test_search_enable_elevated_read(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = await client.search( @@ -45,27 +41,22 @@ async def test_search_enable_elevated_read(self, mock_search_post): x_ms_query_source_authorization="aad:fake-user", ) search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result await result.__anext__() assert mock_search_post.called assert mock_search_post.call_args[1]["x_ms_enable_elevated_read"] is True - assert ( - mock_search_post.call_args[1]["x_ms_query_source_authorization"] - == "aad:fake-user" - ) + assert mock_search_post.call_args[1]["x_ms_query_source_authorization"] == "aad:fake-user" @await_prepared_test - @mock.patch( - "azure.search.documents._generated.aio.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents.aio._operations._operations._SearchClientOperationsMixin._search_post") async def test_get_facets_with_aggregations(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = await client.search(search_text="*") search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"id": "1"})] + search_result.results = [SearchResult({"id": "1"})] facet_bucket = FacetResult() facet_bucket.count = 4 diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py index cddb9b1e30ef..05ad3b2a6bdd 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py @@ -21,9 +21,7 @@ class TestSearchIndexingBufferedSenderAsync(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy_async async def test_search_client_index_buffered_sender(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) batch_client = SearchIndexingBufferedSender( endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60 ) @@ -31,27 +29,13 @@ async def test_search_client_index_buffered_sender(self, endpoint, index_name): async with client: async with batch_client: doc_count = 10 - doc_count = await self._test_upload_documents_new( - client, batch_client, doc_count - ) - doc_count = await self._test_upload_documents_existing( - client, batch_client, doc_count - ) - doc_count = await self._test_delete_documents_existing( - client, batch_client, doc_count - ) - doc_count = await self._test_delete_documents_missing( - client, batch_client, doc_count - ) - doc_count = await self._test_merge_documents_existing( - client, batch_client, doc_count - ) - doc_count = await self._test_merge_documents_missing( - client, batch_client, doc_count - ) - doc_count = await self._test_merge_or_upload_documents( - client, batch_client, doc_count - ) + doc_count = await self._test_upload_documents_new(client, batch_client, doc_count) + doc_count = await self._test_upload_documents_existing(client, batch_client, doc_count) + doc_count = await self._test_delete_documents_existing(client, batch_client, doc_count) + doc_count = await self._test_delete_documents_missing(client, batch_client, doc_count) + doc_count = await self._test_merge_documents_existing(client, batch_client, doc_count) + doc_count = await self._test_merge_documents_missing(client, batch_client, doc_count) + doc_count = await self._test_merge_or_upload_documents(client, batch_client, doc_count) finally: await batch_client.close() diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py index 4af2cc9698de..c021c11c6fb8 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py @@ -21,9 +21,7 @@ class TestSearchClientDocumentsAsync(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy_async async def test_search_client_index_document(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) doc_count = 10 async with client: doc_count = await self._test_upload_documents_new(client, doc_count) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py index 8ac745e79649..a3eec2f3ff63 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py @@ -18,9 +18,7 @@ class TestClientTestAsync(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy_async async def test_search_client(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) async with client: await self._test_get_search_simple(client) await self._test_get_search_simple_with_top(client) @@ -66,9 +64,7 @@ async def _test_get_search_filter(self, client): order_by="hotelName desc", ): results.append(x) - assert [x["hotelName"] for x in results] == sorted( - [x["hotelName"] for x in results], reverse=True - ) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) expected = { "category", "hotelName", @@ -93,9 +89,7 @@ async def _test_get_search_filter_array(self, client): order_by="hotelName desc", ): results.append(x) - assert [x["hotelName"] for x in results] == sorted( - [x["hotelName"] for x in results], reverse=True - ) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) expected = { "category", "hotelName", @@ -133,9 +127,7 @@ async def _test_get_search_facets_none(self, client): async def _test_get_search_facets_result(self, client): select = ("hotelName", "category", "description") - results = await client.search( - search_text="WiFi", facets=["category"], select=",".join(select) - ) + results = await client.search(search_text="WiFi", facets=["category"], select=",".join(select)) assert await results.get_facets() == { "category": [ {"value": "Budget", "count": 4}, @@ -181,14 +173,17 @@ async def _test_get_search_facet_metrics(self, client): async def _test_autocomplete(self, client): results = await client.autocomplete(search_text="mot", suggester_name="sg") - assert results == [{"text": "motel", "query_plus_text": "motel"}] + assert any(d.text == "motel" for d in results) + assert any(d.query_plus_text == "motel" for d in results) async def _test_suggest(self, client): results = await client.suggest(search_text="mot", suggester_name="sg") - assert results == [ - {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, - {"hotelId": "9", "text": "Secret Point Motel"}, - ] + result = results[0] + assert result["hotelId"] == "2" + assert result.text == "Cheapest hotel in town. Infact, a motel." + result = results[1] + assert result["hotelId"] == "9" + assert result.text == "Secret Point Motel" @SearchEnvVarPreparer() @search_decorator(schema="hotel_schema.json", index_batch="hotel_large.json") diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py index 0ebf267545f5..3ea3d88fd418 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py @@ -30,9 +30,7 @@ class TestSearchClientAlias(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy_async async def test_alias(self, endpoint): - client = SearchIndexClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) aliases = ["resort", "motel"] async with client: @@ -44,9 +42,7 @@ async def test_alias(self, endpoint): # point an old alias to a new index new_index_name = "hotel" - await self._test_update_alias_to_new_index( - client, aliases[1], new_index_name, index_name - ) + await self._test_update_alias_to_new_index(client, aliases[1], new_index_name, index_name) await self._test_get_alias(client, aliases) @@ -70,9 +66,7 @@ async def _test_create_or_update_alias(self, client, alias_name, index_name): assert result.name == alias_name assert set(result.indexes) == {index_name} - async def _test_update_alias_to_new_index( - self, client, alias_name, new_index, old_index - ): + async def _test_update_alias_to_new_index(self, client, alias_name, new_index, old_index): await self._create_index(client, new_index) alias = SearchAlias(name=alias_name, indexes=[new_index]) result = await client.create_or_update_alias(alias) @@ -101,8 +95,8 @@ async def _test_delete_aliases(self, client): async def _create_index(self, client, index_name): fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), ] scoring_profile = ScoringProfile(name="MyProfile") scoring_profiles = [] diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py index e70080fc9f43..dd0fd3a611e4 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py @@ -42,90 +42,3 @@ def run(test_class_instance, *args, **kwargs): asyncio.set_event_loop(None) return run - - -class TestSearchIndexClient: - def test_index_init(self): - client = SearchIndexClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_index_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_get_search_client(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - - def test_get_search_client_inherit_api_version(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient( - "endpoint", credential, api_version=ApiVersion.V2020_06_30 - ) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - assert search_client._api_version == ApiVersion.V2020_06_30 - - def test_index_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexClient(12345, credential) - - -class TestSearchIndexerClient: - def test_indexer_init(self): - client = SearchIndexerClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexerClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexerClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexerClient(12345, credential) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py index a05064f20d4a..e5d15a396ff5 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py @@ -31,34 +31,26 @@ def _create_data_source_connection(self, cs, name): @recorded_by_proxy_async async def test_data_source(self, endpoint, **kwargs): storage_cs = kwargs.get("search_storage_connection_string") - client = SearchIndexerClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) async with client: await self._test_create_datasource(client, storage_cs) await self._test_delete_datasource(client, storage_cs) await self._test_get_datasource(client, storage_cs) await self._test_list_datasources(client, storage_cs) await self._test_create_or_update_datasource(client, storage_cs) - await self._test_create_or_update_datasource_if_unchanged( - client, storage_cs - ) + await self._test_create_or_update_datasource_if_unchanged(client, storage_cs) await self._test_delete_datasource_if_unchanged(client, storage_cs) async def _test_create_datasource(self, client, storage_cs): ds_name = "create" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) result = await client.create_data_source_connection(data_source_connection) assert result.name == ds_name assert result.type == "azureblob" async def _test_delete_datasource(self, client, storage_cs): ds_name = "delete" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) await client.create_data_source_connection(data_source_connection) expected_count = len(await client.get_data_source_connections()) - 1 await client.delete_data_source_connection(ds_name) @@ -66,33 +58,23 @@ async def _test_delete_datasource(self, client, storage_cs): async def _test_get_datasource(self, client, storage_cs): ds_name = "get" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) await client.create_data_source_connection(data_source_connection) result = await client.get_data_source_connection(ds_name) assert result.name == ds_name async def _test_list_datasources(self, client, storage_cs): - data_source_connection1 = self._create_data_source_connection( - storage_cs, "list" - ) - data_source_connection2 = self._create_data_source_connection( - storage_cs, "list2" - ) + data_source_connection1 = self._create_data_source_connection(storage_cs, "list") + data_source_connection2 = self._create_data_source_connection(storage_cs, "list2") await client.create_data_source_connection(data_source_connection1) await client.create_data_source_connection(data_source_connection2) result = await client.get_data_source_connections() assert isinstance(result, list) - assert set(x.name for x in result).intersection(set(["list", "list2"])) == set( - ["list", "list2"] - ) + assert set(x.name for x in result).intersection(set(["list", "list2"])) == set(["list", "list2"]) async def _test_create_or_update_datasource(self, client, storage_cs): ds_name = "cou" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) await client.create_data_source_connection(data_source_connection) expected_count = len(await client.get_data_source_connections()) data_source_connection.description = "updated" @@ -104,9 +86,7 @@ async def _test_create_or_update_datasource(self, client, storage_cs): async def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): ds_name = "couunch" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) created = await client.create_data_source_connection(data_source_connection) etag = created.e_tag @@ -115,9 +95,7 @@ async def _test_create_or_update_datasource_if_unchanged(self, client, storage_c await client.create_or_update_data_source_connection(data_source_connection) # prepare data source connection - data_source_connection.e_tag = ( - etag # reset to the original data source connection - ) + data_source_connection.e_tag = etag # reset to the original data source connection data_source_connection.description = "changed" with pytest.raises(HttpResponseError): await client.create_or_update_data_source_connection( @@ -126,9 +104,7 @@ async def _test_create_or_update_datasource_if_unchanged(self, client, storage_c async def _test_delete_datasource_if_unchanged(self, client, storage_cs): ds_name = "delunch" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) created = await client.create_data_source_connection(data_source_connection) etag = created.e_tag @@ -137,9 +113,7 @@ async def _test_delete_datasource_if_unchanged(self, client, storage_cs): await client.create_or_update_data_source_connection(data_source_connection) # prepare data source connection - data_source_connection.e_tag = ( - etag # reset to the original data source connection - ) + data_source_connection.e_tag = etag # reset to the original data source connection with pytest.raises(HttpResponseError): await client.delete_data_source_connection( data_source_connection, match_condition=MatchConditions.IfNotModified diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py index ba77658de89b..a7db4d3f4818 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py @@ -33,9 +33,7 @@ class TestSearchIndexClientAsync(AzureRecordedTestCase): @search_decorator(schema=None, index_batch=None) @recorded_by_proxy_async async def test_search_index_client(self, endpoint, index_name): - client = SearchIndexClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) index_name = "hotels" async with client: await self._test_get_service_statistics(client) @@ -52,8 +50,8 @@ async def test_search_index_client(self, endpoint, index_name): async def _test_get_service_statistics(self, client): result = await client.get_service_statistics() - assert isinstance(result, dict) - assert set(result.keys()) == {"counters", "limits"} + assert "counters" in set(result.keys()) + assert "limits" in set(result.keys()) async def _test_list_indexes_empty(self, client): result = client.list_indexes() @@ -62,8 +60,8 @@ async def _test_list_indexes_empty(self, client): async def _test_create_index(self, client, index_name): fields = fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), ] scoring_profile = ScoringProfile(name="MyProfile") @@ -96,9 +94,9 @@ async def _test_get_index(self, client, index_name): async def _test_get_index_statistics(self, client, index_name): result = await client.get_index_statistics(index_name) keys = set(result.keys()) - assert "document_count" in keys - assert "storage_size" in keys - assert "vector_index_size" in keys + assert "documentCount" in keys + assert "storageSize" in keys + assert "vectorIndexSize" in keys async def _test_delete_indexes_if_unchanged(self, client): # First create an index @@ -125,15 +123,13 @@ async def _test_delete_indexes_if_unchanged(self, client): index.e_tag = etag with pytest.raises(HttpResponseError): - await client.delete_index( - index, match_condition=MatchConditions.IfNotModified - ) + await client.delete_index(index, match_condition=MatchConditions.IfNotModified) async def _test_create_or_update_index(self, client): name = "hotels-cou" fields = fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), ] cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) @@ -187,14 +183,10 @@ async def _test_create_or_update_indexes_if_unchanged(self, client): index.e_tag = etag with pytest.raises(HttpResponseError): - await client.create_or_update_index( - index, match_condition=MatchConditions.IfNotModified - ) + await client.create_or_update_index(index, match_condition=MatchConditions.IfNotModified) async def _test_analyze_text(self, client, index_name): - analyze_request = AnalyzeTextOptions( - text="One's ", analyzer_name="standard.lucene" - ) + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") result = await client.analyze_text(index_name, analyze_request) assert len(result.tokens) == 2 @@ -205,27 +197,23 @@ async def _test_delete_indexes(self, client): @SearchEnvVarPreparer() @recorded_by_proxy_async - async def test_purview_enabled_index( - self, search_service_endpoint, search_service_name - ): + async def test_purview_enabled_index(self, search_service_endpoint, search_service_name): del search_service_name # unused endpoint = search_service_endpoint - client = SearchIndexClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) index_name = self.get_resource_name("purview-index") fields = [ SearchField( name="id", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, key=True, filterable=True, sortable=True, ), SearchField( name="sensitivityLabel", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, filterable=True, sensitivity_label=True, ), @@ -241,9 +229,7 @@ async def test_purview_enabled_index( assert field.sensitivity_label is True break else: - raise AssertionError( - "Expected sensitivityLabel field to be present" - ) + raise AssertionError("Expected sensitivityLabel field to be present") fetched = await client.get_index(index_name) assert fetched.purview_enabled is True @@ -252,9 +238,7 @@ async def test_purview_enabled_index( assert field.sensitivity_label is True break else: - raise AssertionError( - "Expected sensitivityLabel field to be present" - ) + raise AssertionError("Expected sensitivityLabel field to be present") finally: try: await client.delete_index(index_name) @@ -263,21 +247,17 @@ async def test_purview_enabled_index( @SearchEnvVarPreparer() @recorded_by_proxy_async - async def test_scoring_profile_product_aggregation( - self, search_service_endpoint, search_service_name - ): + async def test_scoring_profile_product_aggregation(self, search_service_endpoint, search_service_name): del search_service_name # unused endpoint = search_service_endpoint - client = SearchIndexClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) index_name = self.get_resource_name("agg-product") fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), SimpleField( name="lastUpdated", - type=SearchFieldDataType.DateTimeOffset, + type=SearchFieldDataType.DATE_TIME_OFFSET, filterable=True, ), ] @@ -288,40 +268,25 @@ async def test_scoring_profile_product_aggregation( FreshnessScoringFunction( field_name="lastUpdated", boost=2.5, - parameters=FreshnessScoringParameters( - boosting_duration=timedelta(days=7) - ), + parameters=FreshnessScoringParameters(boosting_duration=timedelta(days=7)), ) ], ) - index = SearchIndex( - name=index_name, fields=fields, scoring_profiles=[scoring_profile] - ) + index = SearchIndex(name=index_name, fields=fields, scoring_profiles=[scoring_profile]) async with client: created = await client.create_index(index) try: - assert ( - created.scoring_profiles[0].function_aggregation - == ScoringFunctionAggregation.PRODUCT - ) + assert created.scoring_profiles[0].function_aggregation == ScoringFunctionAggregation.PRODUCT fetched = await client.get_index(index_name) - assert ( - fetched.scoring_profiles[0].function_aggregation - == ScoringFunctionAggregation.PRODUCT - ) + assert fetched.scoring_profiles[0].function_aggregation == ScoringFunctionAggregation.PRODUCT - fetched.scoring_profiles[0].function_aggregation = ( - ScoringFunctionAggregation.SUM - ) + fetched.scoring_profiles[0].function_aggregation = ScoringFunctionAggregation.SUM await client.create_or_update_index(index=fetched) updated = await client.get_index(index_name) - assert ( - updated.scoring_profiles[0].function_aggregation - == ScoringFunctionAggregation.SUM - ) + assert updated.scoring_profiles[0].function_aggregation == ScoringFunctionAggregation.SUM finally: try: await client.delete_index(index_name) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py index b9e19a8a45dd..8829a539a3d1 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py @@ -12,13 +12,11 @@ from search_service_preparer import SearchEnvVarPreparer, search_decorator from azure.search.documents.indexes.models import ( EntityLinkingSkill, - EntityRecognitionSkill, - EntityRecognitionSkillVersion, + EntityRecognitionSkillV3 as EntityRecognitionSkill, InputFieldMappingEntry, OutputFieldMappingEntry, SearchIndexerSkillset, - SentimentSkill, - SentimentSkillVersion, + SentimentSkillV3 as SentimentSkill, ) from azure.search.documents.indexes.aio import SearchIndexerClient @@ -29,9 +27,7 @@ class TestSearchClientSkillsets(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy_async async def test_skillset_crud(self, endpoint): - client = SearchIndexerClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) async with client: await self._test_create_skillset(client) await self._test_get_skillset(client) @@ -47,11 +43,7 @@ async def _test_create_skillset(self, client): s1 = EntityRecognitionSkill( name="skill1", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizationsS1" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], description="Skill Version 1", model_version="1", include_typeless_entities=True, @@ -60,32 +52,15 @@ async def _test_create_skillset(self, client): s2 = EntityRecognitionSkill( name="skill2", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizationsS2" - ) - ], - skill_version=EntityRecognitionSkillVersion.LATEST, + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], description="Skill Version 3", model_version="3", include_typeless_entities=True, ) - s3 = SentimentSkill( - name="skill3", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], - skill_version=SentimentSkillVersion.V1, - description="Sentiment V1", - include_opinion_mining=True, - ) - s4 = SentimentSkill( name="skill4", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4") - ], - skill_version=SentimentSkillVersion.V3, + outputs=[OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4")], description="Sentiment V3", include_opinion_mining=True, ) @@ -93,32 +68,23 @@ async def _test_create_skillset(self, client): s5 = EntityLinkingSkill( name="skill5", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry(name="entities", target_name="entitiesS5") - ], + outputs=[OutputFieldMappingEntry(name="entities", target_name="entitiesS5")], minimum_precision=0.5, ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s1, s2, s3, s4, s5]), description="desc" - ) + skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s4, s5]), description="desc") result = await client.create_skillset(skillset) assert isinstance(result, SearchIndexerSkillset) assert result.name == name assert result.description == "desc" assert result.e_tag - assert len(result.skills) == 5 + assert len(result.skills) == 4 assert isinstance(result.skills[0], EntityRecognitionSkill) - assert result.skills[0].skill_version == EntityRecognitionSkillVersion.V1 assert isinstance(result.skills[1], EntityRecognitionSkill) - assert result.skills[1].skill_version == EntityRecognitionSkillVersion.V3 assert isinstance(result.skills[2], SentimentSkill) - assert result.skills[2].skill_version == SentimentSkillVersion.V1 - assert isinstance(result.skills[3], SentimentSkill) - assert result.skills[3].skill_version == SentimentSkillVersion.V3 - assert isinstance(result.skills[4], EntityLinkingSkill) - assert result.skills[4].minimum_precision == 0.5 + assert isinstance(result.skills[3], EntityLinkingSkill) + assert result.skills[3].minimum_precision == 0.5 assert len(await client.get_skillsets()) == 1 await client.reset_skills(result, [x.name for x in result.skills]) @@ -127,15 +93,9 @@ async def _test_get_skillset(self, client): name = "test-ss-get" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], - ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc" + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") await client.create_skillset(skillset) result = await client.get_skillset(name) assert isinstance(result, SearchIndexerSkillset) @@ -150,47 +110,29 @@ async def _test_get_skillsets(self, client): name2 = "test-ss-list-2" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name1, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name1, skills=list([s]), description="desc1") await client.create_skillset(skillset1) - skillset2 = SearchIndexerSkillset( - name=name2, skills=list([s]), description="desc2" - ) + skillset2 = SearchIndexerSkillset(name=name2, skills=list([s]), description="desc2") await client.create_skillset(skillset2) result = await client.get_skillsets() assert isinstance(result, list) assert all(isinstance(x, SearchIndexerSkillset) for x in result) - assert set(x.name for x in result).intersection([name1, name2]) == set( - [name1, name2] - ) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) async def _test_create_or_update_skillset(self, client): name = "test-ss-create-or-update" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") await client.create_or_update_skillset(skillset1) expected_count = len(await client.get_skillsets()) - skillset2 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc2" - ) + skillset2 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc2") await client.create_or_update_skillset(skillset2) assert len(await client.get_skillsets()) == expected_count @@ -203,21 +145,13 @@ async def _test_create_or_update_skillset_inplace(self, client): name = "test-ss-create-or-update-inplace" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") ss = await client.create_or_update_skillset(skillset1) expected_count = len(await client.get_skillsets()) - skillset2 = SearchIndexerSkillset( - name=name, skills=[s], description="desc2", skillset=ss - ) + skillset2 = SearchIndexerSkillset(name=name, skills=[s], description="desc2", skillset=ss) await client.create_or_update_skillset(skillset2) assert len(await client.get_skillsets()) == expected_count @@ -230,52 +164,34 @@ async def _test_create_or_update_skillset_if_unchanged(self, client): name = "test-ss-create-or-update-unchanged" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") ss = await client.create_or_update_skillset(skillset1) ss.e_tag = "changed_etag" with pytest.raises(HttpResponseError): - await client.create_or_update_skillset( - ss, match_condition=MatchConditions.IfNotModified - ) + await client.create_or_update_skillset(ss, match_condition=MatchConditions.IfNotModified) async def _test_delete_skillset_if_unchanged(self, client): name = "test-ss-deleted-unchanged" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc" - ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") result = await client.create_skillset(skillset) etag = result.e_tag - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="updated" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="updated") updated = await client.create_or_update_skillset(skillset1) updated.e_tag = etag with pytest.raises(HttpResponseError): - await client.delete_skillset( - updated, match_condition=MatchConditions.IfNotModified - ) + await client.delete_skillset(updated, match_condition=MatchConditions.IfNotModified) async def _test_delete_skillset(self, client): result = await client.get_skillset_names() diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py index 044ff088f61d..41a92e92f91c 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py @@ -21,9 +21,7 @@ class TestSearchClientSynonymMaps(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy_async async def test_synonym_map(self, endpoint): - client = SearchIndexClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) async with client: await self._test_create_synonym_map(client) await self._test_delete_synonym_map(client) @@ -81,9 +79,7 @@ async def _test_delete_synonym_map_if_unchanged(self, client): result.e_tag = etag with pytest.raises(HttpResponseError): - await client.delete_synonym_map( - result, match_condition=MatchConditions.IfNotModified - ) + await client.delete_synonym_map(result, match_condition=MatchConditions.IfNotModified) await client.delete_synonym_map(name) async def _test_get_synonym_map(self, client): diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py index fc72833f6a34..31cc3aa6f6a5 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py @@ -28,48 +28,22 @@ class TestSearchIndexerClientTestAsync(AzureRecordedTestCase): async def test_search_indexers(self, endpoint, **kwargs): storage_cs = kwargs.get("search_storage_connection_string") container_name = kwargs.get("search_storage_container_name") - client = SearchIndexerClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) - index_client = SearchIndexClient( - endpoint, get_credential(is_async=True), retry_backoff_factor=60 - ) + client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + index_client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) async with client: async with index_client: - await self._test_create_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_delete_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_get_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_list_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_create_or_update_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_reset_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_run_indexer( - client, index_client, storage_cs, container_name - ) - await self._test_get_indexer_status( - client, index_client, storage_cs, container_name - ) - await self._test_create_or_update_indexer_if_unchanged( - client, index_client, storage_cs, container_name - ) - await self._test_delete_indexer_if_unchanged( - client, index_client, storage_cs, container_name - ) - - async def _prepare_indexer( - self, client, index_client, storage_cs, name, container_name - ): + await self._test_create_indexer(client, index_client, storage_cs, container_name) + await self._test_delete_indexer(client, index_client, storage_cs, container_name) + await self._test_get_indexer(client, index_client, storage_cs, container_name) + await self._test_list_indexer(client, index_client, storage_cs, container_name) + await self._test_create_or_update_indexer(client, index_client, storage_cs, container_name) + await self._test_reset_indexer(client, index_client, storage_cs, container_name) + await self._test_run_indexer(client, index_client, storage_cs, container_name) + await self._test_get_indexer_status(client, index_client, storage_cs, container_name) + await self._test_create_or_update_indexer_if_unchanged(client, index_client, storage_cs, container_name) + await self._test_delete_indexer_if_unchanged(client, index_client, storage_cs, container_name) + + async def _prepare_indexer(self, client, index_client, storage_cs, name, container_name): data_source_connection = SearchIndexerDataSourceConnection( name=f"{name}-ds", type="azureblob", @@ -78,34 +52,22 @@ async def _prepare_indexer( ) ds = await client.create_data_source_connection(data_source_connection) - fields = [ - {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False} - ] + fields = [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}] index = SearchIndex(name=f"{name}-hotels", fields=fields) ind = await index_client.create_index(index) - return SearchIndexer( - name=name, data_source_name=ds.name, target_index_name=ind.name - ) + return SearchIndexer(name=name, data_source_name=ds.name, target_index_name=ind.name) - async def _test_create_indexer( - self, client, index_client, storage_cs, container_name - ): + async def _test_create_indexer(self, client, index_client, storage_cs, container_name): name = "create" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) result = await client.create_indexer(indexer) assert result.name == name assert result.target_index_name == f"{name}-hotels" assert result.data_source_name == f"{name}-ds" - async def _test_delete_indexer( - self, client, index_client, storage_cs, container_name - ): + async def _test_delete_indexer(self, client, index_client, storage_cs, container_name): name = "delete" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) await client.create_indexer(indexer) expected = len(await client.get_indexers()) - 1 await client.delete_indexer(name) @@ -113,39 +75,25 @@ async def _test_delete_indexer( async def _test_get_indexer(self, client, index_client, storage_cs, container_name): name = "get" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) await client.create_indexer(indexer) result = await client.get_indexer(name) assert result.name == name - async def _test_list_indexer( - self, client, index_client, storage_cs, container_name - ): + async def _test_list_indexer(self, client, index_client, storage_cs, container_name): name1 = "list1" name2 = "list2" - indexer1 = await self._prepare_indexer( - client, index_client, storage_cs, name1, container_name - ) - indexer2 = await self._prepare_indexer( - client, index_client, storage_cs, name2, container_name - ) + indexer1 = await self._prepare_indexer(client, index_client, storage_cs, name1, container_name) + indexer2 = await self._prepare_indexer(client, index_client, storage_cs, name2, container_name) await client.create_indexer(indexer1) await client.create_indexer(indexer2) result = await client.get_indexers() assert isinstance(result, list) - assert set(x.name for x in result).intersection([name1, name2]) == set( - [name1, name2] - ) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) - async def _test_create_or_update_indexer( - self, client, index_client, storage_cs, container_name - ): + async def _test_create_or_update_indexer(self, client, index_client, storage_cs, container_name): name = "cou" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) await client.create_indexer(indexer) expected = len(await client.get_indexers()) indexer.description = "updated" @@ -155,13 +103,9 @@ async def _test_create_or_update_indexer( assert result.name == name assert result.description == "updated" - async def _test_reset_indexer( - self, client, index_client, storage_cs, container_name - ): + async def _test_reset_indexer(self, client, index_client, storage_cs, container_name): name = "reset" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) await client.create_indexer(indexer) await client.reset_indexer(name) assert (await client.get_indexer_status(name)).last_result.status.lower() in ( @@ -171,31 +115,21 @@ async def _test_reset_indexer( async def _test_run_indexer(self, client, index_client, storage_cs, container_name): name = "run" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) await client.create_indexer(indexer) await client.run_indexer(name) assert (await client.get_indexer_status(name)).status == "running" - async def _test_get_indexer_status( - self, client, index_client, storage_cs, container_name - ): + async def _test_get_indexer_status(self, client, index_client, storage_cs, container_name): name = "get-status" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) await client.create_indexer(indexer) status = await client.get_indexer_status(name) assert status.status is not None - async def _test_create_or_update_indexer_if_unchanged( - self, client, index_client, storage_cs, container_name - ): + async def _test_create_or_update_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): name = "couunch" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) created = await client.create_indexer(indexer) etag = created.e_tag @@ -204,17 +138,11 @@ async def _test_create_or_update_indexer_if_unchanged( indexer.e_tag = etag with pytest.raises(HttpResponseError): - await client.create_or_update_indexer( - indexer, match_condition=MatchConditions.IfNotModified - ) + await client.create_or_update_indexer(indexer, match_condition=MatchConditions.IfNotModified) - async def _test_delete_indexer_if_unchanged( - self, client, index_client, storage_cs, container_name - ): + async def _test_delete_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): name = "delunch" - indexer = await self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) result = await client.create_indexer(indexer) etag = result.e_tag @@ -223,6 +151,4 @@ async def _test_delete_indexer_if_unchanged( indexer.e_tag = etag with pytest.raises(HttpResponseError): - await client.delete_indexer( - indexer, match_condition=MatchConditions.IfNotModified - ) + await client.delete_indexer(indexer, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/conftest.py b/sdk/search/azure-search-documents/tests/conftest.py index 4bb3d4315025..0ecac854421a 100644 --- a/sdk/search/azure-search-documents/tests/conftest.py +++ b/sdk/search/azure-search-documents/tests/conftest.py @@ -30,9 +30,7 @@ def add_sanitizers(test_proxy): # Remove storage connection strings from recordings add_general_regex_sanitizer(value="AccountKey=FAKE;", regex=r"AccountKey=([^;]+);") # Remove storage account names from recordings - add_general_regex_sanitizer( - value="AccountName=fakestoragecs;", regex=r"AccountName=([^;]+);" - ) + add_general_regex_sanitizer(value="AccountName=fakestoragecs;", regex=r"AccountName=([^;]+);") # Remove the following sanitizers since certain fields are needed in tests and are non-sensitive: # - AZSDK3493: $..name remove_batch_sanitizers(["AZSDK3493"]) diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py b/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py index 78066af8e220..ccd2a6a595f6 100644 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py @@ -18,12 +18,8 @@ def __init__(self, arguments): service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") key = os.getenv("AZURE_SEARCH_API_KEY") - self.service_client = SyncClient( - service_endpoint, index_name, AzureKeyCredential(api_key) - ) - self.async_service_client = AsyncClient( - service_endpoint, index_name, AzureKeyCredential(api_key) - ) + self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) async def close(self): await self.async_service_client.close() @@ -42,23 +38,15 @@ def add_arguments(parser): def run_sync(self): if self.args.num_documents == -1: - results = len( - self.service_client.autocomplete(search_text="mot", suggester_name="sg") - ) + results = len(self.service_client.autocomplete(search_text="mot", suggester_name="sg")) else: results = len( - self.service_client.autocomplete( - search_text="mot", suggester_name="sg", top=self.args.num_documents - ) + self.service_client.autocomplete(search_text="mot", suggester_name="sg", top=self.args.num_documents) ) async def run_async(self): if self.args.num_documents == -1: - results = len( - await self.async_service_client.autocomplete( - search_text="mot", suggester_name="sg" - ) - ) + results = len(await self.async_service_client.autocomplete(search_text="mot", suggester_name="sg")) else: results = len( await self.async_service_client.autocomplete( diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py b/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py index 2620c7301cba..19fc00efec37 100644 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py @@ -19,12 +19,8 @@ def __init__(self, arguments): service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") key = os.getenv("AZURE_SEARCH_API_KEY") - self.service_client = SyncClient( - service_endpoint, index_name, AzureKeyCredential(api_key) - ) - self.async_service_client = AsyncClient( - service_endpoint, index_name, AzureKeyCredential(api_key) - ) + self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) @staticmethod def add_arguments(parser): @@ -48,19 +44,13 @@ def run_sync(self): if self.args.num_documents == -1: results = len(self.service_client.search(search_text="luxury")) else: - results = len( - self.service_client.search( - search_text="luxury", top=self.args.num_documents - ) - ) + results = len(self.service_client.search(search_text="luxury", top=self.args.num_documents)) async def run_async(self): if self.args.num_documents == -1: results = await self.async_service_client.search(search_text="luxury") else: - results = await self.async_service_client.search( - search_text="luxury", top=self.args.num_documents - ) + results = await self.async_service_client.search(search_text="luxury", top=self.args.num_documents) count = 0 async for result in results: count += count diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py b/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py index 8c4653baf5cd..d906ba271ef8 100644 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py @@ -18,12 +18,8 @@ def __init__(self, arguments): service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") key = os.getenv("AZURE_SEARCH_API_KEY") - self.service_client = SyncClient( - service_endpoint, index_name, AzureKeyCredential(api_key) - ) - self.async_service_client = AsyncClient( - service_endpoint, index_name, AzureKeyCredential(api_key) - ) + self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) async def close(self): await self.async_service_client.close() @@ -42,23 +38,15 @@ def add_arguments(parser): def run_sync(self): if self.args.num_documents == -1: - results = len( - self.service_client.suggest(search_text="mot", suggester_name="sg") - ) + results = len(self.service_client.suggest(search_text="mot", suggester_name="sg")) else: results = len( - self.service_client.suggest( - search_text="mot", suggester_name="sg", top=self.args.num_documents - ) + self.service_client.suggest(search_text="mot", suggester_name="sg", top=self.args.num_documents) ) async def run_async(self): if self.args.num_documents == -1: - results = len( - await self.async_service_client.suggest( - search_text="mot", suggester_name="sg" - ) - ) + results = len(await self.async_service_client.suggest(search_text="mot", suggester_name="sg")) else: results = len( await self.async_service_client.suggest( diff --git a/sdk/search/azure-search-documents/tests/search_service_preparer.py b/sdk/search/azure-search-documents/tests/search_service_preparer.py index eb66cb0f28af..0084a88e480f 100644 --- a/sdk/search/azure-search-documents/tests/search_service_preparer.py +++ b/sdk/search/azure-search-documents/tests/search_service_preparer.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -51,16 +52,34 @@ def _clean_up_indexes(endpoint, cred): client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) + # wipe knowledge sources first (they reference indexes) + try: + for ks in client.list_knowledge_sources(): + client.delete_knowledge_source(ks.name) + except HttpResponseError: + pass + + # wipe knowledge bases + try: + for kb in client.list_knowledge_bases(): + client.delete_knowledge_base(kb.name) + except HttpResponseError: + pass + # wipe the synonym maps which seem to survive the index for map in client.get_synonym_maps(): client.delete_synonym_map(map.name) + # wipe out any existing aliases for alias in client.list_aliases(): client.delete_alias(alias) # wipe any existing indexes for index in client.list_indexes(): - client.delete_index(index) + try: + client.delete_index(index) + except HttpResponseError: + pass def _clean_up_indexers(endpoint, cred): @@ -75,10 +94,7 @@ def _clean_up_indexers(endpoint, cred): for skillset in client.get_skillset_names(): client.delete_skillset(skillset) except HttpResponseError as ex: - if ( - "skillset related operations are not enabled in this region" - in ex.message.lower() - ): + if "skillset related operations are not enabled in this region" in ex.message.lower(): pass else: raise @@ -87,7 +103,7 @@ def _clean_up_indexers(endpoint, cred): def _set_up_index(service_name, endpoint, cred, schema, index_batch): from azure.search.documents import SearchClient from azure.search.documents.indexes.models import SearchIndex - from azure.search.documents._generated.models import IndexBatch + from azure.search.documents import IndexDocumentsBatch from azure.search.documents.indexes import SearchIndexClient schema = _load_schema(schema) @@ -95,13 +111,14 @@ def _set_up_index(service_name, endpoint, cred, schema, index_batch): if schema: index_json = json.loads(schema) index_name = index_json["name"] - index = SearchIndex.from_dict(index_json) + index = SearchIndex(index_json) index_client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) index_create = index_client.create_index(index) # optionally load data into the index if index_batch and schema: - batch = IndexBatch.deserialize(index_batch) + batch = IndexDocumentsBatch() + batch.add_upload_actions(index_batch.get("value", [])) client = SearchClient(endpoint, index_name, cred) results = client.index_documents(batch) if not all(result.succeeded for result in results): @@ -132,9 +149,8 @@ def _trim_kwargs_from_test_function(fn, kwargs): def search_decorator(*, schema, index_batch): def decorator(func): - def wrapper(*args, **kwargs): - # set up hotels search index - test = args[0] + def _prepare_test(test, kwargs): + """Common setup logic for both sync and async tests.""" endpoint = kwargs.get("search_service_endpoint") service_name = kwargs.get("search_service_name") if test.is_live: @@ -153,9 +169,25 @@ def wrapper(*args, **kwargs): trimmed_kwargs = {k: v for k, v in kwargs.items()} _trim_kwargs_from_test_function(func, trimmed_kwargs) + return trimmed_kwargs + + if inspect.iscoroutinefunction(func): + + @functools.wraps(func) + async def async_wrapper(*args, **kwargs): + test = args[0] + trimmed_kwargs = _prepare_test(test, kwargs) + return await func(*args, **trimmed_kwargs) + + return async_wrapper + else: - return func(*args, **trimmed_kwargs) + @functools.wraps(func) + def wrapper(*args, **kwargs): + test = args[0] + trimmed_kwargs = _prepare_test(test, kwargs) + return func(*args, **trimmed_kwargs) - return wrapper + return wrapper return decorator diff --git a/sdk/search/azure-search-documents/tests/test_buffered_sender.py b/sdk/search/azure-search-documents/tests/test_buffered_sender.py index 48819e0ae458..3fcb72cb8c33 100644 --- a/sdk/search/azure-search-documents/tests/test_buffered_sender.py +++ b/sdk/search/azure-search-documents/tests/test_buffered_sender.py @@ -16,23 +16,19 @@ class TestSearchBatchingClient: def test_search_indexing_buffered_sender_kwargs(self): - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, window=100 - ) as client: + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, window=100) as client: assert client._batch_action_count == 512 assert client._max_retries_per_action == 3 assert client._auto_flush_interval == 60 assert client._auto_flush def test_batch_queue(self): - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False - ) as client: - assert client._index_documents_batch - client.upload_documents(["upload1"]) - client.delete_documents(["delete1", "delete2"]) - client.merge_documents(["merge1", "merge2", "merge3"]) - client.merge_or_upload_documents(["merge_or_upload1"]) + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + assert not (client._index_documents_batch is None) + client.upload_documents([{"upload1": "doc"}]) + client.delete_documents([{"delete1": "doc"}, {"delete2": "doc"}]) + client.merge_documents([{"merge1": "doc"}, {"merge2": "doc"}, {"merge3": "doc"}]) + client.merge_or_upload_documents([{"merge_or_upload1": "doc"}]) assert len(client.actions) == 7 actions = client._index_documents_batch.dequeue_actions() assert len(client.actions) == 0 @@ -44,26 +40,18 @@ def test_batch_queue(self): client._index_documents_batch.enqueue_actions(action) assert len(client.actions) == 7 - @mock.patch( - "azure.search.documents._search_indexing_buffered_sender.SearchIndexingBufferedSender._process_if_needed" - ) + @mock.patch("azure.search.documents._patch.SearchIndexingBufferedSender._process_if_needed") def test_process_if_needed(self, mock_process_if_needed): - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL - ) as client: - client.upload_documents(["upload1"]) - client.delete_documents(["delete1", "delete2"]) + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL) as client: + client.upload_documents([{"upload1": "doc"}]) + client.delete_documents([{"delete1": "doc"}, {"delete2": "doc"}]) assert mock_process_if_needed.called - @mock.patch( - "azure.search.documents._search_indexing_buffered_sender.SearchIndexingBufferedSender._cleanup" - ) + @mock.patch("azure.search.documents._patch.SearchIndexingBufferedSender._cleanup") def test_context_manager(self, mock_cleanup): - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False - ) as client: - client.upload_documents(["upload1"]) - client.delete_documents(["delete1", "delete2"]) + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + client.upload_documents([{"upload1": "doc"}]) + client.delete_documents([{"delete1": "doc"}, {"delete2": "doc"}]) assert mock_cleanup.called def test_flush(self): @@ -79,9 +67,7 @@ def test_flush(self): "_index_documents_actions", side_effect=HttpResponseError("Error"), ): - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False - ) as client: + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: client._index_key = "hotelId" client.upload_documents([DOCUMENT]) client.flush() @@ -92,17 +78,16 @@ def test_callback_new(self): with SearchIndexingBufferedSender( "endpoint", "index name", CREDENTIAL, auto_flush=False, on_new=on_new ) as client: - client.upload_documents(["upload1"]) + client.upload_documents([{"upload1": "doc"}]) assert on_new.called def test_callback_error(self): def mock_fail_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 400 result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 return [result] on_error = mock.Mock() @@ -111,7 +96,7 @@ def mock_fail_index_documents(actions, timeout=86400): ) as client: client._index_documents_actions = mock_fail_index_documents client._index_key = "id" - client.upload_documents({"id": 0}) + client.upload_documents([{"id": 0}]) client.flush() assert on_error.called @@ -121,10 +106,9 @@ def mock_fail_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 400 result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 time.sleep(1) return [result] @@ -143,7 +127,7 @@ def test_callback_progress(self): def mock_successful_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 200 result.succeeded = True return [result] @@ -160,7 +144,7 @@ def mock_successful_index_documents(actions, timeout=86400): ) as client: client._index_documents_actions = mock_successful_index_documents client._index_key = "id" - client.upload_documents({"id": 0}) + client.upload_documents([{"id": 0}]) client.flush() assert on_progress.called assert on_remove.called diff --git a/sdk/search/azure-search-documents/tests/test_index_documents_batch.py b/sdk/search/azure-search-documents/tests/test_index_documents_batch.py index 5de862828f1f..899fa96b4f57 100644 --- a/sdk/search/azure-search-documents/tests/test_index_documents_batch.py +++ b/sdk/search/azure-search-documents/tests/test_index_documents_batch.py @@ -6,7 +6,6 @@ import pytest from azure.search.documents.models import IndexAction - from azure.search.documents import IndexDocumentsBatch METHOD_NAMES = [ @@ -20,52 +19,23 @@ class TestIndexDocumentsBatch: - def test_init(self): - batch = IndexDocumentsBatch() - assert batch.actions == [] - - def test_repr(self): - batch = IndexDocumentsBatch() - assert repr(batch) == "" - - batch._actions = [1, 2, 3] - assert repr(batch) == "" - - # a strict length test here would require constructing an actions list - # with a length of ~10**24, so settle for this simple sanity check on - # an extreme case. - batch_actions = list(range(2000)) - assert len(repr(batch)) <= 1024 - - def test_actions_returns_list_copy(self): - batch = IndexDocumentsBatch() - batch.actions.extend([1, 2, 3]) - assert type(batch.actions) is list - assert batch.actions == [] - assert batch.actions is not batch._actions - @pytest.mark.parametrize("method_name", METHOD_NAMES) def test_add_method(self, method_name): batch = IndexDocumentsBatch() method = getattr(batch, method_name) - method("doc1") + method([{"doc1": "doc"}]) assert len(batch.actions) == 1 - method("doc2", "doc3") + method([{"doc2": "doc"}, {"doc3": "doc"}]) assert len(batch.actions) == 3 - method(["doc4", "doc5"]) + method([{"doc4": "doc"}, {"doc5": "doc"}]) assert len(batch.actions) == 5 - method(("doc6", "doc7")) + method([{"doc6": "doc"}, {"doc7": "doc"}]) assert len(batch.actions) == 7 - assert all( - action.action_type == METHOD_MAP[method_name] for action in batch.actions - ) + assert all(action.action_type == METHOD_MAP[method_name] for action in batch.actions) assert all(type(action) == IndexAction for action in batch.actions) - - expected = ["doc{}".format(i) for i in range(1, 8)] - assert [action.additional_properties for action in batch.actions] == expected diff --git a/sdk/search/azure-search-documents/tests/test_index_field_helpers.py b/sdk/search/azure-search-documents/tests/test_index_field_helpers.py index 622e4fdde4f0..0dee28cc7d4c 100644 --- a/sdk/search/azure-search-documents/tests/test_index_field_helpers.py +++ b/sdk/search/azure-search-documents/tests/test_index_field_helpers.py @@ -12,14 +12,14 @@ def test_edm_contents(): - assert SearchFieldDataType.String == "Edm.String" - assert SearchFieldDataType.Int32 == "Edm.Int32" - assert SearchFieldDataType.Int64 == "Edm.Int64" - assert SearchFieldDataType.Double == "Edm.Double" - assert SearchFieldDataType.Boolean == "Edm.Boolean" - assert SearchFieldDataType.DateTimeOffset == "Edm.DateTimeOffset" - assert SearchFieldDataType.GeographyPoint == "Edm.GeographyPoint" - assert SearchFieldDataType.ComplexType == "Edm.ComplexType" + assert SearchFieldDataType.STRING == "Edm.String" + assert SearchFieldDataType.INT32 == "Edm.Int32" + assert SearchFieldDataType.INT64 == "Edm.Int64" + assert SearchFieldDataType.DOUBLE == "Edm.Double" + assert SearchFieldDataType.BOOLEAN == "Edm.Boolean" + assert SearchFieldDataType.DATE_TIME_OFFSET == "Edm.DateTimeOffset" + assert SearchFieldDataType.GEOGRAPHY_POINT == "Edm.GeographyPoint" + assert SearchFieldDataType.COMPLEX == "Edm.ComplexType" assert SearchFieldDataType.Collection("foo") == "Collection(foo)" @@ -27,7 +27,7 @@ class TestComplexField: def test_single(self): fld = ComplexField(name="foo", fields=[]) assert fld.name == "foo" - assert fld.type == SearchFieldDataType.ComplexType + assert fld.type == SearchFieldDataType.COMPLEX assert fld.sortable is None assert fld.facetable is None @@ -38,15 +38,10 @@ def test_single(self): assert fld.index_analyzer_name is None assert fld.synonym_map_names is None - generated_field = fld._to_generated() - assert generated_field.retrievable is None - def test_collection(self): fld = ComplexField(name="foo", fields=[], collection=True) assert fld.name == "foo" - assert fld.type == SearchFieldDataType.Collection( - SearchFieldDataType.ComplexType - ) + assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.COMPLEX) assert fld.sortable is None assert fld.facetable is None @@ -60,10 +55,10 @@ def test_collection(self): class TestSimplexField: def test_defaults(self): - fld = SimpleField(name="foo", type=SearchFieldDataType.Double) + fld = SimpleField(name="foo", type=SearchFieldDataType.DOUBLE) assert fld.name == "foo" - assert fld.type == SearchFieldDataType.Double - assert fld.hidden == False + assert fld.type == SearchFieldDataType.DOUBLE + assert fld.retrievable == True assert fld.sortable == False assert fld.facetable == False assert fld.searchable == False @@ -79,8 +74,8 @@ class TestSearchableField: def test_defaults(self): fld = SearchableField(name="foo", collection=True) assert fld.name == "foo" - assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.String) - assert fld.hidden == False + assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.STRING) + assert fld.retrievable == True assert fld.sortable == False assert fld.facetable == False assert fld.searchable == True diff --git a/sdk/search/azure-search-documents/tests/test_knowledge_base_configuration_live.py b/sdk/search/azure-search-documents/tests/test_knowledge_base_configuration_live.py index 5691bc1fd9eb..6f521e8e3ef4 100644 --- a/sdk/search/azure-search-documents/tests/test_knowledge_base_configuration_live.py +++ b/sdk/search/azure-search-documents/tests/test_knowledge_base_configuration_live.py @@ -14,13 +14,21 @@ from azure.search.documents.indexes import SearchIndexClient from azure.search.documents.indexes.models import ( KnowledgeBase, + KnowledgeSourceReference, + SearchField, + SearchFieldDataType, + SearchIndex, + SearchIndexKnowledgeSource, + SearchIndexKnowledgeSourceParameters, + SemanticConfiguration, + SemanticField, + SemanticPrioritizedFields, + SemanticSearch, +) + +from azure.search.documents.knowledgebases.models import ( KnowledgeRetrievalMediumReasoningEffort, KnowledgeRetrievalMinimalReasoningEffort, - KnowledgeSourceReference, - WebKnowledgeSource, - WebKnowledgeSourceDomain, - WebKnowledgeSourceDomains, - WebKnowledgeSourceParameters, ) from search_service_preparer import SearchEnvVarPreparer, search_decorator @@ -30,12 +38,14 @@ class _TestContext: def __init__( self, index_client: SearchIndexClient, + index_name: str, source_name: str, - created_source: WebKnowledgeSource, + created_source: SearchIndexKnowledgeSource, base_name: str, created_base: KnowledgeBase, ) -> None: self.index_client = index_client + self.index_name = index_name self.source_name = source_name self.created_source = created_source self.base_name = base_name @@ -47,21 +57,8 @@ def _create_context(self, endpoint: str) -> "_TestContext": credential = get_credential() index_client = SearchIndexClient(endpoint, credential, retry_backoff_factor=60) + index_name = self.get_resource_name("cfgidx") source_name = self.get_resource_name("cfgks") - create_source = WebKnowledgeSource( - name=source_name, - description="configuration source", - web_parameters=WebKnowledgeSourceParameters( - domains=WebKnowledgeSourceDomains( - allowed_domains=[ - WebKnowledgeSourceDomain( - address="https://learn.microsoft.com", - include_subpages=True, - ) - ] - ) - ), - ) base_name = self.get_resource_name("cfgkb") # best-effort cleanup in case a previous run failed before teardown @@ -73,7 +70,38 @@ def _create_context(self, endpoint: str) -> "_TestContext": index_client.delete_knowledge_source(source_name) except HttpResponseError: pass + try: + index_client.delete_index(index_name) + except HttpResponseError: + pass + # Create a search index with semantic configuration (required for SearchIndexKnowledgeSource) + index = SearchIndex( + name=index_name, + fields=[ + SearchField(name="id", type=SearchFieldDataType.String, key=True), + SearchField(name="content", type=SearchFieldDataType.String, searchable=True), + ], + semantic_search=SemanticSearch( + default_configuration_name="default", + configurations=[ + SemanticConfiguration( + name="default", + prioritized_fields=SemanticPrioritizedFields( + content_fields=[SemanticField(field_name="content")] + ), + ) + ], + ), + ) + index_client.create_index(index) + + # Create knowledge source pointing to the index + create_source = SearchIndexKnowledgeSource( + name=source_name, + description="configuration source", + search_index_parameters=SearchIndexKnowledgeSourceParameters(search_index_name=index_name), + ) created_source = index_client.create_knowledge_source(create_source) create_base = KnowledgeBase( @@ -87,16 +115,18 @@ def _create_context(self, endpoint: str) -> "_TestContext": try: created_base = index_client.create_knowledge_base(create_base) except HttpResponseError: - # creation failed; remove the knowledge source created above before raising + # creation failed; remove the knowledge source and index before raising try: index_client.delete_knowledge_source(created_source) except HttpResponseError: pass + try: + index_client.delete_index(index_name) + except HttpResponseError: + pass raise - return _TestContext( - index_client, source_name, created_source, base_name, created_base - ) + return _TestContext(index_client, index_name, source_name, created_source, base_name, created_base) def _cleanup(self, ctx: "_TestContext") -> None: try: @@ -114,6 +144,10 @@ def _cleanup(self, ctx: "_TestContext") -> None: ) except HttpResponseError: pass + try: + ctx.index_client.delete_index(ctx.index_name) + except HttpResponseError: + pass finally: ctx.index_client.close() diff --git a/sdk/search/azure-search-documents/tests/test_knowledge_base_live.py b/sdk/search/azure-search-documents/tests/test_knowledge_base_live.py index 186ab6d2d0d2..517b3b6ff031 100644 --- a/sdk/search/azure-search-documents/tests/test_knowledge_base_live.py +++ b/sdk/search/azure-search-documents/tests/test_knowledge_base_live.py @@ -15,12 +15,17 @@ from azure.search.documents.indexes.models import ( KnowledgeBase, KnowledgeSourceReference, + SearchField, + SearchFieldDataType, + SearchIndex, + SearchIndexKnowledgeSource, + SearchIndexKnowledgeSourceParameters, SearchServiceStatistics, + SemanticConfiguration, + SemanticField, + SemanticPrioritizedFields, + SemanticSearch, ServiceIndexersRuntime, - WebKnowledgeSource, - WebKnowledgeSourceDomain, - WebKnowledgeSourceDomains, - WebKnowledgeSourceParameters, ) from search_service_preparer import SearchEnvVarPreparer, search_decorator @@ -30,12 +35,14 @@ class _TestContext: def __init__( self, index_client: SearchIndexClient, + index_name: str, source_name: str, - created_source: WebKnowledgeSource, + created_source: SearchIndexKnowledgeSource, base_name: str, created_base: KnowledgeBase, ) -> None: self.index_client = index_client + self.index_name = index_name self.source_name = source_name self.created_source = created_source self.base_name = base_name @@ -47,21 +54,36 @@ def _create_context(self, endpoint: str) -> "_TestContext": credential = get_credential() index_client = SearchIndexClient(endpoint, credential, retry_backoff_factor=60) + index_name = self.get_resource_name("kbidx") source_name = self.get_resource_name("ksrc") base_name = self.get_resource_name("kb") - create_source = WebKnowledgeSource( + + # Create a search index with semantic configuration (required for SearchIndexKnowledgeSource) + index = SearchIndex( + name=index_name, + fields=[ + SearchField(name="id", type=SearchFieldDataType.String, key=True), + SearchField(name="content", type=SearchFieldDataType.String, searchable=True), + ], + semantic_search=SemanticSearch( + default_configuration_name="default", + configurations=[ + SemanticConfiguration( + name="default", + prioritized_fields=SemanticPrioritizedFields( + content_fields=[SemanticField(field_name="content")] + ), + ) + ], + ), + ) + index_client.create_index(index) + + # Create knowledge source pointing to the index + create_source = SearchIndexKnowledgeSource( name=source_name, description="knowledge base dependent source", - web_parameters=WebKnowledgeSourceParameters( - domains=WebKnowledgeSourceDomains( - allowed_domains=[ - WebKnowledgeSourceDomain( - address="https://learn.microsoft.com", - include_subpages=True, - ) - ] - ) - ), + search_index_parameters=SearchIndexKnowledgeSourceParameters(search_index_name=index_name), ) created_source = index_client.create_knowledge_source(create_source) @@ -71,9 +93,7 @@ def _create_context(self, endpoint: str) -> "_TestContext": knowledge_sources=[KnowledgeSourceReference(name=source_name)], ) created_base = index_client.create_knowledge_base(create_base) - return _TestContext( - index_client, source_name, created_source, base_name, created_base - ) + return _TestContext(index_client, index_name, source_name, created_source, base_name, created_base) def _cleanup(self, ctx: "_TestContext") -> None: try: @@ -91,6 +111,10 @@ def _cleanup(self, ctx: "_TestContext") -> None: ) except HttpResponseError: pass + try: + ctx.index_client.delete_index(ctx.index_name) + except HttpResponseError: + pass finally: ctx.index_client.close() @@ -155,10 +179,7 @@ def test_knowledge_base_read(self, endpoint: str) -> None: listed = list(ctx.index_client.list_knowledge_bases()) assert fetched.name == ctx.base_name - assert ( - fetched.knowledge_sources - and fetched.knowledge_sources[0].name == ctx.source_name - ) + assert fetched.knowledge_sources and fetched.knowledge_sources[0].name == ctx.source_name assert any(item.name == ctx.base_name for item in listed) finally: self._cleanup(ctx) @@ -211,9 +232,7 @@ def test_service_indexer_runtime_statistics(self, endpoint: str) -> None: snapshots = self._poll_status_snapshots(ctx) assert snapshots, "Expected at least one status snapshot" - service_stats = ( - ctx.index_client._client.get_service_statistics() - ) # pylint:disable=protected-access + service_stats = ctx.index_client.get_service_statistics() # pylint:disable=protected-access assert isinstance(service_stats, SearchServiceStatistics) runtime = service_stats.indexers_runtime diff --git a/sdk/search/azure-search-documents/tests/test_models.py b/sdk/search/azure-search-documents/tests/test_models.py deleted file mode 100644 index cc46c17e33ca..000000000000 --- a/sdk/search/azure-search-documents/tests/test_models.py +++ /dev/null @@ -1,194 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from datetime import timedelta - -from azure.search.documents.indexes.models import ( - ContentUnderstandingSkill, - ContentUnderstandingSkillChunkingProperties, - ContentUnderstandingSkillExtractionOptions, - FreshnessScoringFunction, - FreshnessScoringParameters, - InputFieldMappingEntry, - OutputFieldMappingEntry, - ScoringFunctionAggregation, - ScoringProfile, - SearchField, - SearchIndex, - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, - SearchResourceEncryptionKey, - SearchIndexerSkillset, - ShaperSkill, - SearchIndexer, -) - - -def test_encryption_key_serialization(): - from azure.search.documents.indexes._generated.models import ( - SearchResourceEncryptionKey as SearchResourceEncryptionKeyGen, - ) - - container = SearchIndexerDataContainer(name="container_name") - encryption_key = SearchResourceEncryptionKey( - key_name="key", - key_version="key_version", - vault_uri="vault_uri", - ) - data_source_connection = SearchIndexerDataSourceConnection( - name="datasource-name", - type="azureblob", - connection_string="connection_string", - container=container, - encryption_key=encryption_key, - ) - packed_data_source = data_source_connection._to_generated() - assert isinstance(packed_data_source.encryption_key, SearchResourceEncryptionKeyGen) - - search_indexer = SearchIndexer( - name="indexer-name", - data_source_name="datasource-name", - target_index_name="target-index-name", - encryption_key=encryption_key, - ) - packed_search_indexer = search_indexer._to_generated() - assert isinstance( - packed_search_indexer.encryption_key, SearchResourceEncryptionKeyGen - ) - - -def test_search_index_purview_enabled_round_trip(): - fields = [SearchField(name="id", type="Edm.String", key=True)] - index = SearchIndex( - name="idx", - fields=fields, - purview_enabled=True, - permission_filter_option="enabled", - ) - - generated = index._to_generated() - assert generated.purview_enabled is True - - round_tripped = SearchIndex._from_generated(generated) - assert round_tripped is not None - assert round_tripped.purview_enabled is True - - -def test_content_understanding_skill_round_trip(): - skill = ContentUnderstandingSkill( - name="content-skill", - description="extract structured signals", - context="/document", - inputs=[ - InputFieldMappingEntry(name="text", source="/document/content"), - ], - outputs=[ - OutputFieldMappingEntry(name="structured", target_name="structuredContent"), - ], - extraction_options=[ - ContentUnderstandingSkillExtractionOptions.IMAGES, - ContentUnderstandingSkillExtractionOptions.LOCATION_METADATA, - ], - chunking_properties=ContentUnderstandingSkillChunkingProperties( - maximum_length=600, - overlap_length=50, - ), - ) - skillset = SearchIndexerSkillset(name="cu-skillset", skills=[skill]) - - generated_skillset = skillset._to_generated() - assert isinstance(generated_skillset.skills[0], ContentUnderstandingSkill) - generated_skill = generated_skillset.skills[0] - assert generated_skill.chunking_properties.maximum_length == 600 - assert generated_skill.chunking_properties.overlap_length == 50 - assert generated_skill.extraction_options == ["images", "locationMetadata"] - - generated_skill.description = "updated description" - generated_skill.chunking_properties.maximum_length = 700 - - round_tripped = SearchIndexerSkillset._from_generated(generated_skillset) - assert round_tripped is not None - round_trip_skill = round_tripped.skills[0] - assert isinstance(round_trip_skill, ContentUnderstandingSkill) - assert round_trip_skill.description == "updated description" - assert round_trip_skill.chunking_properties.maximum_length == 700 - assert round_trip_skill.extraction_options == ["images", "locationMetadata"] - - -def test_content_understanding_skill_payload_shape(): - skill = ContentUnderstandingSkill( - name="content-skill", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="structured")], - chunking_properties=ContentUnderstandingSkillChunkingProperties(), - ) - payload = SearchIndexerSkillset(name="cu-skillset", skills=[skill]).serialize() - - skill_payload = payload["skills"][0] - assert ( - skill_payload["@odata.type"] - == "#Microsoft.Skills.Util.ContentUnderstandingSkill" - ) - assert skill_payload["chunkingProperties"]["unit"] == "characters" - - -def test_search_index_scoring_profile_product_round_trip(): - fields = [ - SearchField(name="id", type="Edm.String", key=True), - SearchField(name="lastUpdated", type="Edm.DateTimeOffset", filterable=True), - ] - scoring_profile = ScoringProfile( - name="product-score", - function_aggregation=ScoringFunctionAggregation.PRODUCT, - functions=[ - FreshnessScoringFunction( - field_name="lastUpdated", - boost=2.5, - parameters=FreshnessScoringParameters( - boosting_duration=timedelta(days=7) - ), - ) - ], - ) - index = SearchIndex( - name="scoring-index", fields=fields, scoring_profiles=[scoring_profile] - ) - - generated = index._to_generated() - assert generated.scoring_profiles[0].function_aggregation == "product" - - generated.scoring_profiles[0].function_aggregation = "sum" - - round_tripped = SearchIndex._from_generated(generated) - assert round_tripped is not None - assert round_tripped.scoring_profiles[0].function_aggregation == "sum" - - -def test_search_index_scoring_profile_product_payload(): - fields = [ - SearchField(name="id", type="Edm.String", key=True), - SearchField(name="lastUpdated", type="Edm.DateTimeOffset", filterable=True), - ] - scoring_profile = ScoringProfile( - name="product-score", - function_aggregation=ScoringFunctionAggregation.PRODUCT, - functions=[ - FreshnessScoringFunction( - field_name="lastUpdated", - boost=2.0, - parameters=FreshnessScoringParameters( - boosting_duration=timedelta(days=3) - ), - ) - ], - ) - payload = SearchIndex( - name="scoring-index", - fields=fields, - scoring_profiles=[scoring_profile], - ).serialize() - - scoring_payload = payload["scoringProfiles"][0] - assert scoring_payload["functionAggregation"] == "product" diff --git a/sdk/search/azure-search-documents/tests/test_queries.py b/sdk/search/azure-search-documents/tests/test_queries.py deleted file mode 100644 index baad05231809..000000000000 --- a/sdk/search/azure-search-documents/tests/test_queries.py +++ /dev/null @@ -1,167 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import pytest -from unittest import mock - -from azure.search.documents._generated.models import ( - AutocompleteRequest, - SearchRequest, - SuggestRequest, -) - -from azure.search.documents._queries import AutocompleteQuery, SuggestQuery, SearchQuery - - -class TestAutocompleteQuery: - def test_init(self): - query = AutocompleteQuery(search_text="text", suggester_name="sg") - assert type(query.request) is AutocompleteRequest - assert query.request.filter is None - - @mock.patch("azure.search.documents._queries.AutocompleteQuery._request_type") - def test_kwargs_forwarded(self, mock_request): - mock_request.return_value = None - AutocompleteQuery(foo=10, bar=20) - assert mock_request.called - assert mock_request.call_args[0] == () - assert mock_request.call_args[1] == {"foo": 10, "bar": 20} - - def test_repr(self): - query = AutocompleteQuery(search_text="foo bar", suggester_name="sg") - assert repr(query) == "" - - query = AutocompleteQuery(search_text="aaaaabbbbb" * 200, suggester_name="sg") - assert len(repr(query)) == 1024 - - def test_filter(self): - query = AutocompleteQuery(search_text="text", suggester_name="sg") - assert query.request.filter is None - query.filter("expr0") - assert query.request.filter == "expr0" - - query = AutocompleteQuery( - search_text="text", suggester_name="sg", filter="expr1" - ) - assert query.request.filter == "expr1" - query.filter("expr2") - assert query.request.filter == "expr2" - - -class TestSearchQuery: - def test_init(self): - query = SearchQuery() - assert type(query.request) is SearchRequest - assert query.request.filter is None - assert query.request.order_by is None - assert query.request.select is None - - @mock.patch("azure.search.documents._queries.SearchQuery._request_type") - def test_kwargs_forwarded(self, mock_request): - mock_request.return_value = None - SearchQuery(foo=10, bar=20) - assert mock_request.called - assert mock_request.call_args[0] == () - assert mock_request.call_args[1] == {"foo": 10, "bar": 20} - - def test_repr(self): - query = SearchQuery() - assert repr(query) == "" - - query = SearchQuery(search_text="foo bar", suggester_name="sg") - assert repr(query) == "" - - query = SearchQuery(search_text="aaaaabbbbb" * 200) - assert len(repr(query)) == 1024 - - def test_filter(self): - query = SearchQuery() - assert query.request.filter is None - query.filter("expr0") - assert query.request.filter == "expr0" - - query = SearchQuery(filter="expr0") - assert query.request.filter == "expr0" - query.filter("expr1") - assert query.request.filter == "expr1" - - def test_order_by(self): - query = SearchQuery() - assert query.request.order_by is None - query.order_by("f0") - assert query.request.order_by == "f0" - query.order_by("f1,f2") - assert query.request.order_by == "f1,f2" - query.order_by("f3", "f4") - assert query.request.order_by == "f3,f4" - - query = SearchQuery(order_by="f0") - assert query.request.order_by == "f0" - query.order_by("f1,f2") - assert query.request.order_by == "f1,f2" - query.order_by("f3", "f4") - assert query.request.order_by == "f3,f4" - - with pytest.raises(ValueError) as e: - query.order_by() - assert str(e) == "At least one field must be provided" - - def test_select(self): - query = SearchQuery() - assert query.request.select is None - query.select("f0") - assert query.request.select == "f0" - query.select("f1,f2") - assert query.request.select == "f1,f2" - query.select("f3", "f4") - assert query.request.select == "f3,f4" - - query = SearchQuery(select="f0") - assert query.request.select == "f0" - query.select("f1,f2") - assert query.request.select == "f1,f2" - query.select("f3", "f4") - assert query.request.select == "f3,f4" - - str = ["f1", "f2"] - query.select(str) - assert query.request.select == "f1,f2" - - with pytest.raises(ValueError) as e: - query.select() - assert str(e) == "At least one field must be provided" - - -class TestSuggestQuery: - def test_init(self): - query = SuggestQuery(search_text="text", suggester_name="sg") - assert type(query.request) is SuggestRequest - assert query.request.filter is None - - @mock.patch("azure.search.documents._queries.SuggestQuery._request_type") - def test_kwargs_forwarded(self, mock_request): - mock_request.return_value = None - SuggestQuery(foo=10, bar=20) - assert mock_request.called - assert mock_request.call_args[0] == () - assert mock_request.call_args[1] == {"foo": 10, "bar": 20} - - def test_repr(self): - query = SuggestQuery(search_text="foo bar", suggester_name="sg") - assert repr(query) == "" - - query = SuggestQuery(search_text="aaaaabbbbb" * 200, suggester_name="sg") - assert len(repr(query)) == 1024 - - def test_filter(self): - query = SuggestQuery(search_text="text", suggester_name="sg") - assert query.request.filter is None - query.filter("expr0") - assert query.request.filter == "expr0" - - query = SuggestQuery(search_text="text", suggester_name="sg", filter="expr1") - assert query.request.filter == "expr1" - query.filter("expr2") - assert query.request.filter == "expr2" diff --git a/sdk/search/azure-search-documents/tests/test_regex_flags.py b/sdk/search/azure-search-documents/tests/test_regex_flags.py deleted file mode 100644 index 01726af1ffa2..000000000000 --- a/sdk/search/azure-search-documents/tests/test_regex_flags.py +++ /dev/null @@ -1,122 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.search.documents.indexes.models import ( - SearchIndex, - RegexFlags, - PatternAnalyzer, - PatternTokenizer, -) -from azure.search.documents.indexes._generated.models import ( - PatternAnalyzer as _PatternAnalyzer, - PatternTokenizer as _PatternTokenizer, -) - - -def test_unpack_search_index(): - pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags="CANON_EQ") - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags="CANON_EQ") - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex( - name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers - ) - result = SearchIndex._from_generated(index) - assert isinstance(result.analyzers[0], PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, list) - assert result.analyzers[0].flags[0] == "CANON_EQ" - assert isinstance(result.tokenizers[0], PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, list) - assert result.tokenizers[0].flags[0] == "CANON_EQ" - - -def test_multi_unpack_search_index(): - pattern_analyzer = _PatternAnalyzer( - name="test_analyzer", flags="CANON_EQ|MULTILINE" - ) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = _PatternTokenizer( - name="test_tokenizer", flags="CANON_EQ|MULTILINE" - ) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex( - name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers - ) - result = SearchIndex._from_generated(index) - assert isinstance(result.analyzers[0], PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, list) - assert result.analyzers[0].flags[0] == "CANON_EQ" - assert result.analyzers[0].flags[1] == "MULTILINE" - assert isinstance(result.tokenizers[0], PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, list) - assert result.tokenizers[0].flags[0] == "CANON_EQ" - assert result.tokenizers[0].flags[1] == "MULTILINE" - - -def test_unpack_search_index_enum(): - pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags=RegexFlags.canon_eq) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = _PatternTokenizer( - name="test_tokenizer", flags=RegexFlags.canon_eq - ) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex( - name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers - ) - result = SearchIndex._from_generated(index) - assert isinstance(result.analyzers[0], PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, list) - assert result.analyzers[0].flags[0] == "CANON_EQ" - assert isinstance(result.tokenizers[0], PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, list) - assert result.tokenizers[0].flags[0] == "CANON_EQ" - - -def test_pack_search_index(): - pattern_analyzer = PatternAnalyzer(name="test_analyzer", flags=["CANON_EQ"]) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = PatternTokenizer(name="test_tokenizer", flags=["CANON_EQ"]) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex( - name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers - ) - result = index._to_generated() - assert isinstance(result.analyzers[0], _PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, str) - assert result.analyzers[0].flags == "CANON_EQ" - assert isinstance(result.tokenizers[0], _PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, str) - assert result.tokenizers[0].flags == "CANON_EQ" - - -def test_multi_pack_search_index(): - pattern_analyzer = PatternAnalyzer( - name="test_analyzer", flags=["CANON_EQ", "MULTILINE"] - ) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = PatternTokenizer( - name="test_analyzer", flags=["CANON_EQ", "MULTILINE"] - ) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex( - name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers - ) - result = index._to_generated() - assert isinstance(result.analyzers[0], _PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, str) - assert result.analyzers[0].flags == "CANON_EQ|MULTILINE" - assert isinstance(result.tokenizers[0], _PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, str) - assert result.tokenizers[0].flags == "CANON_EQ|MULTILINE" diff --git a/sdk/search/azure-search-documents/tests/test_search_client.py b/sdk/search/azure-search-documents/tests/test_search_client.py index 937c154aec9a..dfbac7308cde 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client.py +++ b/sdk/search/azure-search-documents/tests/test_search_client.py @@ -5,15 +5,16 @@ import pytest from unittest import mock -from azure.core.paging import ItemPaged +from azure.core.paging import ItemPaged, PageIterator from azure.core.credentials import AzureKeyCredential -from azure.search.documents._generated.models import ( +from azure.search.documents._operations._patch import SearchPageIterator + +from azure.search.documents.models import ( FacetResult, SearchDocumentsResult, SearchResult, ) -from azure.search.documents._search_client import SearchPageIterator from azure.search.documents import ( IndexDocumentsBatch, @@ -21,7 +22,6 @@ RequestEntityTooLargeError, ApiVersion, ) -from azure.search.documents._utils import odata, get_answer_query CREDENTIAL = AzureKeyCredential(key="test_api_key") @@ -32,148 +32,50 @@ "merge_or_upload_documents", ] -CRUD_METHOD_MAP = dict( - zip(CRUD_METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"]) -) - - -class Test_odata: - def test_const(self): - assert odata("no escapes") == "no escapes" - - def test_numbers(self): - assert odata("foo eq {foo}", foo=10) == "foo eq 10" - - def test_string(self): - assert odata("foo eq {foo}", foo="a string") == "foo eq 'a string'" - - def test_mixed(self): - expected = "foo eq 'a string' and bar le 10" - out = odata("foo eq {foo} and bar le {bar}", foo="a string", bar=10) - assert out == expected - - def test_escape_single_quote(self): - assert odata("foo eq {foo}", foo="a '' str'ing") == "foo eq 'a '''' str''ing'" - - def test_prevent_double_quoting(self): - assert odata("foo eq '{foo}'", foo="a string") == "foo eq 'a string'" - - -class TestAnswerQuery: - def test_no_args(self): - assert get_answer_query() is None - - def test_query_answer(self): - assert get_answer_query("query") == "query" - - def test_query_answer_count(self): - assert get_answer_query("query", 5) == "query|count-5" - - def test_query_answer_threshold(self): - assert ( - get_answer_query("query", query_answer_threshold=0.5) - == "query|threshold-0.5" - ) - - def test_query_answer_count_threshold(self): - assert get_answer_query("query", 5, 0.5) == "query|count-5,threshold-0.5" +CRUD_METHOD_MAP = dict(zip(CRUD_METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"])) class TestSearchClient: - def test_init(self): - client = SearchClient("endpoint", "index name", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=none", - } - - def test_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchClient("endpoint", "index name", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=none", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=none", - } - - def test_headers_merge(self): - credential = AzureKeyCredential(key="test_api_key") - client = SearchClient("endpoint", "index name", credential) - orig = {"foo": "bar"} - result = client._merge_client_headers(orig) - assert result is not orig - assert result == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=none", - "foo": "bar", - } - - def test_repr(self): - client = SearchClient("endpoint", "index name", CREDENTIAL) - assert repr(client) == "".format( - repr("endpoint"), repr("index name") - ) - - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.count" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin.get_document_count") def test_get_document_count(self, mock_count): client = SearchClient("endpoint", "index name", CREDENTIAL) client.get_document_count() assert mock_count.called assert mock_count.call_args[0] == () - assert len(mock_count.call_args[1]) == 1 - assert mock_count.call_args[1]["headers"] == client._headers + assert len(mock_count.call_args[1]) == 0 - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.get" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin.get_document") def test_get_document(self, mock_get): client = SearchClient("endpoint", "index name", CREDENTIAL) client.get_document("some_key") assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" - assert mock_get.call_args[1]["selected_fields"] == None + assert mock_get.call_args[0] == ("some_key",) + assert len(mock_get.call_args[1]) == 0 mock_get.reset() client.get_document("some_key", selected_fields="foo") assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" + assert mock_get.call_args[0] == ("some_key",) + assert len(mock_get.call_args[1]) == 1 assert mock_get.call_args[1]["selected_fields"] == "foo" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._search_post") def test_search_query_argument(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = client.search(search_text="search text") assert isinstance(result, ItemPaged) assert result._page_iterator_class is SearchPageIterator search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result assert not mock_search_post.called next(result) assert mock_search_post.called assert mock_search_post.call_args[0] == () - assert ( - mock_search_post.call_args[1]["search_request"].search_text == "search text" - ) + # assert mock_search_post.call_args[1]["search_request"].search_text == "search text" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._search_post") def test_search_enable_elevated_read(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = client.search( @@ -182,91 +84,65 @@ def test_search_enable_elevated_read(self, mock_search_post): x_ms_query_source_authorization="aad:fake-user", ) search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result next(result) assert mock_search_post.called assert mock_search_post.call_args[1]["x_ms_enable_elevated_read"] is True - assert ( - mock_search_post.call_args[1]["x_ms_query_source_authorization"] - == "aad:fake-user" - ) + assert mock_search_post.call_args[1]["x_ms_query_source_authorization"] == "aad:fake-user" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.suggest_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._suggest_post") def test_suggest_query_argument(self, mock_suggest_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = client.suggest(search_text="search text", suggester_name="sg") assert mock_suggest_post.called assert mock_suggest_post.call_args[0] == () - assert mock_suggest_post.call_args[1]["headers"] == client._headers - assert ( - mock_suggest_post.call_args[1]["suggest_request"].search_text - == "search text" - ) + # assert mock_suggest_post.call_args[1]["suggest_request"].search_text == "search text" def test_suggest_bad_argument(self): client = SearchClient("endpoint", "index name", CREDENTIAL) with pytest.raises(TypeError) as e: client.suggest("bad_query") - assert str(e) == "Expected a SuggestQuery for 'query', but got {}".format( - repr("bad_query") - ) + assert str(e) == "Expected a SuggestQuery for 'query', but got {}".format(repr("bad_query")) - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._search_post") def test_get_count_reset_continuation_token(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = client.search(search_text="search text") assert isinstance(result, ItemPaged) assert result._page_iterator_class is SearchPageIterator search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result result.__next__() result._first_page_iterator_instance.continuation_token = "fake token" result.get_count() assert not result._first_page_iterator_instance.continuation_token - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.autocomplete_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._autocomplete_post") def test_autocomplete_query_argument(self, mock_autocomplete_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = client.autocomplete(search_text="search text", suggester_name="sg") assert mock_autocomplete_post.called assert mock_autocomplete_post.call_args[0] == () - assert mock_autocomplete_post.call_args[1]["headers"] == client._headers - assert ( - mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text - == "search text" - ) + # assert mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text == "search text" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.count" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin.get_document_count") def test_get_document_count_v2020_06_30(self, mock_count): - client = SearchClient( - "endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30 - ) + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) client.get_document_count() assert mock_count.called assert mock_count.call_args[0] == () - assert len(mock_count.call_args[1]) == 1 - assert mock_count.call_args[1]["headers"] == client._headers + assert len(mock_count.call_args[1]) == 0 - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._search_post") def test_get_facets_with_aggregations(self, mock_search_post): client = SearchClient("endpoint", "index name", CREDENTIAL) result = client.search(search_text="*") search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"id": "1"})] + search_result.results = [SearchResult({"id": "1"})] facet_bucket = FacetResult() facet_bucket.count = 4 @@ -291,102 +167,65 @@ def test_get_facets_with_aggregations(self, mock_search_post): assert bucket["max"] == 240.0 assert bucket["cardinality"] == 3 - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.get" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin.get_document") def test_get_document_v2020_06_30(self, mock_get): - client = SearchClient( - "endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30 - ) + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) client.get_document("some_key") assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" - assert mock_get.call_args[1]["selected_fields"] == None + assert mock_get.call_args[0] == ("some_key",) + assert len(mock_get.call_args[1]) == 0 mock_get.reset() client.get_document("some_key", selected_fields="foo") assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" + assert mock_get.call_args[0] == ("some_key",) + assert len(mock_get.call_args[1]) == 1 assert mock_get.call_args[1]["selected_fields"] == "foo" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._search_post") def test_search_query_argument_v2020_06_30(self, mock_search_post): - client = SearchClient( - "endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30 - ) + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) result = client.search(search_text="search text") assert isinstance(result, ItemPaged) assert result._page_iterator_class is SearchPageIterator search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result assert not mock_search_post.called next(result) assert mock_search_post.called assert mock_search_post.call_args[0] == () - assert ( - mock_search_post.call_args[1]["search_request"].search_text == "search text" - ) + # assert mock_search_post.call_args[1]["search_request"].search_text == "search text" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.suggest_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._suggest_post") def test_suggest_query_argument_v2020_06_30(self, mock_suggest_post): - client = SearchClient( - "endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30 - ) + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) result = client.suggest(search_text="search text", suggester_name="sg") assert mock_suggest_post.called assert mock_suggest_post.call_args[0] == () - assert mock_suggest_post.call_args[1]["headers"] == client._headers - assert ( - mock_suggest_post.call_args[1]["suggest_request"].search_text - == "search text" - ) + # assert mock_suggest_post.call_args[1]["suggest_request"].search_text == "search text" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.autocomplete_post" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._autocomplete_post") def test_autocomplete_query_argument_v2020_06_30(self, mock_autocomplete_post): - client = SearchClient( - "endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30 - ) + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) result = client.autocomplete(search_text="search text", suggester_name="sg") assert mock_autocomplete_post.called assert mock_autocomplete_post.call_args[0] == () - assert mock_autocomplete_post.call_args[1]["headers"] == client._headers - assert ( - mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text - == "search text" - ) + # assert mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text == "search text" def test_autocomplete_bad_argument(self): client = SearchClient("endpoint", "index name", CREDENTIAL) with pytest.raises(TypeError) as e: client.autocomplete("bad_query") - assert str( - e - ) == "Expected a AutocompleteQuery for 'query', but got {}".format( - repr("bad_query") - ) + assert str(e) == "Expected a AutocompleteQuery for 'query', but got {}".format(repr("bad_query")) @pytest.mark.parametrize( - "arg", [[], ["doc1"], ["doc1", "doc2"]], ids=lambda x: str(len(x)) + " docs" + "arg", [[], [{"doc1": "doc"}], [{"doc1": "doc"}, {"doc2": "doc"}]], ids=lambda x: str(len(x)) + " docs" ) @pytest.mark.parametrize("method_name", CRUD_METHOD_NAMES) def test_add_method(self, arg, method_name): - with mock.patch.object( - SearchClient, "index_documents", return_value=None - ) as mock_index_documents: + with mock.patch.object(SearchClient, "index_documents", return_value=None) as mock_index_documents: client = SearchClient("endpoint", "index name", CREDENTIAL) method = getattr(client, method_name) @@ -396,40 +235,32 @@ def test_add_method(self, arg, method_name): assert len(mock_index_documents.call_args[0]) == 1 batch = mock_index_documents.call_args[0][0] assert isinstance(batch, IndexDocumentsBatch) - assert all( - action.action_type == CRUD_METHOD_MAP[method_name] - for action in batch.actions - ) - assert [action.additional_properties for action in batch.actions] == arg - assert mock_index_documents.call_args[1]["headers"] == client._headers + assert all(action.action_type == CRUD_METHOD_MAP[method_name] for action in batch.actions) assert mock_index_documents.call_args[1]["extra"] == "foo" - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.index" - ) + @mock.patch("azure.search.documents._operations._operations._SearchClientOperationsMixin._index") def test_index_documents(self, mock_index): client = SearchClient("endpoint", "index name", CREDENTIAL) batch = IndexDocumentsBatch() - actions = batch.add_upload_actions("upload1") + actions = batch.add_upload_actions([{"upload1": "doc"}]) assert len(actions) == 1 for x in actions: assert x.action_type == "upload" - actions = batch.add_delete_actions("delete1", "delete2") + actions = batch.add_delete_actions([{"delete1": "doc"}, {"delete2": "doc"}]) assert len(actions) == 2 for x in actions: assert x.action_type == "delete" - actions = batch.add_merge_actions(["merge1", "merge2", "merge3"]) + actions = batch.add_merge_actions([{"merge1": "doc"}, {"merge2": "doc"}, {"merge3": "doc"}]) for x in actions: assert x.action_type == "merge" - actions = batch.add_merge_or_upload_actions("merge_or_upload1") + actions = batch.add_merge_or_upload_actions([{"merge_or_upload1": "doc"}]) for x in actions: assert x.action_type == "mergeOrUpload" client.index_documents(batch, extra="foo") assert mock_index.called assert mock_index.call_args[0] == () - assert mock_index.call_args[1]["headers"] == client._headers assert mock_index.call_args[1]["extra"] == "foo" def test_request_too_large_error(self): @@ -440,6 +271,6 @@ def test_request_too_large_error(self): ): client = SearchClient("endpoint", "index name", CREDENTIAL) batch = IndexDocumentsBatch() - batch.add_upload_actions("upload1") + batch.add_upload_actions([{"upload1": "doc"}]) with pytest.raises(RequestEntityTooLargeError): client.index_documents(batch, extra="foo") diff --git a/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py b/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py index 644b21adc88e..5c1500615dee 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py @@ -17,18 +17,14 @@ class TestSearchClient(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_get_document_count(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) assert client.get_document_count() == 10 @SearchEnvVarPreparer() @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_get_document(self, endpoint, index_name, index_batch): - client = SearchClient( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) for hotel_id in range(1, 11): result = client.get_document(key=str(hotel_id)) expected = index_batch["value"][hotel_id - 1] @@ -40,8 +36,6 @@ def test_get_document(self, endpoint, index_name, index_batch): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_get_document_missing(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) with pytest.raises(HttpResponseError): client.get_document(key="1000") diff --git a/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py b/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py index 1886a1654bb8..30d6f221bfd1 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py @@ -20,33 +20,17 @@ class TestSearchIndexingBufferedSender(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_search_client_index_buffered_sender(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) - batch_client = SearchIndexingBufferedSender( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + batch_client = SearchIndexingBufferedSender(endpoint, index_name, get_credential(), retry_backoff_factor=60) try: doc_count = 10 doc_count = self._test_upload_documents_new(client, batch_client, doc_count) - doc_count = self._test_upload_documents_existing( - client, batch_client, doc_count - ) - doc_count = self._test_delete_documents_existing( - client, batch_client, doc_count - ) - doc_count = self._test_delete_documents_missing( - client, batch_client, doc_count - ) - doc_count = self._test_merge_documents_existing( - client, batch_client, doc_count - ) - doc_count = self._test_merge_documents_missing( - client, batch_client, doc_count - ) - doc_count = self._test_merge_or_upload_documents( - client, batch_client, doc_count - ) + doc_count = self._test_upload_documents_existing(client, batch_client, doc_count) + doc_count = self._test_delete_documents_existing(client, batch_client, doc_count) + doc_count = self._test_delete_documents_missing(client, batch_client, doc_count) + doc_count = self._test_merge_documents_existing(client, batch_client, doc_count) + doc_count = self._test_merge_documents_missing(client, batch_client, doc_count) + doc_count = self._test_merge_or_upload_documents(client, batch_client, doc_count) finally: batch_client.close() diff --git a/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py b/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py index d01ea18eac77..15b3bba3cc5d 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py @@ -19,9 +19,7 @@ class TestSearchClientIndexDocument(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_search_client_index_document(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) doc_count = 10 doc_count = self._test_upload_documents_new(client, doc_count) doc_count = self._test_upload_documents_existing(client, doc_count) @@ -118,7 +116,7 @@ def _test_merge_documents_existing(self, client, doc_count): time.sleep(TIME_TO_SLEEP) test = client.get_document_count() - assert client.get_document_count() == doc_count + assert test == doc_count result = client.get_document(key="5") assert result["rating"] == 1 diff --git a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py index 921fab81d82e..36f15455cb4f 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py @@ -17,9 +17,7 @@ class TestSearchClient(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_search_client(self, endpoint, index_name): - client = SearchClient( - endpoint, index_name, get_credential(), retry_backoff_factor=60 - ) + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) self._test_get_search_simple(client) self._test_get_search_simple_with_top(client) self._test_get_search_filter(client) @@ -56,9 +54,7 @@ def _test_get_search_filter(self, client): order_by="hotelName desc", ) ) - assert [x["hotelName"] for x in results] == sorted( - [x["hotelName"] for x in results], reverse=True - ) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) expected = { "category", "hotelName", @@ -83,9 +79,7 @@ def _test_get_search_filter_array(self, client): order_by="hotelName desc", ) ) - assert [x["hotelName"] for x in results] == sorted( - [x["hotelName"] for x in results], reverse=True - ) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) expected = { "category", "hotelName", @@ -123,9 +117,7 @@ def _test_get_search_facets_none(self, client): def _test_get_search_facets_result(self, client): select = ("hotelName", "category", "description") - results = client.search( - search_text="WiFi", facets=["category"], select=",".join(select) - ) + results = client.search(search_text="WiFi", facets=["category"], select=",".join(select)) assert results.get_facets() == { "category": [ {"value": "Budget", "count": 4}, @@ -164,9 +156,7 @@ def _test_get_search_facet_metrics(self, client): } for metric, expected in expected_metrics.items(): assert metric in observed_metrics - assert math.isclose( - observed_metrics[metric], expected, rel_tol=0.0, abs_tol=0.001 - ) + assert math.isclose(observed_metrics[metric], expected, rel_tol=0.0, abs_tol=0.001) sleeps_metrics = facet_payload.get("rooms/sleepsCount", []) assert len(sleeps_metrics) == 1 @@ -174,11 +164,14 @@ def _test_get_search_facet_metrics(self, client): def _test_autocomplete(self, client): results = client.autocomplete(search_text="mot", suggester_name="sg") - assert results == [{"text": "motel", "query_plus_text": "motel"}] + assert any(d.text == "motel" for d in results) + assert any(d.query_plus_text == "motel" for d in results) def _test_suggest(self, client): results = client.suggest(search_text="mot", suggester_name="sg") - assert results == [ - {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, - {"hotelId": "9", "text": "Secret Point Motel"}, - ] + result = results[0] + assert result["hotelId"] == "2" + assert result.text == "Cheapest hotel in town. Infact, a motel." + result = results[1] + assert result["hotelId"] == "9" + assert result.text == "Secret Point Motel" diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client.py b/sdk/search/azure-search-documents/tests/test_search_index_client.py deleted file mode 100644 index cdb23a9c32ff..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client.py +++ /dev/null @@ -1,136 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import pytest -from unittest import mock - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient, ApiVersion -from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient -from azure.search.documents.indexes.models import ( - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, -) - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - - -class TestSearchIndexClient: - def test_index_init(self): - client = SearchIndexClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_index_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential, retry_backoff_factor=60) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_get_search_client(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - - def test_get_search_client_inherit_api_version(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient( - "endpoint", credential, api_version=ApiVersion.V2020_06_30 - ) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - assert search_client._api_version == ApiVersion.V2020_06_30 - - @mock.patch( - "azure.search.documents.indexes._generated.operations._search_service_client_operations._SearchServiceClientOperationsMixin.get_service_statistics" - ) - def test_get_service_statistics(self, mock_get_stats): - client = SearchIndexClient("endpoint", CREDENTIAL) - client.get_service_statistics() - assert mock_get_stats.called - assert mock_get_stats.call_args[0] == () - assert mock_get_stats.call_args[1] == {"headers": client._headers} - - @mock.patch( - "azure.search.documents.indexes._generated.operations._search_service_client_operations._SearchServiceClientOperationsMixin.get_service_statistics" - ) - def test_get_service_statistics_v2020_06_30(self, mock_get_stats): - client = SearchIndexClient( - "endpoint", CREDENTIAL, api_version=ApiVersion.V2020_06_30 - ) - client.get_service_statistics() - assert mock_get_stats.called - assert mock_get_stats.call_args[0] == () - assert mock_get_stats.call_args[1] == {"headers": client._headers} - - def test_index_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexClient(12345, credential) - - -class TestSearchIndexerClient: - def test_indexer_init(self): - client = SearchIndexerClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexerClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexerClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexerClient(12345, credential) - - def test_datasource_with_empty_connection_string(self): - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name="test", type="azureblob", connection_string="", container=container - ) - packed_data_source_connection = data_source_connection._to_generated() - assert ( - packed_data_source_connection.credentials.connection_string == "" - ) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py index ad5e1f227d9c..96c9baa2eff9 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py @@ -39,9 +39,7 @@ def test_alias(self, endpoint): # point an old alias to a new index new_index_name = "hotel" - self._test_update_alias_to_new_index( - client, aliases[1], new_index_name, index_name - ) + self._test_update_alias_to_new_index(client, aliases[1], new_index_name, index_name) self._test_get_alias(client, aliases) @@ -94,8 +92,8 @@ def _test_delete_aliases(self, client): def _create_index(self, client, index_name): fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), ] scoring_profile = ScoringProfile(name="MyProfile") scoring_profiles = [] diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py index 260dbbfea37a..b188d0be73fe 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py @@ -31,9 +31,7 @@ def _create_data_source_connection(self, cs, name): @recorded_by_proxy def test_data_source(self, endpoint, **kwargs): storage_cs = kwargs.get("search_storage_connection_string") - client = SearchIndexerClient( - endpoint, get_credential(), retry_backoff_factor=60 - ) + client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) self._test_create_datasource(client, storage_cs) self._test_delete_datasource(client, storage_cs) self._test_get_datasource(client, storage_cs) @@ -41,22 +39,17 @@ def test_data_source(self, endpoint, **kwargs): self._test_create_or_update_datasource(client, storage_cs) self._test_create_or_update_datasource_if_unchanged(client, storage_cs) self._test_delete_datasource_if_unchanged(client, storage_cs) - self._test_delete_datasource_string_if_unchanged(client, storage_cs) def _test_create_datasource(self, client, storage_cs): ds_name = "create" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) result = client.create_data_source_connection(data_source_connection) assert result.name == ds_name assert result.type == "azureblob" def _test_delete_datasource(self, client, storage_cs): ds_name = "delete" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) client.create_data_source_connection(data_source_connection) expected_count = len(client.get_data_source_connections()) - 1 client.delete_data_source_connection(ds_name) @@ -64,33 +57,23 @@ def _test_delete_datasource(self, client, storage_cs): def _test_get_datasource(self, client, storage_cs): ds_name = "get" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) client.create_data_source_connection(data_source_connection) result = client.get_data_source_connection(ds_name) assert result.name == ds_name def _test_list_datasources(self, client, storage_cs): - data_source_connection1 = self._create_data_source_connection( - storage_cs, "list" - ) - data_source_connection2 = self._create_data_source_connection( - storage_cs, "list2" - ) + data_source_connection1 = self._create_data_source_connection(storage_cs, "list") + data_source_connection2 = self._create_data_source_connection(storage_cs, "list2") client.create_data_source_connection(data_source_connection1) client.create_data_source_connection(data_source_connection2) result = client.get_data_source_connections() assert isinstance(result, list) - assert set(x.name for x in result).intersection(set(["list", "list2"])) == set( - ["list", "list2"] - ) + assert set(x.name for x in result).intersection(set(["list", "list2"])) == set(["list", "list2"]) def _test_create_or_update_datasource(self, client, storage_cs): ds_name = "cou" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) client.create_data_source_connection(data_source_connection) expected_count = len(client.get_data_source_connections()) data_source_connection.description = "updated" @@ -102,9 +85,7 @@ def _test_create_or_update_datasource(self, client, storage_cs): def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): ds_name = "couunch" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) created = client.create_data_source_connection(data_source_connection) etag = created.e_tag @@ -113,9 +94,7 @@ def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): client.create_or_update_data_source_connection(data_source_connection) # prepare data source connection - data_source_connection.e_tag = ( - etag # reset to the original data source connection - ) + data_source_connection.e_tag = etag # reset to the original data source connection data_source_connection.description = "changed" with pytest.raises(HttpResponseError): client.create_or_update_data_source_connection( @@ -124,9 +103,7 @@ def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): def _test_delete_datasource_if_unchanged(self, client, storage_cs): ds_name = "delunch" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) created = client.create_data_source_connection(data_source_connection) etag = created.e_tag @@ -135,32 +112,6 @@ def _test_delete_datasource_if_unchanged(self, client, storage_cs): client.create_or_update_data_source_connection(data_source_connection) # prepare data source connection - data_source_connection.e_tag = ( - etag # reset to the original data source connection - ) + data_source_connection.e_tag = etag # reset to the original data source connection with pytest.raises(HttpResponseError): - client.delete_data_source_connection( - data_source_connection, match_condition=MatchConditions.IfNotModified - ) - - def _test_delete_datasource_string_if_unchanged(self, client, storage_cs): - ds_name = "delstrunch" - data_source_connection = self._create_data_source_connection( - storage_cs, ds_name - ) - created = client.create_data_source_connection(data_source_connection) - etag = created.e_tag - - # Now update the data source connection - data_source_connection.description = "updated" - client.create_or_update_data_source_connection(data_source_connection) - - # prepare data source connection - data_source_connection.e_tag = ( - etag # reset to the original data source connection - ) - with pytest.raises(ValueError): - client.delete_data_source_connection( - data_source_connection.name, - match_condition=MatchConditions.IfNotModified, - ) + client.delete_data_source_connection(data_source_connection, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py index d0ec01c47903..84fd24dc571b 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py @@ -47,8 +47,8 @@ def test_search_index_client(self, endpoint, index_name): def _test_get_service_statistics(self, client): result = client.get_service_statistics() - assert isinstance(result, dict) - assert set(result.keys()) == {"counters", "indexers_runtime", "limits"} + assert "counters" in set(result.keys()) + assert "limits" in set(result.keys()) def _test_list_indexes_empty(self, client): result = client.list_indexes() @@ -70,14 +70,14 @@ def _test_get_index(self, client, index_name): def _test_get_index_statistics(self, client, index_name): result = client.get_index_statistics(index_name) keys = set(result.keys()) - assert "document_count" in keys - assert "storage_size" in keys - assert "vector_index_size" in keys + assert "documentCount" in keys + assert "storageSize" in keys + assert "vectorIndexSize" in keys def _test_create_index(self, client, index_name): fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), ] scoring_profile = ScoringProfile(name="MyProfile") scoring_profiles = [] @@ -98,8 +98,8 @@ def _test_create_index(self, client, index_name): def _test_create_or_update_index(self, client): name = "hotels-cou" fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), ] cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) scoring_profiles = [] @@ -152,14 +152,10 @@ def _test_create_or_update_indexes_if_unchanged(self, client): index.e_tag = etag with pytest.raises(HttpResponseError): - client.create_or_update_index( - index, match_condition=MatchConditions.IfNotModified - ) + client.create_or_update_index(index, match_condition=MatchConditions.IfNotModified) def _test_analyze_text(self, client, index_name): - analyze_request = AnalyzeTextOptions( - text="One's ", analyzer_name="standard.lucene" - ) + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") result = client.analyze_text(index_name, analyze_request) assert len(result.tokens) == 2 @@ -205,14 +201,14 @@ def test_purview_enabled_index(self, search_service_endpoint, search_service_nam fields = [ SearchField( name="id", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, key=True, filterable=True, sortable=True, ), SearchField( name="sensitivityLabel", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, filterable=True, sensitivity_label=True, ), @@ -245,19 +241,17 @@ def test_purview_enabled_index(self, search_service_endpoint, search_service_nam @SearchEnvVarPreparer() @recorded_by_proxy - def test_scoring_profile_product_aggregation( - self, search_service_endpoint, search_service_name - ): + def test_scoring_profile_product_aggregation(self, search_service_endpoint, search_service_name): del search_service_name # unused endpoint = search_service_endpoint client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) index_name = self.get_resource_name("agg-product") fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), SimpleField( name="lastUpdated", - type=SearchFieldDataType.DateTimeOffset, + type=SearchFieldDataType.DATE_TIME_OFFSET, filterable=True, ), ] @@ -268,39 +262,24 @@ def test_scoring_profile_product_aggregation( FreshnessScoringFunction( field_name="lastUpdated", boost=2.5, - parameters=FreshnessScoringParameters( - boosting_duration=timedelta(days=7) - ), + parameters=FreshnessScoringParameters(boosting_duration=timedelta(days=7)), ) ], ) - index = SearchIndex( - name=index_name, fields=fields, scoring_profiles=[scoring_profile] - ) + index = SearchIndex(name=index_name, fields=fields, scoring_profiles=[scoring_profile]) created = client.create_index(index) try: - assert ( - created.scoring_profiles[0].function_aggregation - == ScoringFunctionAggregation.PRODUCT - ) + assert created.scoring_profiles[0].function_aggregation == ScoringFunctionAggregation.PRODUCT fetched = client.get_index(index_name) - assert ( - fetched.scoring_profiles[0].function_aggregation - == ScoringFunctionAggregation.PRODUCT - ) + assert fetched.scoring_profiles[0].function_aggregation == ScoringFunctionAggregation.PRODUCT - fetched.scoring_profiles[0].function_aggregation = ( - ScoringFunctionAggregation.SUM - ) + fetched.scoring_profiles[0].function_aggregation = ScoringFunctionAggregation.SUM client.create_or_update_index(index=fetched) updated = client.get_index(index_name) - assert ( - updated.scoring_profiles[0].function_aggregation - == ScoringFunctionAggregation.SUM - ) + assert updated.scoring_profiles[0].function_aggregation == ScoringFunctionAggregation.SUM finally: try: client.delete_index(index_name) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py index f82b72749050..5b4afeba5c51 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py @@ -12,13 +12,11 @@ from search_service_preparer import SearchEnvVarPreparer, search_decorator from azure.search.documents.indexes.models import ( EntityLinkingSkill, - EntityRecognitionSkill, - EntityRecognitionSkillVersion, + EntityRecognitionSkillV3 as EntityRecognitionSkill, InputFieldMappingEntry, OutputFieldMappingEntry, SearchIndexerSkillset, - SentimentSkill, - SentimentSkillVersion, + SentimentSkillV3 as SentimentSkill, ) from azure.search.documents.indexes import SearchIndexerClient @@ -29,9 +27,7 @@ class TestSearchSkillset(AzureRecordedTestCase): @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") @recorded_by_proxy def test_skillset_crud(self, endpoint): - client = SearchIndexerClient( - endpoint, get_credential(), retry_backoff_factor=60 - ) + client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) self._test_create_skillset_validation() self._test_create_skillset(client) self._test_get_skillset(client) @@ -45,50 +41,24 @@ def test_skillset_crud(self, endpoint): def _test_create_skillset_validation(self): name = "test-ss-validation" with pytest.raises(ValueError) as err: - client = SearchIndexerClient( - "fake_endpoint", AzureKeyCredential("fake_key") - ) + client = SearchIndexerClient("fake_endpoint", AzureKeyCredential("fake_key")) s1 = EntityRecognitionSkill( - inputs=[ - InputFieldMappingEntry(name="text", source="/document/content") - ], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizationsS1" - ) - ], + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], description="Skill Version 1", model_version="1", include_typeless_entities=True, ) s2 = EntityRecognitionSkill( - inputs=[ - InputFieldMappingEntry(name="text", source="/document/content") - ], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizationsS2" - ) - ], - skill_version=EntityRecognitionSkillVersion.LATEST, + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], description="Skill Version 3", model_version="3", include_typeless_entities=True, ) - s3 = SentimentSkill( - inputs=[ - InputFieldMappingEntry(name="text", source="/document/content") - ], - outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], - skill_version=SentimentSkillVersion.V1, - description="Sentiment V1", - include_opinion_mining=True, - ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s1, s2, s3]), description="desc" - ) + skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2]), description="desc") client.create_skillset(skillset) assert "include_typeless_entities" in str(err.value) assert "model_version" in str(err.value) @@ -99,11 +69,7 @@ def _test_create_skillset(self, client): s1 = EntityRecognitionSkill( name="skill1", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizationsS1" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], description="Skill Version 1", include_typeless_entities=True, ) @@ -111,30 +77,14 @@ def _test_create_skillset(self, client): s2 = EntityRecognitionSkill( name="skill2", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizationsS2" - ) - ], - skill_version=EntityRecognitionSkillVersion.LATEST, + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], description="Skill Version 3", model_version="3", ) - s3 = SentimentSkill( - name="skill3", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], - skill_version=SentimentSkillVersion.V1, - description="Sentiment V1", - ) - s4 = SentimentSkill( name="skill4", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4") - ], - skill_version=SentimentSkillVersion.V3, + outputs=[OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4")], description="Sentiment V3", include_opinion_mining=True, ) @@ -142,15 +92,11 @@ def _test_create_skillset(self, client): s5 = EntityLinkingSkill( name="skill5", inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry(name="entities", target_name="entitiesS5") - ], + outputs=[OutputFieldMappingEntry(name="entities", target_name="entitiesS5")], minimum_precision=0.5, ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s1, s2, s3, s4, s5]), description="desc" - ) + skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s4, s5]), description="desc") dict_skills = [skill.as_dict() for skill in skillset.skills] skillset.skills = dict_skills @@ -163,15 +109,10 @@ def _test_create_skillset(self, client): assert result.e_tag assert len(result.skills) == 5 assert isinstance(result.skills[0], EntityRecognitionSkill) - assert result.skills[0].skill_version == EntityRecognitionSkillVersion.V1 assert isinstance(result.skills[1], EntityRecognitionSkill) - assert result.skills[1].skill_version == EntityRecognitionSkillVersion.V3 assert isinstance(result.skills[2], SentimentSkill) - assert result.skills[2].skill_version == SentimentSkillVersion.V1 - assert isinstance(result.skills[3], SentimentSkill) - assert result.skills[3].skill_version == SentimentSkillVersion.V3 - assert isinstance(result.skills[4], EntityLinkingSkill) - assert result.skills[4].minimum_precision == 0.5 + assert isinstance(result.skills[3], EntityLinkingSkill) + assert result.skills[3].minimum_precision == 0.5 assert len(client.get_skillsets()) == 1 client.reset_skills(result, [x.name for x in result.skills]) @@ -180,15 +121,9 @@ def _test_get_skillset(self, client): name = "test-ss-get" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], - ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc" + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") client.create_skillset(skillset) result = client.get_skillset(name) assert isinstance(result, SearchIndexerSkillset) @@ -203,47 +138,29 @@ def _test_get_skillsets(self, client): name2 = "test-ss-list-2" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name1, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name1, skills=list([s]), description="desc1") client.create_skillset(skillset1) - skillset2 = SearchIndexerSkillset( - name=name2, skills=list([s]), description="desc2" - ) + skillset2 = SearchIndexerSkillset(name=name2, skills=list([s]), description="desc2") client.create_skillset(skillset2) result = client.get_skillsets() assert isinstance(result, list) assert all(isinstance(x, SearchIndexerSkillset) for x in result) - assert set(x.name for x in result).intersection([name1, name2]) == set( - [name1, name2] - ) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) def _test_create_or_update_skillset(self, client): name = "test-ss-create-or-update" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") client.create_or_update_skillset(skillset1) expected_count = len(client.get_skillsets()) - skillset2 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc2" - ) + skillset2 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc2") client.create_or_update_skillset(skillset2) assert len(client.get_skillsets()) == expected_count @@ -256,21 +173,13 @@ def _test_create_or_update_skillset_inplace(self, client): name = "test-ss-create-or-update-inplace" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") ss = client.create_or_update_skillset(skillset1) expected_count = len(client.get_skillsets()) - skillset2 = SearchIndexerSkillset( - name=name, skills=[s], description="desc2", skillset=ss - ) + skillset2 = SearchIndexerSkillset(name=name, skills=[s], description="desc2", skillset=ss) client.create_or_update_skillset(skillset2) assert len(client.get_skillsets()) == expected_count @@ -283,53 +192,35 @@ def _test_create_or_update_skillset_if_unchanged(self, client): name = "test-ss-create-or-update-unchanged" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset1 = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc1" - ) + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") ss = client.create_or_update_skillset(skillset1) ss.e_tag = "changed_etag" with pytest.raises(HttpResponseError): - client.create_or_update_skillset( - ss, match_condition=MatchConditions.IfNotModified - ) + client.create_or_update_skillset(ss, match_condition=MatchConditions.IfNotModified) def _test_delete_skillset_if_unchanged(self, client): name = "test-ss-deleted-unchanged" s = EntityRecognitionSkill( inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[ - OutputFieldMappingEntry( - name="organizations", target_name="organizations" - ) - ], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], ) - skillset = SearchIndexerSkillset( - name=name, skills=list([s]), description="desc" - ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") result = client.create_skillset(skillset) etag = result.e_tag - skillset = SearchIndexerSkillset( - name=name, skills=list([s]), description="updated" - ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="updated") updated = client.create_or_update_skillset(skillset) updated.e_tag = etag with pytest.raises(HttpResponseError): - client.delete_skillset( - updated, match_condition=MatchConditions.IfNotModified - ) + client.delete_skillset(updated, match_condition=MatchConditions.IfNotModified) def _test_delete_skillset(self, client): for skillset in client.get_skillset_names(): diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py index b53e85a6b41c..42a4154b0f45 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py @@ -77,9 +77,7 @@ def _test_delete_synonym_map_if_unchanged(self, client): result.e_tag = etag with pytest.raises(HttpResponseError): - client.delete_synonym_map( - result, match_condition=MatchConditions.IfNotModified - ) + client.delete_synonym_map(result, match_condition=MatchConditions.IfNotModified) client.delete_synonym_map(name) def _test_get_synonym_map(self, client): diff --git a/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py b/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py index cd6dfb314b95..5dc6daacdab2 100644 --- a/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py @@ -28,28 +28,18 @@ class TestSearchIndexerClientTest(AzureRecordedTestCase): def test_search_indexers(self, endpoint, **kwargs): storage_cs = kwargs.get("search_storage_connection_string") container_name = kwargs.get("search_storage_container_name") - client = SearchIndexerClient( - endpoint, get_credential(), retry_backoff_factor=60 - ) - index_client = SearchIndexClient( - endpoint, get_credential(), retry_backoff_factor=60 - ) + client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) + index_client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) self._test_create_indexer(client, index_client, storage_cs, container_name) self._test_delete_indexer(client, index_client, storage_cs, container_name) self._test_get_indexer(client, index_client, storage_cs, container_name) self._test_list_indexer(client, index_client, storage_cs, container_name) - self._test_create_or_update_indexer( - client, index_client, storage_cs, container_name - ) + self._test_create_or_update_indexer(client, index_client, storage_cs, container_name) self._test_reset_indexer(client, index_client, storage_cs, container_name) self._test_run_indexer(client, index_client, storage_cs, container_name) self._test_get_indexer_status(client, index_client, storage_cs, container_name) - self._test_create_or_update_indexer_if_unchanged( - client, index_client, storage_cs, container_name - ) - self._test_delete_indexer_if_unchanged( - client, index_client, storage_cs, container_name - ) + self._test_create_or_update_indexer_if_unchanged(client, index_client, storage_cs, container_name) + self._test_delete_indexer_if_unchanged(client, index_client, storage_cs, container_name) def _prepare_indexer(self, client, index_client, storage_cs, name, container_name): data_source_connection = SearchIndexerDataSourceConnection( @@ -60,20 +50,14 @@ def _prepare_indexer(self, client, index_client, storage_cs, name, container_nam ) ds = client.create_data_source_connection(data_source_connection) - fields = [ - {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False} - ] + fields = [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}] index = SearchIndex(name=f"{name}-hotels", fields=fields) ind = index_client.create_index(index) - return SearchIndexer( - name=name, data_source_name=ds.name, target_index_name=ind.name - ) + return SearchIndexer(name=name, data_source_name=ds.name, target_index_name=ind.name) def _test_create_indexer(self, client, index_client, storage_cs, container_name): name = "create" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) result = client.create_indexer(indexer) assert result.name == name assert result.target_index_name == f"{name}-hotels" @@ -81,9 +65,7 @@ def _test_create_indexer(self, client, index_client, storage_cs, container_name) def _test_delete_indexer(self, client, index_client, storage_cs, container_name): name = "delete" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) client.create_indexer(indexer) expected = len(client.get_indexers()) - 1 client.delete_indexer(name) @@ -91,9 +73,7 @@ def _test_delete_indexer(self, client, index_client, storage_cs, container_name) def _test_get_indexer(self, client, index_client, storage_cs, container_name): name = "get" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) client.create_indexer(indexer) result = client.get_indexer(name) assert result.name == name @@ -101,27 +81,17 @@ def _test_get_indexer(self, client, index_client, storage_cs, container_name): def _test_list_indexer(self, client, index_client, storage_cs, container_name): name1 = "list1" name2 = "list2" - indexer1 = self._prepare_indexer( - client, index_client, storage_cs, name1, container_name - ) - indexer2 = self._prepare_indexer( - client, index_client, storage_cs, name2, container_name - ) + indexer1 = self._prepare_indexer(client, index_client, storage_cs, name1, container_name) + indexer2 = self._prepare_indexer(client, index_client, storage_cs, name2, container_name) client.create_indexer(indexer1) client.create_indexer(indexer2) result = client.get_indexers() assert isinstance(result, list) - assert set(x.name for x in result).intersection([name1, name2]) == set( - [name1, name2] - ) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) - def _test_create_or_update_indexer( - self, client, index_client, storage_cs, container_name - ): + def _test_create_or_update_indexer(self, client, index_client, storage_cs, container_name): name = "cou" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) client.create_indexer(indexer) expected = len(client.get_indexers()) if self.is_live: @@ -135,9 +105,7 @@ def _test_create_or_update_indexer( def _test_reset_indexer(self, client, index_client, storage_cs, container_name): name = "reset" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) client.create_indexer(indexer) if self.is_live: time.sleep(10) @@ -149,31 +117,21 @@ def _test_reset_indexer(self, client, index_client, storage_cs, container_name): def _test_run_indexer(self, client, index_client, storage_cs, container_name): name = "run" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) client.create_indexer(indexer) client.run_indexer(name) assert (client.get_indexer_status(name)).status == "running" - def _test_get_indexer_status( - self, client, index_client, storage_cs, container_name - ): + def _test_get_indexer_status(self, client, index_client, storage_cs, container_name): name = "get-status" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) client.create_indexer(indexer) status = client.get_indexer_status(name) assert status.status is not None - def _test_create_or_update_indexer_if_unchanged( - self, client, index_client, storage_cs, container_name - ): + def _test_create_or_update_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): name = "couunch" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) created = client.create_indexer(indexer) etag = created.e_tag if self.is_live: @@ -183,17 +141,11 @@ def _test_create_or_update_indexer_if_unchanged( indexer.e_tag = etag with pytest.raises(HttpResponseError): - client.create_or_update_indexer( - indexer, match_condition=MatchConditions.IfNotModified - ) + client.create_or_update_indexer(indexer, match_condition=MatchConditions.IfNotModified) - def _test_delete_indexer_if_unchanged( - self, client, index_client, storage_cs, container_name - ): + def _test_delete_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): name = "delunch" - indexer = self._prepare_indexer( - client, index_client, storage_cs, name, container_name - ) + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) result = client.create_indexer(indexer) etag = result.e_tag if self.is_live: @@ -203,6 +155,4 @@ def _test_delete_indexer_if_unchanged( indexer.e_tag = etag with pytest.raises(HttpResponseError): - client.delete_indexer( - indexer, match_condition=MatchConditions.IfNotModified - ) + client.delete_indexer(indexer, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/test_serialization.py b/sdk/search/azure-search-documents/tests/test_serialization.py index 0d532c9c7137..6c82dc9a8c00 100644 --- a/sdk/search/azure-search-documents/tests/test_serialization.py +++ b/sdk/search/azure-search-documents/tests/test_serialization.py @@ -24,18 +24,16 @@ def test_serialize_search_index(): new_index_name = "hotels" fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField( - name="description", type=SearchFieldDataType.String, collection=True - ), - SearchableField(name="hotelName", type=SearchFieldDataType.String), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="description", type=SearchFieldDataType.STRING, collection=True), + SearchableField(name="hotelName", type=SearchFieldDataType.STRING), ComplexField( name="address", fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), + SimpleField(name="streetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="city", type=SearchFieldDataType.STRING), + SimpleField(name="state", type=SearchFieldDataType.STRING), ], collection=True, ), @@ -50,8 +48,8 @@ def test_serialize_search_index(): scoring_profiles=scoring_profiles, cors_options=cors_options, ) - search_index_serialized = index.serialize() - search_index = SearchIndex.deserialize(search_index_serialized) + search_index_serialized = index.as_dict() + search_index = SearchIndex(search_index_serialized) assert search_index @@ -59,9 +57,7 @@ def test_serialize_search_indexer_skillset(): COGNITIVE_KEY = ... COGNITIVE_DESCRIPTION = ... - cognitive_services_account = CognitiveServicesAccountKey( - key=COGNITIVE_KEY, description=COGNITIVE_DESCRIPTION - ) + cognitive_services_account = CognitiveServicesAccountKey(key=COGNITIVE_KEY, description=COGNITIVE_DESCRIPTION) inputs = [InputFieldMappingEntry(name="text", source="/document/content")] @@ -83,26 +79,24 @@ def test_serialize_search_indexer_skillset(): cognitive_services_account=cognitive_services_account, ) - serialized_skillset = skillset.serialize() - skillset = SearchIndexerSkillset.deserialize(serialized_skillset) + serialized_skillset = skillset.as_dict() + skillset = SearchIndexerSkillset(serialized_skillset) assert skillset def test_serialize_search_index_dict(): new_index_name = "hotels" fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField( - name="description", type=SearchFieldDataType.String, collection=True - ), - SearchableField(name="hotelName", type=SearchFieldDataType.String), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.DOUBLE), + SearchableField(name="description", type=SearchFieldDataType.STRING, collection=True), + SearchableField(name="hotelName", type=SearchFieldDataType.STRING), ComplexField( name="address", fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), + SimpleField(name="streetAddress", type=SearchFieldDataType.STRING), + SimpleField(name="city", type=SearchFieldDataType.STRING), + SimpleField(name="state", type=SearchFieldDataType.STRING), ], collection=True, ), @@ -118,5 +112,5 @@ def test_serialize_search_index_dict(): cors_options=cors_options, ) search_index_serialized_dict = index.as_dict() - search_index = SearchIndex.from_dict(search_index_serialized_dict) + search_index = SearchIndex(search_index_serialized_dict) assert search_index diff --git a/sdk/search/azure-search-documents/tsp-location.yaml b/sdk/search/azure-search-documents/tsp-location.yaml new file mode 100644 index 000000000000..b843d75e9b2d --- /dev/null +++ b/sdk/search/azure-search-documents/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/search/data-plane/Search +commit: 83e4bd86d32bf00cfab973cf24b2e10733f4d1b8 +repo: Azure/azure-rest-api-specs + \ No newline at end of file From a907cd907a2f31f7c5621218da913027145ee8e1 Mon Sep 17 00:00:00 2001 From: jenny <63012604+JennyPng@users.noreply.github.com> Date: Fri, 6 Feb 2026 14:39:57 -0800 Subject: [PATCH 80/84] Automate Conda Release File Updates (#44569) * update version * csv parsing * progress on checking package versions * update package version checking logic * progress on updating vers and getting uri * some progress, but csv method misses packages * better handling download_uri * minor cleanup log output * minor progress and clean * minor fix to quote string values in yaml * minor progress in generating meta.yml * minor * getting parsedsetup requirements..but this isn't everything * minor improvements * more requirement fetching logic refinement * minor * refine metadata extraction * about section handling improvements * use metadata from parsedsetup * preserve indent in conda-sdk-client * lots of refactoring to update conda-sdk-client * minor service name improvements * minor * basic logic for adding new mgmt packages * minor * properly add new mgmt entries in conda sdk client * initial release log script but i need to use more csv data to group packages * some progress in using repopath for service * initial mappings * minor * refactor progress * conda sdk client refactor almost complete * this here seems to work for new batched packages * some progress in dataplane yml * basic data plane yaml working for grouped? * minor clean * minor * refactor utility functions * minor progress * data plane release logs * remove azure-common from group, need to handle * data plane existing release log update almost fully works * exception for healthinsights * yayay mgmt release log * uampq * minor * fix hyphenated mgmt imports * check if release log already has section * remove uamqp ref * overwrite release log existing sections * minor temp grouping fix * fix * additional deprecated check * parse stable vs beta release * test pyproject bundle * begin pyproject.toml logic attempt * refactor conda sdk client update * minor * clean up package sorting * start preprocessing bundle mapping from pyproject * fix bundling for new data plane yaml * add conda section to pyprojects of established bundles * minor helper improvement * clean and bundle map progress * refactor release log updates for bundles * mgmt release log * clean * clean * handle msal release log * minor * bug fix * remove using metadata as summary, doesn't always work * minor clean * initial pipeline attempt * Update conda-update-pipeline.yml for Azure Pipelines * minor * variable group? * nvm * minor * add schedule to pipeline * add date to pr name * Minor clean * initial draft of publish stage * yml improvements, enable dry run of file updates * remove duplicated tool section from merge * fix org name * move publish logic to python script * just to be safe * remove publishing changes from this PR * clean up some todos * handle home_url for bundle * add next steps to generated PR desc * untouch pyprojects that only have diff coz resolving merge * fix common_root, release type classification, other minor fixes * improve manual next steps * bundle fix * properly import submodules * release log bundle bug fix * check stable release thru pypi, update missed pyproject * clean, remove unneeded function and uamqp exception * cleanup * cache glob results * minor fix to use service dir for metadata desc * use pypi_tools * simplify bundle map creation, only look at data pkgs * actually catch pkgs w/o conda config when making the map * use namespace for module name instead of naive parsing * error if somehow someway version is ever missing from processed pkgs * never allow null pkg_path for getting service_dir metadata * trim essential reqs list * dont need to import types * trim again --- conda/conda-recipes/azure-mgmt/meta.yaml | 21 +- conda/conda_helper_functions.py | 344 +++++ conda/update_conda_files.py | 1134 +++++++++++++++++ eng/pipelines/conda-update-pipeline.yml | 121 ++ .../templates/stages/conda-sdk-client.yml | 2 - .../ci_tools/parsing/parse_functions.py | 27 +- sdk/ai/azure-ai-voicelive/pyproject.toml | 5 +- 7 files changed, 1637 insertions(+), 17 deletions(-) create mode 100644 conda/conda_helper_functions.py create mode 100644 conda/update_conda_files.py create mode 100644 eng/pipelines/conda-update-pipeline.yml diff --git a/conda/conda-recipes/azure-mgmt/meta.yaml b/conda/conda-recipes/azure-mgmt/meta.yaml index 6b6a9d67e940..191506a42734 100644 --- a/conda/conda-recipes/azure-mgmt/meta.yaml +++ b/conda/conda-recipes/azure-mgmt/meta.yaml @@ -73,7 +73,7 @@ test: - azure.mgmt.applicationinsights.v2022_06_15.aio.operations - azure.mgmt.applicationinsights.v2022_06_15.models - azure.mgmt.applicationinsights.v2022_06_15.operations - - azure-mgmt-arizeaiobservabilityeval + - azure.mgmt.arizeaiobservabilityeval - azure.mgmt.arizeaiobservabilityeval.aio - azure.mgmt.arizeaiobservabilityeval.aio.operations - azure.mgmt.arizeaiobservabilityeval.models @@ -150,7 +150,7 @@ test: - azure.mgmt.botservice.aio.operations - azure.mgmt.botservice.models - azure.mgmt.botservice.operations - - azure-mgmt-carbonoptimization + - azure.mgmt.carbonoptimization - azure.mgmt.carbonoptimization.aio - azure.mgmt.carbonoptimization.aio.operations - azure.mgmt.carbonoptimization.models @@ -260,11 +260,6 @@ test: - azure.mgmt.dashboard.operations - azure.mgmt.databox - azure.mgmt.databox.aio - - azure.mgmt.datab - - azure.mgmt.datab.aio - - azure.mgmt.datab.aio.operations - - azure.mgmt.datab.models - - azure.mgmt.datab.operations - azure.mgmt.databoxedge - azure.mgmt.databoxedge.aio - azure.mgmt.databoxedge.aio @@ -419,7 +414,7 @@ test: - azure.mgmt.hanaonazure.aio.operations - azure.mgmt.hanaonazure.models - azure.mgmt.hanaonazure.operations - - azure-mgmt-hardwaresecuritymodules + - azure.mgmt.hardwaresecuritymodules - azure.mgmt.hardwaresecuritymodules.aio - azure.mgmt.hardwaresecuritymodules.aio.operations - azure.mgmt.hardwaresecuritymodules.models @@ -515,7 +510,7 @@ test: - azure.mgmt.labservices.aio.operations - azure.mgmt.labservices.models - azure.mgmt.labservices.operations - - azure-mgmt-lambdatesthyperexecute + - azure.mgmt.lambdatesthyperexecute - azure.mgmt.lambdatesthyperexecute.aio - azure.mgmt.lambdatesthyperexecute.aio.operations - azure.mgmt.lambdatesthyperexecute.models @@ -610,7 +605,7 @@ test: - azure.mgmt.mongocluster.aio.operations - azure.mgmt.mongocluster.models - azure.mgmt.mongocluster.operations - - azure-mgmt-mongodbatlas + - azure.mgmt.mongodbatlas - azure.mgmt.mongodbatlas.aio - azure.mgmt.mongodbatlas.aio.operations - azure.mgmt.mongodbatlas.models @@ -730,7 +725,7 @@ test: - azure.mgmt.privatedns.aio.operations - azure.mgmt.privatedns.models - azure.mgmt.privatedns.operations - - azure-mgmt-purestorageblock + - azure.mgmt.purestorageblock - azure.mgmt.purestorageblock.aio - azure.mgmt.purestorageblock.aio.operations - azure.mgmt.purestorageblock.models @@ -791,7 +786,7 @@ test: - azure.mgmt.recoveryservicesbackup.passivestamp.aio.operations - azure.mgmt.recoveryservicesbackup.passivestamp.models - azure.mgmt.recoveryservicesbackup.passivestamp.operations - - azure-mgmt-recoveryservicesdatareplication + - azure.mgmt.recoveryservicesdatareplication - azure.mgmt.recoveryservicesdatareplication.aio - azure.mgmt.recoveryservicesdatareplication.aio.operations - azure.mgmt.recoveryservicesdatareplication.models @@ -977,7 +972,7 @@ test: - azure.mgmt.storage.aio.operations - azure.mgmt.storage.models - azure.mgmt.storage.operations - - azure-mgmt-storageactions + - azure.mgmt.storageactions - azure.mgmt.storageactions.aio - azure.mgmt.storageactions.aio.operations - azure.mgmt.storageactions.models diff --git a/conda/conda_helper_functions.py b/conda/conda_helper_functions.py new file mode 100644 index 000000000000..2b9e0b2d8e35 --- /dev/null +++ b/conda/conda_helper_functions.py @@ -0,0 +1,344 @@ +""" +Helper functions for updating conda files. +""" + +import os +import glob +from functools import lru_cache +from typing import Optional +import csv +from ci_tools.logging import logger +import urllib.request +from datetime import datetime +from ci_tools.parsing import ParsedSetup +from packaging.version import Version +from pypi_tools.pypi import PyPIClient, retrieve_versions_from_pypi + + +ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +SDK_DIR = os.path.join(ROOT_DIR, "sdk") + +AZURE_SDK_CSV_URL = "https://raw.githubusercontent.com/Azure/azure-sdk/main/_data/releases/latest/python-packages.csv" +PACKAGE_COL = "Package" +LATEST_GA_DATE_COL = "LatestGADate" +VERSION_GA_COL = "VersionGA" +FIRST_GA_DATE_COL = "FirstGADate" +DISPLAY_NAME_COL = "DisplayName" +SERVICE_NAME_COL = "ServiceName" +REPO_PATH_COL = "RepoPath" +TYPE_COL = "Type" +SUPPORT_COL = "Support" + +# ===================================== +# Helpers for handling bundled releases +# ===================================== + + +@lru_cache(maxsize=None) +def _build_package_path_index() -> dict[str, str]: + """ + Build a one-time index mapping package names to their filesystem paths. + + This scans the sdk/ directory once and caches the result for all subsequent lookups. + """ + all_paths = glob.glob(os.path.join(SDK_DIR, "*", "*")) + # Exclude temp directories like .tox, .venv, __pycache__, etc. + return { + os.path.basename(p): p + for p in all_paths + if os.path.isdir(p) and not os.path.basename(p).startswith((".", "__")) + } + + +def get_package_path(package_name: str) -> Optional[str]: + """Get the filesystem path of an SDK package given its name.""" + path_index = _build_package_path_index() + package_path = path_index.get(package_name) + if not package_path: + logger.warning(f"Package path not found for package: {package_name}") + return None + return package_path + + +def get_bundle_name(package_name: str) -> Optional[str]: + """ + Check bundled release config from package's pyproject.toml file given the package name. + + If bundled, return the bundle name; otherwise, return None. + """ + package_path = get_package_path(package_name) + if not package_path: + logger.warning(f"Cannot determine package path for {package_name}") + return None + parsed = ParsedSetup.from_path(package_path) + if not parsed: + # can't proceed, need to know if it's bundled or not + logger.error(f"Failed to parse setup for package {package_name}") + raise Exception(f"Failed to parse setup for package {package_name}") + + conda_config = parsed.get_conda_config() + + if not conda_config: + if is_stable_on_pypi(package_name): + raise Exception( + f"Stable release package {package_name} needs a conda config" + ) + + logger.warning( + f"No conda config found for package {package_name}, which may be a pre-release" + ) + return None + + if conda_config and "bundle_name" in conda_config: + return conda_config["bundle_name"] + + return None + + +def map_bundle_to_packages( + package_names: list[str], +) -> tuple[dict[str, list[str]], list[str]]: + """Create a mapping of bundle names to their constituent package names. + + :return: Tuple of (bundle_map, failed_packages) where failed_packages are packages that threw exceptions. + """ + logger.info("Mapping bundle names to packages...") + + bundle_map = {} + failed_packages = [] + for package_name in package_names: + logger.debug(f"Processing package for bundle mapping: {package_name}") + try: + bundle_name = get_bundle_name(package_name) + if bundle_name: + logger.debug(f"Bundle name for package {package_name}: {bundle_name}") + bundle_map.setdefault(bundle_name, []).append(package_name) + except Exception as e: + logger.error(f"Failed to get bundle name for {package_name}: {e}") + failed_packages.append(package_name) + continue + + return bundle_map, failed_packages + + +# ===================================== +# Utility functions for parsing data +# ===================================== + + +def parse_csv() -> list[dict[str, str]]: + """Download and parse the Azure SDK Python packages CSV file.""" + try: + logger.info(f"Downloading CSV from {AZURE_SDK_CSV_URL}") + + with urllib.request.urlopen(AZURE_SDK_CSV_URL, timeout=10) as response: + csv_content = response.read().decode("utf-8") + + # Parse the CSV content + csv_reader = csv.DictReader(csv_content.splitlines()) + packages = list(csv_reader) + + logger.info(f"Successfully parsed {len(packages)} packages from CSV") + + return packages + + except Exception as e: + logger.error(f"Failed to download or parse CSV: {e}") + return [] + + +def is_mgmt_package(pkg: dict[str, str]) -> bool: + pkg_name = pkg.get(PACKAGE_COL, "") + _type = pkg.get(TYPE_COL, "") + if _type == "mgmt": + return True + elif _type == "client": + return False + else: + return pkg_name != "azure-mgmt-core" and ( + "mgmt" in pkg_name or "cognitiveservices" in pkg_name + ) + + +def separate_packages_by_type( + packages: list[dict[str, str]], +) -> tuple[list[dict[str, str]], list[dict[str, str]]]: + """Separate packages into data plane and management plane libraries.""" + data_plane_packages = [] + mgmt_plane_packages = [] + + for pkg in packages: + if is_mgmt_package(pkg): + mgmt_plane_packages.append(pkg) + else: + data_plane_packages.append(pkg) + + logger.debug( + f"Separated {len(data_plane_packages)} data plane and {len(mgmt_plane_packages)} management plane packages" + ) + + return (data_plane_packages, mgmt_plane_packages) + + +def package_needs_update( + package_row: dict[str, str], prev_release_date: str, is_new=False +) -> bool: + """ + Check if the package is new or needs version update (i.e., FirstGADate or LatestGADate is after the last release). + + :param package_row: The parsed CSV row for the package. + :param prev_release_date: The date of the previous release in "mm/dd/yyyy" format. + :param is_new: Whether to check for new package (FirstGADate) or outdated package (LatestGADate). + :return: if the package is new or needs an update. + """ + compare_date = ( + package_row.get(FIRST_GA_DATE_COL) + if is_new + else package_row.get(LATEST_GA_DATE_COL) + ) + + logger.debug( + f"Checking {'new package' if is_new else 'outdated package'} for package {package_row.get(PACKAGE_COL)} with against date: {compare_date}" + ) + + if not compare_date: + logger.debug( + f"Package {package_row.get(PACKAGE_COL)} is skipped due to missing {FIRST_GA_DATE_COL if is_new else LATEST_GA_DATE_COL}." + ) + + return False + + try: + # Convert string dates to datetime objects for proper comparison + compare_date = datetime.strptime(compare_date, "%m/%d/%Y") + prev_date = datetime.strptime(prev_release_date, "%m/%d/%Y") + logger.debug( + f"Comparing {package_row.get(PACKAGE_COL)} CompareDate {compare_date} with previous release date {prev_date}" + ) + return compare_date > prev_date + except ValueError as e: + logger.error( + f"Date parsing error for package {package_row.get(PACKAGE_COL)}: {e}" + ) + return False + + +def is_stable_on_pypi(package_name: str) -> bool: + """ + Check if a package has any stable (GA) release on PyPI. + + :param package_name: The name of the package to check. + :return: True if any stable version exists on PyPI, False otherwise. + """ + try: + versions = retrieve_versions_from_pypi(package_name) + if not versions: + logger.warning(f"No versions found on PyPI for {package_name}") + return False + + # Check if any version is stable (not a prerelease) + for v in versions: + if not Version(v).is_prerelease: + logger.debug(f"Package {package_name} has stable version {v}") + return True + + logger.debug(f"Package {package_name} has no stable versions") + return False + + except Exception as e: + logger.warning(f"Failed to check PyPI for {package_name}: {e}") + return False + + +def get_package_data_from_pypi( + package_name: str, +) -> tuple[Optional[str], Optional[str]]: + """Fetch the latest version and download URI for a package from PyPI.""" + try: + client = PyPIClient() + data = client.project(package_name) + + # Get the latest version + latest_version = data["info"]["version"] + if latest_version in data["releases"] and data["releases"][latest_version]: + # Get the source distribution (sdist) if available + files = data["releases"][latest_version] + source_dist = next((f for f in files if f["packagetype"] == "sdist"), None) + if source_dist: + download_url = source_dist["url"] + logger.info( + f"Found download URL for {package_name}=={latest_version}: {download_url}" + ) + return latest_version, download_url + + except Exception as e: + logger.error(f"Failed to fetch download URI from PyPI for {package_name}: {e}") + return None, None + + +def build_package_index(conda_artifacts: list[dict]) -> dict[str, tuple[int, int]]: + """Build an index of package name -> (artifact_idx, checkout_idx) for fast lookups in conda-sdk-client.yml.""" + package_index = {} + + for artifact_idx, artifact in enumerate(conda_artifacts): + if "checkout" in artifact: + for checkout_idx, checkout_item in enumerate(artifact["checkout"]): + package_name = checkout_item.get("package") + if package_name: + package_index[package_name] = (artifact_idx, checkout_idx) + return package_index + + +def get_valid_package_imports(package_name: str) -> list[str]: + """ + Inspect the package's actual module structure and return only valid imports. + + :param package_name: The name of the package (e.g., "azure-mgmt-advisor" or "azure-eventgrid"). + :return: List of valid module names for import (e.g., ["azure.eventgrid", "azure.eventgrid.aio"]). + """ + package_path = get_package_path(package_name) + if not package_path: + logger.warning( + f"Could not find package path for {package_name} to determine imports, using fallback" + ) + return [package_name.replace("-", ".")] + else: + parsed = ParsedSetup.from_path(package_path) + if not parsed or not parsed.namespace: + logger.warning( + f"Could not parse namespace for {package_name}, using fallback" + ) + module_name = package_name.replace("-", ".") + else: + module_name = parsed.namespace + + imports = [module_name] + + # Construct the path to the actual module directory + module_parts = module_name.split(".") + module_dir = os.path.join(package_path, *module_parts) + + if not os.path.isdir(module_dir): + logger.warning( + f"Module directory not found for {package_name} at {module_dir}, using base import only" + ) + return imports + + # Check for common submodules and only add if they exist + submodules_to_check = ["aio", "models", "operations"] + + for submodule_name in submodules_to_check: + submodule_path = os.path.join(module_dir, submodule_name) + if os.path.isdir(submodule_path) and os.path.exists( + os.path.join(submodule_path, "__init__.py") + ): + imports.append(f"{module_name}.{submodule_name}") + + # Check for aio.operations (nested submodule) + aio_operations_path = os.path.join(module_dir, "aio", "operations") + if os.path.isdir(aio_operations_path) and os.path.exists( + os.path.join(aio_operations_path, "__init__.py") + ): + imports.append(f"{module_name}.aio.operations") + + return imports diff --git a/conda/update_conda_files.py b/conda/update_conda_files.py new file mode 100644 index 000000000000..417f45bcbf0b --- /dev/null +++ b/conda/update_conda_files.py @@ -0,0 +1,1134 @@ +"""Update package versions, yml files, release-logs, and changelogs for conda packages.""" + +import os +import argparse +import yaml +import re +import glob +from datetime import datetime +from dateutil.relativedelta import relativedelta +from ci_tools.logging import logger, configure_logging +from ci_tools.parsing import ParsedSetup +from typing import Optional +from conda_helper_functions import ( + parse_csv, + separate_packages_by_type, + package_needs_update, + get_package_data_from_pypi, + build_package_index, + get_package_path, + get_bundle_name, + map_bundle_to_packages, + get_valid_package_imports, + PACKAGE_COL, + VERSION_GA_COL, + LATEST_GA_DATE_COL, + REPO_PATH_COL, + SUPPORT_COL, +) + +# paths +ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +SDK_DIR = os.path.join(ROOT_DIR, "sdk") +CONDA_DIR = os.path.join(ROOT_DIR, "conda") +CONDA_RECIPES_DIR = os.path.join(CONDA_DIR, "conda-recipes") +CONDA_RELEASE_LOGS_DIR = os.path.join(CONDA_DIR, "conda-releaselogs") +CONDA_ENV_PATH = os.path.join(CONDA_RECIPES_DIR, "conda_env.yml") +CONDA_CLIENT_YAML_PATH = os.path.join( + ROOT_DIR, "eng", "pipelines", "templates", "stages", "conda-sdk-client.yml" +) +CONDA_MGMT_META_YAML_PATH = os.path.join(CONDA_RECIPES_DIR, "azure-mgmt", "meta.yaml") + +# constants +RELEASE_PERIOD_MONTHS = 3 + +# packages that should be shipped but are known to be missing from the csv - store version here +PACKAGES_WITH_DOWNLOAD_URI = { + "msal": "", + "msal-extensions": "", +} + + +# ===================================== +# Helpers for updating conda_env.yml +# ===================================== + + +class quoted(str): + pass + + +def quoted_presenter(dumper, data): + """YAML presenter to force quotes around a string.""" + return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="'") + + +def update_conda_version( + target_release_date: Optional[datetime] = None, +) -> tuple[datetime, str]: + """Update the AZURESDK_CONDA_VERSION in conda_env.yml and return the old and new versions. + + Args: + target_release_date: Optional specific release date to use. If None, calculates + the next release date by adding RELEASE_PERIOD_MONTHS to the old version. + """ + + with open(CONDA_ENV_PATH, "r") as file: + conda_env_data = yaml.safe_load(file) + + old_version = conda_env_data["variables"]["AZURESDK_CONDA_VERSION"] + old_date = datetime.strptime(old_version, "%Y.%m.%d") + + if target_release_date: + new_date = target_release_date + else: + new_date = old_date + relativedelta(months=RELEASE_PERIOD_MONTHS) + + # bump version + new_version = new_date.strftime("%Y.%m.%d") + conda_env_data["variables"]["AZURESDK_CONDA_VERSION"] = quoted(new_version) + + yaml.add_representer(quoted, quoted_presenter) + + with open(CONDA_ENV_PATH, "w") as file: + yaml.dump(conda_env_data, file, default_flow_style=False, sort_keys=False) + + logger.info(f"Updated AZURESDK_CONDA_VERSION from {old_version} to {new_version}") + + return old_date, new_version + + +# ===================================== +# Helpers for updating conda-sdk-client.yml +# ===================================== + + +class IndentDumper(yaml.SafeDumper): + """Used to preserve indentation levels in conda-sdk-client.yml.""" + + def increase_indent(self, flow=False, indentless=False): + return super().increase_indent(flow, False) + + +def update_conda_sdk_client_yml( + package_dict: dict[str, dict[str, str]], + packages_to_update: list[str], + new_data_plane_packages: list[str], + new_mgmt_plane_packages: list[str], +) -> list[str]: + """ + Update outdated package versions and add new entries in conda-sdk-client.yml file + + :param package_dict: Dictionary mapping package names to their CSV row data. + :param packages_to_update: List of package names that need version updates. + :param new_data_plane_packages: List of new data plane package names. + :param new_mgmt_plane_packages: List of new management plane package names. + :return: List of package names that were not updated or added and may require manual action. + """ + updated_count = 0 + added_count = 0 + result = [] + + with open(CONDA_CLIENT_YAML_PATH, "r") as file: + conda_client_data = yaml.safe_load(file) + + conda_artifacts = conda_client_data["extends"]["parameters"]["stages"][0]["jobs"][ + 0 + ]["steps"][0]["parameters"]["CondaArtifacts"] + + # === Update outdated package versions === + + logger.info( + f"Detected {len(packages_to_update)} outdated package versions to update in conda-sdk-client.yml" + ) + package_index = build_package_index(conda_artifacts) + + for pkg_name in packages_to_update: + pkg = package_dict.get(pkg_name, {}) + new_version = pkg.get(VERSION_GA_COL) + if pkg_name in package_index: + artifact_idx, checkout_idx = package_index[pkg_name] + checkout_item = conda_artifacts[artifact_idx]["checkout"][checkout_idx] + + if "version" in checkout_item: + old_version = checkout_item.get("version", "") + checkout_item["version"] = new_version + logger.info(f"Updated {pkg_name}: {old_version} -> {new_version}") + updated_count += 1 + else: + logger.warning( + f"Package {pkg_name} has no 'version' field, skipping update" + ) + result.append(pkg_name) + else: + logger.warning( + f"Package {pkg_name} not found in conda-sdk-client.yml, skipping update" + ) + result.append(pkg_name) + + # handle download_uri for packages known to be missing from the csv + for pkg_name in PACKAGES_WITH_DOWNLOAD_URI: + if pkg_name in package_index: + artifact_idx, checkout_idx = package_index[pkg_name] + checkout_item = conda_artifacts[artifact_idx]["checkout"][checkout_idx] + + curr_download_uri = checkout_item.get("download_uri", "") + latest_version, download_uri = get_package_data_from_pypi(pkg_name) + + if not latest_version or not download_uri: + logger.warning( + f"Could not retrieve latest version or download URI for {pkg_name} from PyPI, skipping" + ) + result.append(pkg_name) + continue + + # store retrieved version for release log + PACKAGES_WITH_DOWNLOAD_URI[pkg_name] = latest_version + + if curr_download_uri != download_uri: + # version needs update + logger.info( + f"Package {pkg_name} download_uri mismatch with PyPi, updating {curr_download_uri} to {download_uri}" + ) + # checkout for these packages only has download_uri, no version field + checkout_item["download_uri"] = download_uri + logger.info( + f"Updated download_uri for {pkg_name} with version {latest_version}: {download_uri}" + ) + updated_count += 1 + else: + logger.warning( + f"Package {pkg_name} not found in conda-sdk-client.yml, skipping download_uri update" + ) + result.append(pkg_name) + + # === Add new data plane packages === + + logger.info( + f"Detected {len(new_data_plane_packages)} new data plane packages to add to conda-sdk-client.yml" + ) + + parameters = conda_client_data["parameters"] + + # quick look up for handling bundled package releases + existing_parameter_names = [p.get("name") for p in parameters] + existing_artifact_names = { + a.get("name"): idx for idx, a in enumerate(conda_artifacts) + } + + for package_name in new_data_plane_packages: + pkg = package_dict.get(package_name, {}) + + if package_name in package_index: + logger.warning( + f"New package {package_name} already exists in conda-sdk-client.yml, skipping addition" + ) + result.append(package_name) + continue + + # bundle info is based on pyproject.toml + bundle_name = get_bundle_name(package_name) + + if bundle_name: + # package is part of a bundle + logger.info( + f"Package {package_name} belongs to release bundle {bundle_name}" + ) + release_name = f"release_{bundle_name.replace('-', '_')}" + display_name = bundle_name + else: + # package is released individually + release_name = f"release_{package_name.replace('-', '_')}" + display_name = package_name + + # add new release parameter if not exists + if release_name not in existing_parameter_names: + logger.info(f"Adding new release parameter: {release_name}") + new_parameter = { + "name": release_name, + "displayName": display_name, + "type": "boolean", + "default": True, + } + parameters.append(new_parameter) + existing_parameter_names.append(release_name) + + # add to CondaArtifacts + curr_version = pkg.get(VERSION_GA_COL) + + if not curr_version: + logger.error( + f"Package {package_name} is missing version info, skipping addition" + ) + result.append(package_name) + continue + + checkout_package = {"package": package_name, "version": curr_version} + common_root, service_name = determine_service_info(pkg, bundle_name) + + if package_name in existing_artifact_names: + # individual released package already exists + logger.warning( + f"New package {package_name} already exists in conda-sdk-client.yml, skipping addition" + ) + result.append(package_name) + continue + + if bundle_name and bundle_name in existing_artifact_names: + # bundle already exists, will append packages to it + logger.info( + f"Release bundle {bundle_name} already exists in conda-sdk-client.yml, will append package {package_name} to it" + ) + conda_artifacts[existing_artifact_names[bundle_name]]["checkout"].append( + checkout_package + ) + else: + # no existing artifact, whether bundle or not -> create + new_artifact_entry = { + "name": bundle_name if bundle_name else package_name, + "common_root": common_root, + "service": service_name, + "in_batch": f"${{{{ parameters.{release_name} }}}}", + "checkout": [checkout_package], + } + # append before azure-mgmt entry + conda_artifacts.insert(len(conda_artifacts) - 1, new_artifact_entry) + + added_count += 1 + logger.info(f"Added new data plane package: {package_name}") + + existing_artifact_names[bundle_name if bundle_name else package_name] = ( + len(conda_artifacts) - 2 + ) # new index + + # === Add new mgmt plane packages === + + logger.info( + f"Detected {len(new_mgmt_plane_packages)} new management plane packages to add to conda-sdk-client.yml" + ) + + # assumes azure-mgmt will always be the last CondaArtifacts entry + azure_mgmt_artifact_checkout = conda_artifacts[-1]["checkout"] + + for package_name in new_mgmt_plane_packages: + pkg = package_dict.get(package_name, {}) + + if package_name in package_index: + logger.warning( + f"New package {package_name} already exists in conda-sdk-client.yml, skipping addition" + ) + result.append(package_name) + continue + + new_mgmt_entry = { + "package": package_name, + "version": pkg.get(VERSION_GA_COL), + } + + azure_mgmt_artifact_checkout.append(new_mgmt_entry) + + added_count += 1 + logger.info(f"Added new management plane package: {package_name}") + + # sort mgmt packages alphabetically + azure_mgmt_artifact_checkout.sort(key=lambda x: x["package"]) + + if updated_count > 0 or added_count > 0: + with open(CONDA_CLIENT_YAML_PATH, "w") as file: + yaml.dump( + conda_client_data, + file, + Dumper=IndentDumper, + default_flow_style=False, + sort_keys=False, + indent=2, + width=float("inf"), + ) + logger.info( + f"Successfully updated {updated_count} package versions in conda-sdk-client.yml" + ) + else: + logger.warning("No packages were found in the YAML file to update") + return result + + +# ===================================== +# Helpers for creating conda-recipes//meta.yaml files +# ===================================== + + +def determine_service_info( + pkg: dict[str, str], bundle_name: Optional[str] +) -> tuple[str, str]: + """ + Returns the common root and service name for the given package. + + :param package_name: The name of the package (e.g., "azure-ai-textanalytics"). + :param bundle_name: The name of the bundle/release group the package belongs to, if any. + """ + # defaults + package_name = pkg.get(PACKAGE_COL, "") + service_name = pkg.get(REPO_PATH_COL, "").lower() + common_root = "azure" + + package_path = get_package_path(package_name) + if not service_name and package_path: + service_name = os.path.basename(os.path.dirname(package_path)) + + if bundle_name and service_name: + common_root = f"azure/{service_name}" + + return common_root, service_name + + +def format_requirement(req: str) -> str: + """Format a requirement string for conda meta.yaml.""" + name_unpinned = re.split(r"[>=={{{{ environ.get('AZURESDK_CONDA_VERSION', '0.0.0') }}}}" + + # translate compatible release (~=) to >= for yml + req = req.replace("~=", ">=") + return req + + +def get_package_requirements(parsed: ParsedSetup) -> tuple[list[str], list[str]]: + """Retrieve the host and run requirements for a data plane package meta.yaml.""" + host_requirements = set(["pip", "python"]) + run_requirements = set(["python"]) + + # reqs commonly seen in existing meta.yaml files that aren't always in setup.py or pyproject.toml + for essential_req in ["azure-core", "aiohttp"]: + req_name = format_requirement(essential_req) + host_requirements.add(req_name) + run_requirements.add(req_name) + + package_path = get_package_path(parsed.name) + if not package_path: + logger.error(f"Could not find package path for {parsed.name}") + return list(host_requirements), list(run_requirements) + + # get requirements from setup.py or pyproject.toml + install_reqs = parsed.requires + + for req in install_reqs: + req_name = format_requirement(req) + host_requirements.add(req_name) + run_requirements.add(req_name) + + return list(host_requirements), list(run_requirements) + + +def get_package_metadata( + package_name: str, package_path: str, is_bundle: bool = False +) -> tuple[str, str, str]: + """Extract package metadata for about section in meta.yaml. + + :param package_name: The name of the package or bundle. + :param package_path: The filesystem path to the package. + :param is_bundle: Whether this is a release bundle (affects URL structure). + """ + service_dir = os.path.basename(os.path.dirname(package_path)) + + # For bundles, URL points to service directory; for individual packages, include package name + if is_bundle: + home_url = ( + f"https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/{service_dir}" + ) + else: + home_url = f"https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/{service_dir}/{package_name}" + + summary = f"Microsoft Azure {service_dir.replace('-', ' ').title()} Client Library for Python" + + conda_url = f"https://aka.ms/azsdk/conda/releases/{service_dir}" + description = ( + f"This is the {summary}.\n Please see {conda_url} for version details." + ) + + return home_url, summary, description + + +def generate_data_plane_meta_yaml( + bundle_map: dict[str, list[str]], + package_name: str, + bundle_name: Optional[str], +) -> str: + """ + Generate the meta.yaml content for a data plane package or release group. + """ + # Use bundle_name if available for recipe name and env var derivation + # however, env var name is arbitrary and replaced in conda_functions.py + recipe_name = bundle_name if bundle_name else package_name + src_distr_name = recipe_name.split("-")[-1].upper() + src_distribution_env_var = f"{src_distr_name}_SOURCE_DISTRIBUTION" + + if bundle_name: + # handle grouped packages + logger.info( + f"Generating meta.yaml for release group {bundle_name} including packages: {bundle_map[bundle_name]}" + ) + host_reqs = set() + run_reqs = set() + pkg_imports = [] + + for pkg in bundle_map[bundle_name]: + package_path = get_package_path(pkg) + parsed_setup = ParsedSetup.from_path(package_path) + + pkg_host_reqs, pkg_run_reqs = get_package_requirements(parsed_setup) + host_reqs.update(pkg_host_reqs) + run_reqs.update(pkg_run_reqs) + + # Get valid imports for this package (including .aio if it exists) + pkg_imports.extend(get_valid_package_imports(pkg)) + host_reqs = list(host_reqs) + run_reqs = list(run_reqs) + pkg_imports = list(set(pkg_imports)) # deduplicate + + package_path = get_package_path(bundle_map[bundle_name][0]) + + if not package_path: + logger.error( + f"Could not find package path for {bundle_name} to extract metadata, skipping meta.yaml generation" + ) + return "" + + home_url, summary, description = get_package_metadata( + bundle_name, package_path, is_bundle=True + ) + else: + logger.info(f"Generating meta.yaml for package {package_name}") + package_path = get_package_path(package_name) + + if not package_path: + logger.error( + f"Could not find package path for {package_name} to extract metadata, skipping meta.yaml generation" + ) + return "" + parsed_setup = ParsedSetup.from_path(package_path) + + host_reqs, run_reqs = get_package_requirements(parsed_setup) + # Get valid imports for this package (including .aio if it exists) + pkg_imports = get_valid_package_imports(package_name) + + home_url, summary, description = get_package_metadata( + package_name, package_path + ) + + # Format requirements with proper YAML indentation + host_reqs_str = "\n - ".join(host_reqs) + run_reqs_str = "\n - ".join(run_reqs) + pkg_imports_str = "\n - ".join(pkg_imports) + meta_yaml_content = f"""{{% set name = "{recipe_name}" %}} + +package: + name: "{{{{ name|lower }}}}" + version: {{{{ environ.get('AZURESDK_CONDA_VERSION', '0.0.0') }}}} + +source: + url: {{{{ environ.get('{src_distribution_env_var}', '') }}}} + +build: + noarch: python + number: 0 + script: "{{{{ PYTHON }}}} -m pip install . -vv" + +requirements: + host: + - {host_reqs_str} + run: + - {run_reqs_str} + +test: + imports: + - {pkg_imports_str} + +about: + home: "{home_url}" + license: MIT + license_family: MIT + license_file: + summary: "{summary}" + description: | + {description} + doc_url: + dev_url: + +extra: + recipe-maintainers: + - xiangyan99 +""" + return meta_yaml_content + + +def add_new_data_plane_packages( + bundle_map: dict[str, list[str]], + new_data_plane_names: list[str], +) -> list[str]: + """Create meta.yaml files for new data plane packages and add import tests.""" + if len(new_data_plane_names) == 0: + return [] + + logger.info(f"Adding {len(new_data_plane_names)} new data plane packages") + result = [] + + # bundles are processed once when encountering the first package in that group + bundles_processed = set() + for package_name in new_data_plane_names: + logger.info(f"Adding new data plane meta.yaml for: {package_name}") + + folder_name = package_name + bundle_name = get_bundle_name(package_name) + if bundle_name: + if bundle_name in bundles_processed: + logger.info( + f"Meta.yaml for bundle {bundle_name} already created, skipping {package_name}" + ) + continue + folder_name = bundle_name + + pkg_yaml_path = os.path.join(CONDA_RECIPES_DIR, folder_name, "meta.yaml") + os.makedirs(os.path.dirname(pkg_yaml_path), exist_ok=True) + + try: + meta_yml = generate_data_plane_meta_yaml( + bundle_map, package_name, bundle_name + ) + if bundle_name: + bundles_processed.add(bundle_name) + except Exception as e: + logger.error( + f"Failed to generate meta.yaml content for {package_name} and skipping, error: {e}" + ) + result.append(package_name) + continue + + if not meta_yml: + logger.error( + f"Meta.yaml content for {package_name} is empty, skipping file creation" + ) + result.append(package_name) + continue + + try: + with open(pkg_yaml_path, "w") as f: + f.write(meta_yml) + logger.info(f"Created meta.yaml for {package_name} at {pkg_yaml_path}") + except Exception as e: + logger.error(f"Failed to create meta.yaml for {package_name}: {e}") + result.append(package_name) + + return result + + +# ===================================== +# Helpers for adding new mgmt plane packages to azure-mgmt/meta.yaml +# ===================================== + + +def add_new_mgmt_plane_packages(new_mgmt_plane_names: list[str]) -> list[str]: + """Update azure-mgmt/meta.yaml with new management libraries, and add import tests.""" + if len(new_mgmt_plane_names) == 0: + return [] + logger.info(f"Adding {len(new_mgmt_plane_names)} new management plane packages") + result = [] + + # can't use pyyaml due to jinja2 + with open(CONDA_MGMT_META_YAML_PATH, "r") as file: + content = file.read() + + test_match = re.search( + r"^test:\s*\n\s*imports:(.*?)^(?=\w)", content, re.MULTILINE | re.DOTALL + ) + if not test_match: + logger.error("Could not find 'test: imports:' section in meta.yaml") + result.extend(new_mgmt_plane_names) + return result + + existing_imports_text = test_match.group(1) + existing_imports = [ + line.strip() + for line in existing_imports_text.strip().split("\n") + if line.strip().startswith("-") + ] + + new_imports = [] + for package_name in new_mgmt_plane_names: + if not package_name: + logger.warning("Skipping package with missing name") + continue + + imports = get_valid_package_imports(package_name) + # Format imports for YAML with "- " prefix + formatted = [f"- {imp}" for imp in imports] + new_imports.extend(formatted) + logger.info( + f"Generated {len(imports)} import statements for {package_name}: {formatted}" + ) + + all_imports = list(set(existing_imports + new_imports)) + + # sort alphabetically + all_imports.sort() + + # format imports with proper indentation + formatted_imports = "\n".join(f" {imp}" for imp in all_imports) + + # replace the imports section + new_imports_section = f"test:\n imports:\n{formatted_imports}\n\n" + updated_content = re.sub( + r"^test:\s*\n\s*imports:.*?^(?=\w)", + new_imports_section, + content, + flags=re.MULTILINE | re.DOTALL, + ) + + try: + with open(CONDA_MGMT_META_YAML_PATH, "w") as file: + file.write(updated_content) + except Exception as e: + logger.error(f"Failed to update {CONDA_MGMT_META_YAML_PATH}: {e}") + result.extend(new_mgmt_plane_names) + + logger.info( + f"Added {len(new_mgmt_plane_names)} new management plane packages to meta.yaml" + ) + return result + + +# ===================================== +# Helpers for updating release logs +# ===================================== + + +def update_data_plane_release_logs( + package_dict: dict, + bundle_map: dict[str, list[str]], + new_data_plane_names: list[str], + release_date: str, +) -> list[str]: + """ + Add and update release logs for data plane conda packages. Release log includes versions of all packages for the release + """ + result = [] + + # Update all existing data plane release logs by file + + existing_release_logs = glob.glob(os.path.join(CONDA_RELEASE_LOGS_DIR, "*.md")) + for release_log_path in existing_release_logs: + curr_service_name = os.path.basename(release_log_path).replace(".md", "") + # skip azure-mgmt here + if curr_service_name == "azure-mgmt": + continue + if ( + curr_service_name not in package_dict + and curr_service_name not in bundle_map + and curr_service_name not in PACKAGES_WITH_DOWNLOAD_URI + ): + logger.warning( + f"Existing release log service {curr_service_name} was not found in CSV data, skipping update. It may be deprecated." + ) + result.append(curr_service_name) + continue + + pkg_updates = [] + if curr_service_name in bundle_map: + # handle grouped packages + pkg_names_in_bundle = bundle_map[curr_service_name] + for pkg_name in pkg_names_in_bundle: + pkg = package_dict.get(pkg_name, {}) + version = pkg.get(VERSION_GA_COL) + if version: + pkg_updates.append(f"- {pkg_name}-{version}") + else: + # shouldn't happen, but fallback + logger.error( + f"Package {pkg_name} in group {curr_service_name} is missing version info, it may be deprecated. Skipping in release log update" + ) + result.append(pkg_name) + else: + # handle exception for packages with download_uri + if curr_service_name in PACKAGES_WITH_DOWNLOAD_URI: + version = PACKAGES_WITH_DOWNLOAD_URI[curr_service_name] + if not version: + logger.error( + f"Package {curr_service_name} with download_uri is missing version info, it may be deprecated. Skipping in release log update" + ) + result.append(curr_service_name) + continue + else: + pkg = package_dict.get(curr_service_name, {}) + version = pkg.get(VERSION_GA_COL) + + if version: + pkg_updates.append(f"- {curr_service_name}-{version}") + else: + logger.error( + f"Package {curr_service_name} is missing version info, it may be deprecated. Skipping in release log update" + ) + result.append(curr_service_name) + try: + with open(release_log_path, "r") as f: + existing_content = f.read() + + lines = existing_content.split("\n") + + new_release = f"\n## {release_date}\n\n" + + # check if release is already logged + if new_release in existing_content: + logger.info( + f"Release log for {curr_service_name} already contains entry for {release_date}, overwriting" + ) + # remove existing release section to overwrite + release_idx = lines.index(new_release.strip()) + + ## find next release heading or end of file + next_release_idx = next( + ( + i + for i in range(release_idx + 1, len(lines)) + if lines[i].startswith("## ") + ), + len(lines), + ) + del lines[release_idx:next_release_idx] + + new_release += "### Packages included\n\n" + new_release += "\n".join(pkg_updates) + lines.insert(1, new_release) + + updated_content = "\n".join(lines) + + with open(release_log_path, "w") as f: + f.write(updated_content) + + logger.info(f"Updated release log for {os.path.basename(release_log_path)}") + except Exception as e: + logger.error( + f"Failed to update release log {os.path.basename(release_log_path)}: {e}" + ) + result.append(curr_service_name) + + # Handle brand new packages + for package_name in new_data_plane_names: + pkg = package_dict.get(package_name, {}) + version = pkg.get(VERSION_GA_COL) + + if not version: + logger.warning(f"Skipping {package_name} with missing version") + result.append(package_name) + continue + + bundle_name = get_bundle_name(package_name) + # check for bundle + if bundle_name: + display_name = bundle_name + else: + display_name = package_name + + release_log_path = os.path.join(CONDA_RELEASE_LOGS_DIR, f"{display_name}.md") + + if not os.path.exists(release_log_path): + # Add brand new release log file + logger.info(f"Creating new release log for: {display_name}") + + title_parts = display_name.replace("azure-", "").split("-") + title = " ".join(word.title() for word in title_parts) + + content = f"# Azure {title} client library for Python (conda)\n\n" + content += f"## {release_date}\n\n" + content += "### Packages included\n\n" + + pkg_updates = [] + if bundle_name: + pkg_names_in_log = bundle_map.get(bundle_name, []) + for pkg_name in pkg_names_in_log: + pkg = package_dict.get(pkg_name, {}) + version = pkg.get(VERSION_GA_COL) + pkg_updates.append(f"- {pkg_name}-{version}") + else: + pkg = package_dict.get(package_name, {}) + version = pkg.get(VERSION_GA_COL) + pkg_updates.append(f"- {package_name}-{version}") + content += "\n".join(pkg_updates) + + try: + with open(release_log_path, "w") as f: + f.write(content) + logger.info(f"Created new release log for {display_name}") + except Exception as e: + logger.error(f"Failed to create release log for {display_name}: {e}") + result.append(display_name) + + else: + logger.info( + f"Release log for {display_name} already exists, check that new package {package_name} is included" + ) + + return result + + +def update_mgmt_plane_release_log( + package_dict: dict, + all_mgmt_plane_names: list[str], + release_date: str, +) -> list[str]: + """ + Update azure-mgmt release log. + """ + result = [] + + mgmt_log_path = os.path.join(CONDA_RELEASE_LOGS_DIR, "azure-mgmt.md") + if not os.path.exists(mgmt_log_path): + logger.error("Management plane release log azure-mgmt.md does not exist.") + return all_mgmt_plane_names # all new packages need attention + + pkg_updates = [] + for package_name in all_mgmt_plane_names: + pkg = package_dict.get(package_name, {}) + version = pkg.get(VERSION_GA_COL) + + if not version: + logger.warning( + f"Skipping release log update of {package_name} with missing version" + ) + result.append(package_name) + continue + + pkg_updates.append(f"- {package_name}-{version}") + + try: + with open(mgmt_log_path, "r") as f: + existing_content = f.read() + + lines = existing_content.split("\n") + + new_release = f"\n## {release_date}\n\n" + + # check if release is already logged + if new_release in existing_content: + logger.info( + f"Release log for azure-mgmt already contains entry for {release_date}, overwriting" + ) + # remove existing release section to overwrite + release_idx = lines.index(new_release.strip()) + + ## find next release heading or end of file + next_release_idx = next( + ( + i + for i in range(release_idx + 1, len(lines)) + if lines[i].startswith("## ") + ), + len(lines), + ) + del lines[release_idx:next_release_idx] + + new_release += "### Packages included\n\n" + + new_release += "\n".join(pkg_updates) + lines.insert(1, new_release) + updated_content = "\n".join(lines) + + with open(mgmt_log_path, "w") as f: + f.write(updated_content) + except Exception as e: + logger.error(f"Failed to update azure-mgmt release log: {e}") + return all_mgmt_plane_names + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Update conda package files and versions for release." + ) + parser.add_argument( + "--verbose", + action="store_true", + help="Enable debug logging", + ) + parser.add_argument( + "--release-date", + type=str, + default=None, + help="Release date in 'MM.DD' format (e.g., '03.01', '12.01'). " + "Year is determined automatically. If not provided, the next release date is calculated.", + ) + + args = parser.parse_args() + configure_logging(args) + + # Handle release date + if args.release_date: + try: + current_year = datetime.now().year + target_release_date = datetime.strptime( + f"{current_year}.{args.release_date}", "%Y.%m.%d" + ) + logger.info( + f"Using provided release date: {target_release_date.strftime('%Y.%m.%d')}" + ) + except ValueError as e: + logger.error(f"Invalid release date format '{args.release_date}': {e}") + logger.error("Expected format: 'MM.DD' (e.g., '03.01', '12.01')") + exit(1) + else: + logger.info( + "No release date provided, auto bumping old date by {} months.".format( + RELEASE_PERIOD_MONTHS + ) + ) + target_release_date = None + + old_date, new_version = update_conda_version(target_release_date) + + # Output version as Azure DevOps pipeline variable to use in PR + print(f"##vso[task.setvariable variable=CondaReleaseVersion]{new_version}") + + # convert to mm/dd/yyyy format for comparison with CSV dates + old_version = old_date.strftime("%m/%d/%Y") + + packages = parse_csv() + if not packages: + logger.error("No packages found in CSV data.") + exit(1) + + # Only ship GA packages that are not deprecated + packages = [ + pkg + for pkg in packages + if ( + (pkg.get(VERSION_GA_COL) and pkg.get(LATEST_GA_DATE_COL)) + and not pkg.get(SUPPORT_COL) == "deprecated" + ) + ] + logger.info(f"Filtered to {len(packages)} GA packages") + + data_pkgs, mgmt_pkgs = separate_packages_by_type(packages) + + outdated_data_plane_names = [ + pkg.get(PACKAGE_COL, "") + for pkg in data_pkgs + if package_needs_update(pkg, old_version, is_new=False) + ] + new_data_plane_names = [ + pkg.get(PACKAGE_COL, "") + for pkg in data_pkgs + if package_needs_update(pkg, old_version, is_new=True) + ] + outdated_mgmt_plane_names = [ + pkg.get(PACKAGE_COL, "") + for pkg in mgmt_pkgs + if package_needs_update(pkg, old_version, is_new=False) + ] + new_mgmt_plane_names = [ + pkg.get(PACKAGE_COL, "") + for pkg in mgmt_pkgs + if package_needs_update(pkg, old_version, is_new=True) + ] + + # don't overlap new packages with outdated packages + outdated_data_plane_names = [ + name for name in outdated_data_plane_names if name not in new_data_plane_names + ] + outdated_mgmt_plane_names = [ + name for name in outdated_mgmt_plane_names if name not in new_mgmt_plane_names + ] + + # map package name to csv row for easy lookup + package_dict = {pkg.get(PACKAGE_COL, ""): pkg for pkg in packages} + + outdated_package_names = outdated_data_plane_names + outdated_mgmt_plane_names + + # update conda-sdk-client.yml + conda_sdk_client_pkgs_result = update_conda_sdk_client_yml( + package_dict, outdated_package_names, new_data_plane_names, new_mgmt_plane_names + ) + + # pre-process bundled data packages to minimize file writes for new data plane packages, + # and release logs (mgmt packages are always bundled together) + bundle_map, bundle_failed_pkgs = map_bundle_to_packages( + [pkg.get(PACKAGE_COL, "") for pkg in data_pkgs] + ) + logger.info( + f"Identified {len(bundle_map)} release bundles from package data: {bundle_map}" + ) + + # handle new data plane libraries + new_data_plane_results = add_new_data_plane_packages( + bundle_map, new_data_plane_names + ) + + # handle new mgmt plane libraries + new_mgmt_plane_results = add_new_mgmt_plane_packages(new_mgmt_plane_names) + + # add/update release logs + data_plane_release_log_results = update_data_plane_release_logs( + package_dict, bundle_map, new_data_plane_names, new_version + ) + + all_mgmt_plane_names = [pkg.get(PACKAGE_COL, "") for pkg in mgmt_pkgs] + + mgmt_plane_release_log_results = update_mgmt_plane_release_log( + package_dict, all_mgmt_plane_names, new_version + ) + + print("=== REPORT ===") + + if conda_sdk_client_pkgs_result: + print( + "The following packages may require manual adjustments in conda-sdk-client.yml:" + ) + for pkg_name in conda_sdk_client_pkgs_result: + print(f"- {pkg_name}") + + if new_data_plane_results: + print( + "\nThe following new data plane packages may require manual meta.yaml creation or adjustments:" + ) + for pkg_name in new_data_plane_results: + print(f"- {pkg_name}") + + if new_mgmt_plane_results: + print( + "\nThe following new management plane packages may require manual adjustments in azure-mgmt/meta.yaml:" + ) + for pkg_name in new_mgmt_plane_results: + print(f"- {pkg_name}") + + if data_plane_release_log_results: + print( + "\nThe following data plane packages may require manual adjustments in release logs:" + ) + for pkg_name in data_plane_release_log_results: + print(f"- {pkg_name}") + + if mgmt_plane_release_log_results: + print( + "\nThe following management plane packages may require manual adjustments in azure-mgmt release log:" + ) + for pkg_name in mgmt_plane_release_log_results: + print(f"- {pkg_name}") + + if bundle_failed_pkgs: + print( + "\nThe following packages errored when constructing bundle map, they may need a [tool.azure-sdk-conda] section in their pyproject.toml for proper release grouping, and may have been improperly individually processed." + ) + for pkg_name in bundle_failed_pkgs: + print(f"- {pkg_name}") + + if len(new_data_plane_names) > 0: + print("\n=== Manual Steps for New Data Plane Packages ===") + print( + "- A dummy placeholder library needs to be requested on Conda for new data plane packages." + ) + print("- A new AKA link needs to be created for each new release log.") + print( + "\nSee the generated PR description for further details. The new data plane package names are:" + ) + for pkg_name in new_data_plane_names: + print(f"{pkg_name}") diff --git a/eng/pipelines/conda-update-pipeline.yml b/eng/pipelines/conda-update-pipeline.yml new file mode 100644 index 000000000000..c7a4a6db1d66 --- /dev/null +++ b/eng/pipelines/conda-update-pipeline.yml @@ -0,0 +1,121 @@ +trigger: none +pr: none + +parameters: + - name: releaseDate + displayName: Release Date (MM.DD) + type: string + default: 'auto' + values: + - auto + - 03.01 + - 06.01 + - 09.01 + - 12.01 + - name: dryRun + displayName: Dry Run (skip PR submission) + type: boolean + default: false + +# Scheduled to run a week before each quarterly release +schedules: + - cron: "0 0 24 11 *" + displayName: Pre-December Quarterly Release + branches: + include: + - main + always: true + - cron: "0 0 22 2 *" + displayName: Pre-March Quarterly Release + branches: + include: + - main + always: true + - cron: "0 0 25 5 *" + displayName: Pre-June Quarterly Release + branches: + include: + - main + always: true + - cron: "0 0 25 8 *" + displayName: Pre-September Quarterly Release + branches: + include: + - main + always: true + +extends: + template: /eng/pipelines/templates/stages/1es-redirect.yml + parameters: + stages: + - stage: UpdateCondaFiles + displayName: Update Conda Files + + jobs: + - job: UpdateCondaFilesJob + timeoutInMinutes: 90 + displayName: Update Conda Files and Submit PR + variables: + - template: /eng/pipelines/templates/variables/globals.yml + - name: ReleaseDate + ${{ if eq(parameters.releaseDate, 'auto') }}: + ${{ if contains(variables['Build.CronSchedule.DisplayName'], 'December') }}: + value: '12.01' + ${{ elseif contains(variables['Build.CronSchedule.DisplayName'], 'March') }}: + value: '03.01' + ${{ elseif contains(variables['Build.CronSchedule.DisplayName'], 'June') }}: + value: '06.01' + ${{ elseif contains(variables['Build.CronSchedule.DisplayName'], 'September') }}: + value: '09.01' + ${{ else }}: + value: 'Unknown' + ${{ else }}: + value: ${{ parameters.releaseDate }} + + pool: + name: azsdk-pool + image: ubuntu-24.04 + os: linux + + steps: + - checkout: self + persistCredentials: true + + - task: UsePythonVersion@0 + displayName: 'Use Python 3.11' + inputs: + versionSpec: '3.11' + + - script: | + python -m pip install --upgrade pip + python -m pip install "eng/tools/azure-sdk-tools[build]" + python -m pip install python-dateutil + displayName: 'Prep Environment' + + - script: | + if [ "$(ReleaseDate)" != "Unknown" ]; then + python conda/update_conda_files.py --release-date "$(ReleaseDate)" + else + python conda/update_conda_files.py + fi + displayName: 'Update Conda Files' + + - ${{ if eq(parameters.dryRun, false) }}: + - template: /eng/common/pipelines/templates/steps/create-pull-request.yml + parameters: + PRBranchName: conda-update-$(Build.BuildId) + CommitMsg: 'Update conda files for $(CondaReleaseVersion) release' + PRTitle: 'Conda Release $(CondaReleaseVersion) generated by $(Build.BuildId)' + PRBody: | + This PR was automatically generated to update Conda files for a new release. + + - Updates outdated package versions in conda-sdk-client.yml + - Adds new packages to conda-sdk-client.yml + - Adds/updates yamls and changelogs + + ## Next Steps + - [ ] For new data plane packages, submit this form to create a private dummy library placeholder in Conda before uploading a release: https://forms.office.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbR180k2XpSUFBtXHTh8-jMUlUNlA1MFpZOVhZME1aNU1EU1Y3SjZRU0JNRC4u + - [ ] After this PR is merged and succeeds the Conda build, approve the pipeline to upload the releases to Conda + - [ ] After upload, delete the dummy libraries and make the new packages publicly available in Conda. + - [ ] Create an AKA link for new release logs here: http://aka.ms/ + BaseBranchName: main diff --git a/eng/pipelines/templates/stages/conda-sdk-client.yml b/eng/pipelines/templates/stages/conda-sdk-client.yml index 98b6811d2600..68e89ba8f7f0 100644 --- a/eng/pipelines/templates/stages/conda-sdk-client.yml +++ b/eng/pipelines/templates/stages/conda-sdk-client.yml @@ -905,5 +905,3 @@ extends: version: 1.0.0 - package: azure-mgmt-workloadssapvirtualinstance version: 1.0.0 - - diff --git a/eng/tools/azure-sdk-tools/ci_tools/parsing/parse_functions.py b/eng/tools/azure-sdk-tools/ci_tools/parsing/parse_functions.py index 0c5bb8b5ebab..5c8504ba4fbb 100644 --- a/eng/tools/azure-sdk-tools/ci_tools/parsing/parse_functions.py +++ b/eng/tools/azure-sdk-tools/ci_tools/parsing/parse_functions.py @@ -16,6 +16,7 @@ # this assumes the presence of "packaging" from packaging.requirements import Requirement +from packaging.version import Version, InvalidVersion from setuptools import Extension from ci_tools.variables import str_to_bool @@ -351,6 +352,9 @@ def from_path(cls, parse_directory_or_file: str): def get_build_config(self) -> Optional[Dict[str, Any]]: return get_build_config(self.folder) + def get_conda_config(self) -> Optional[Dict[str, Any]]: + return get_conda_config(self.folder) + def get_config_setting(self, setting: str, default: Any = True) -> Any: return get_config_setting(self.folder, setting, default) @@ -383,7 +387,7 @@ def __str__(self): def update_build_config(package_path: str, new_build_config: Dict[str, Any]) -> Dict[str, Any]: """ - Attempts to update a pyproject.toml's [tools.azure-sdk-tools] section with a new check configuration. + Attempts to update a pyproject.toml's [tool.azure-sdk-tools] section with a new check configuration. This function can only append or override existing check values. It cannot delete them. """ @@ -454,6 +458,27 @@ def get_build_config(package_path: str) -> Optional[Dict[str, Any]]: return {} +def get_conda_config(package_path: str) -> Optional[Dict[str, Any]]: + """ + Attempts to retrieve all values within [tool.azure-sdk-conda] section of a pyproject.toml. + """ + if os.path.isfile(package_path): + package_path = os.path.dirname(package_path) + + toml_file = os.path.join(package_path, "pyproject.toml") + + if os.path.exists(toml_file): + try: + with open(toml_file, "rb") as f: + toml_dict = toml.load(f) + if "tool" in toml_dict: + tool_configs = toml_dict["tool"] + if "azure-sdk-conda" in tool_configs: + return tool_configs["azure-sdk-conda"] + except: + return {} + + def get_ci_config(package_path: str) -> Optional[Dict[str, Any]]: """ Attempts to retrieve the parsed toml content of a CI.yml associated with this package. diff --git a/sdk/ai/azure-ai-voicelive/pyproject.toml b/sdk/ai/azure-ai-voicelive/pyproject.toml index 3e2540ab6842..02fb44dc7667 100644 --- a/sdk/ai/azure-ai-voicelive/pyproject.toml +++ b/sdk/ai/azure-ai-voicelive/pyproject.toml @@ -76,4 +76,7 @@ exclude = [ pytyped = ["py.typed"] [tool.pytest.ini_options] asyncio_default_fixture_loop_scope = "function" -asyncio_mode = "auto" \ No newline at end of file +asyncio_mode = "auto" + +[tool.azure-sdk-conda] +in_bundle = false \ No newline at end of file From 21387f1976a22aae98eec2a5a5260f3c80d0772d Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 6 Feb 2026 14:52:56 -0800 Subject: [PATCH 81/84] Add conda bundle configuration to 10 SDK packages (#45042) * Add [tool.azure-sdk-conda] section to 10 package pyproject.toml files Co-authored-by: JennyPng <63012604+JennyPng@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: JennyPng <63012604+JennyPng@users.noreply.github.com> --- sdk/ai/azure-ai-projects/pyproject.toml | 3 +++ sdk/attestation/azure-security-attestation/pyproject.toml | 3 +++ .../azure-ai-language-conversations/pyproject.toml | 3 +++ .../azure-ai-language-questionanswering/pyproject.toml | 3 +++ .../azure-confidentialledger/pyproject.toml | 3 +++ sdk/identity/azure-identity-broker/pyproject.toml | 3 +++ sdk/identity/azure-identity/pyproject.toml | 3 +++ sdk/servicebus/azure-servicebus/pyproject.toml | 5 ++++- sdk/translation/azure-ai-translation-text/pyproject.toml | 3 +++ sdk/webpubsub/azure-messaging-webpubsubclient/pyproject.toml | 3 +++ 10 files changed, 31 insertions(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/pyproject.toml b/sdk/ai/azure-ai-projects/pyproject.toml index 7f55115918ef..73bf11ce0688 100644 --- a/sdk/ai/azure-ai-projects/pyproject.toml +++ b/sdk/ai/azure-ai-projects/pyproject.toml @@ -67,3 +67,6 @@ pytyped = ["py.typed"] [tool.azure-sdk-build] verifytypes = false +[tool.azure-sdk-conda] +in_bundle = false + diff --git a/sdk/attestation/azure-security-attestation/pyproject.toml b/sdk/attestation/azure-security-attestation/pyproject.toml index 3fe4fb7254eb..20eb14b3b63c 100644 --- a/sdk/attestation/azure-security-attestation/pyproject.toml +++ b/sdk/attestation/azure-security-attestation/pyproject.toml @@ -63,3 +63,6 @@ pytyped = ["py.typed"] [tool.azure-sdk-build] pyright = false ci_enabled = false + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/cognitivelanguage/azure-ai-language-conversations/pyproject.toml b/sdk/cognitivelanguage/azure-ai-language-conversations/pyproject.toml index 7ec2b439e6be..1699d92773ee 100644 --- a/sdk/cognitivelanguage/azure-ai-language-conversations/pyproject.toml +++ b/sdk/cognitivelanguage/azure-ai-language-conversations/pyproject.toml @@ -63,3 +63,6 @@ pytyped = ["py.typed"] [packaging] auto_update = false + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/pyproject.toml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/pyproject.toml index 6195829bfcb2..fc08b2e41ab4 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/pyproject.toml +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/pyproject.toml @@ -58,3 +58,6 @@ exclude = [ [tool.setuptools.package-data] pytyped = ["py.typed"] + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/confidentialledger/azure-confidentialledger/pyproject.toml b/sdk/confidentialledger/azure-confidentialledger/pyproject.toml index f21c0681cf8f..90bafd3f2522 100644 --- a/sdk/confidentialledger/azure-confidentialledger/pyproject.toml +++ b/sdk/confidentialledger/azure-confidentialledger/pyproject.toml @@ -63,3 +63,6 @@ pytyped = ["py.typed"] [tool.azure-sdk-build] pyright = false + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/identity/azure-identity-broker/pyproject.toml b/sdk/identity/azure-identity-broker/pyproject.toml index 808055951185..463cc7d4e174 100644 --- a/sdk/identity/azure-identity-broker/pyproject.toml +++ b/sdk/identity/azure-identity-broker/pyproject.toml @@ -44,3 +44,6 @@ pytyped = ["py.typed"] [tool.azure-sdk-build] pyright = false black = true + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/identity/azure-identity/pyproject.toml b/sdk/identity/azure-identity/pyproject.toml index 557d2c15d1c7..12f18848e5ea 100644 --- a/sdk/identity/azure-identity/pyproject.toml +++ b/sdk/identity/azure-identity/pyproject.toml @@ -49,3 +49,6 @@ pytyped = ["py.typed"] pyright = false verifytypes = true black = true + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/servicebus/azure-servicebus/pyproject.toml b/sdk/servicebus/azure-servicebus/pyproject.toml index 27bff06b8758..4d1d9557b729 100644 --- a/sdk/servicebus/azure-servicebus/pyproject.toml +++ b/sdk/servicebus/azure-servicebus/pyproject.toml @@ -47,4 +47,7 @@ pyright = false type_check_samples = true verifytypes = true pylint = true -black = false \ No newline at end of file +black = false + +[tool.azure-sdk-conda] +in_bundle = false \ No newline at end of file diff --git a/sdk/translation/azure-ai-translation-text/pyproject.toml b/sdk/translation/azure-ai-translation-text/pyproject.toml index 400681a29b03..b9f2fa74378f 100644 --- a/sdk/translation/azure-ai-translation-text/pyproject.toml +++ b/sdk/translation/azure-ai-translation-text/pyproject.toml @@ -66,3 +66,6 @@ pylint = true type_check_samples = true verifytypes = true pyright = true + +[tool.azure-sdk-conda] +in_bundle = false diff --git a/sdk/webpubsub/azure-messaging-webpubsubclient/pyproject.toml b/sdk/webpubsub/azure-messaging-webpubsubclient/pyproject.toml index d7cbd8f4139a..1589d68a230d 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubclient/pyproject.toml +++ b/sdk/webpubsub/azure-messaging-webpubsubclient/pyproject.toml @@ -57,3 +57,6 @@ pytyped = ["py.typed"] [tool.azure-sdk-build] pylint = false pyright = false + +[tool.azure-sdk-conda] +in_bundle = false From 6a7dcf8591c98f71391dd7d3c03f8e3a91d998f9 Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Fri, 6 Feb 2026 17:47:07 -0800 Subject: [PATCH 82/84] [Identity] Update HttpRequest class usage (#44993) This updates HttpRequest imports from azure.core.transport to use the HttpRequest class from azure.core.rest. The HttpRequest class from azure.core.transport is considered legacy. Updating this also enables the transports from `corehttp` to be used with azure-identity, including the `HttpxTransports`. Signed-off-by: Paul Van Eck --- sdk/identity/azure-identity/CHANGELOG.md | 1 + .../identity/_credentials/app_service.py | 6 ++-- .../azure/identity/_credentials/azure_arc.py | 6 ++-- .../azure/identity/_credentials/azure_ml.py | 6 ++-- .../identity/_credentials/cloud_shell.py | 5 ++-- .../azure/identity/_credentials/imds.py | 6 ++-- .../identity/_credentials/service_fabric.py | 8 +++--- .../azure/identity/_internal/aad_client.py | 2 +- .../identity/_internal/aad_client_base.py | 2 +- .../_internal/managed_identity_client.py | 2 +- .../azure/identity/_internal/msal_client.py | 28 ++++++++----------- .../identity/aio/_internal/aad_client.py | 2 +- .../bearer_token_auth_policy.py | 2 +- .../tests/test_imds_credential.py | 2 +- .../tests/test_imds_credential_async.py | 2 +- .../tests/test_managed_identity_client.py | 2 +- .../test_managed_identity_client_async.py | 2 +- 17 files changed, 36 insertions(+), 48 deletions(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index a164938150c9..5c0f944d3b57 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -18,6 +18,7 @@ ### Other Changes - Bumped minimum dependency on `msal` to `>=1.31.0`. +- Replace instances of `azure.core.pipeline.transport.HttpRequest` with `azure.core.rest.HttpRequest`. ([#44993](https://github.com/Azure/azure-sdk-for-python/pull/44993)) ## 1.26.0b1 (2025-11-07) diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/app_service.py b/sdk/identity/azure-identity/azure/identity/_credentials/app_service.py index ff4531cb8525..4f8bca54380f 100644 --- a/sdk/identity/azure-identity/azure/identity/_credentials/app_service.py +++ b/sdk/identity/azure-identity/azure/identity/_credentials/app_service.py @@ -5,7 +5,7 @@ import functools import os from typing import Optional, Dict, Any -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from .._constants import EnvironmentVariables from .._internal.msal_managed_identity_client import MsalManagedIdentityClient @@ -34,6 +34,4 @@ def _get_client_args(**kwargs: Any) -> Optional[Dict]: def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: - request = HttpRequest("GET", url) - request.format_parameters(dict({"api-version": "2019-08-01", "resource": scope}, **identity_config)) - return request + return HttpRequest("GET", url, params=dict({"api-version": "2019-08-01", "resource": scope}, **identity_config)) diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/azure_arc.py b/sdk/identity/azure-identity/azure/identity/_credentials/azure_arc.py index 765af7bc7cfe..b43edaecb7f9 100644 --- a/sdk/identity/azure-identity/azure/identity/_credentials/azure_arc.py +++ b/sdk/identity/azure-identity/azure/identity/_credentials/azure_arc.py @@ -7,7 +7,7 @@ from typing import Dict from azure.core.exceptions import ClientAuthenticationError -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from azure.core.pipeline.policies import HTTPPolicy from azure.core.pipeline import PipelineRequest, PipelineResponse @@ -27,9 +27,7 @@ def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: "DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set." ) - request = HttpRequest("GET", url) - request.format_parameters(dict({"api-version": "2020-06-01", "resource": scope}, **identity_config)) - return request + return HttpRequest("GET", url, params=dict({"api-version": "2020-06-01", "resource": scope}, **identity_config)) def _get_secret_key(response: PipelineResponse) -> str: diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/azure_ml.py b/sdk/identity/azure-identity/azure/identity/_credentials/azure_ml.py index bed313195c2c..3572ca624cbc 100644 --- a/sdk/identity/azure-identity/azure/identity/_credentials/azure_ml.py +++ b/sdk/identity/azure-identity/azure/identity/_credentials/azure_ml.py @@ -6,7 +6,7 @@ import os from typing import Optional, Dict -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from .._constants import EnvironmentVariables from .._internal.msal_managed_identity_client import MsalManagedIdentityClient @@ -39,9 +39,7 @@ def _get_client_args(**kwargs) -> Optional[Dict]: def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: - request = HttpRequest("GET", url) - request.format_parameters(dict({"api-version": "2017-09-01", "resource": scope}, **identity_config)) - return request + return HttpRequest("GET", url, params=dict({"api-version": "2017-09-01", "resource": scope}, **identity_config)) def _parse_expires_on(content: Dict) -> None: diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/cloud_shell.py b/sdk/identity/azure-identity/azure/identity/_credentials/cloud_shell.py index 61aefdb0c28b..41d8fb82f929 100644 --- a/sdk/identity/azure-identity/azure/identity/_credentials/cloud_shell.py +++ b/sdk/identity/azure-identity/azure/identity/_credentials/cloud_shell.py @@ -6,7 +6,7 @@ import os from typing import Any, Optional, Dict, Mapping -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from .._constants import EnvironmentVariables from .._internal import within_dac @@ -43,5 +43,4 @@ def get_unavailable_message(self, desc: str = "") -> str: def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: - request = HttpRequest("POST", url, data=dict({"resource": scope}, **identity_config)) - return request + return HttpRequest("POST", url, data=dict({"resource": scope}, **identity_config)) diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/imds.py b/sdk/identity/azure-identity/azure/identity/_credentials/imds.py index b1e82bb88052..ece23fbc4419 100644 --- a/sdk/identity/azure-identity/azure/identity/_credentials/imds.py +++ b/sdk/identity/azure-identity/azure/identity/_credentials/imds.py @@ -8,7 +8,7 @@ from azure.core.pipeline import PipelineResponse from azure.core.exceptions import ClientAuthenticationError, HttpResponseError -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from azure.core.credentials import AccessTokenInfo from azure.core.pipeline.policies import RetryPolicy @@ -60,9 +60,7 @@ def _get_request(scope: str, identity_config: Dict) -> HttpRequest: os.environ.get(EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST, IMDS_AUTHORITY).strip("/") + IMDS_TOKEN_PATH ) - request = HttpRequest("GET", url) - request.format_parameters(dict({"api-version": "2018-02-01", "resource": scope}, **identity_config)) - return request + return HttpRequest("GET", url, params=dict({"api-version": "2018-02-01", "resource": scope}, **identity_config)) def _check_forbidden_response(ex: HttpResponseError) -> None: diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/service_fabric.py b/sdk/identity/azure-identity/azure/identity/_credentials/service_fabric.py index c3fe591cc5d2..b79234ee4adf 100644 --- a/sdk/identity/azure-identity/azure/identity/_credentials/service_fabric.py +++ b/sdk/identity/azure-identity/azure/identity/_credentials/service_fabric.py @@ -8,7 +8,7 @@ from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions from azure.core.exceptions import ClientAuthenticationError -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from .._constants import EnvironmentVariables from .._internal.msal_managed_identity_client import MsalManagedIdentityClient @@ -55,6 +55,6 @@ def _get_client_args(**kwargs: Any) -> Optional[Dict]: def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: - request = HttpRequest("GET", url) - request.format_parameters(dict({"api-version": "2019-07-01-preview", "resource": scope}, **identity_config)) - return request + return HttpRequest( + "GET", url, params=dict({"api-version": "2019-07-01-preview", "resource": scope}, **identity_config) + ) diff --git a/sdk/identity/azure-identity/azure/identity/_internal/aad_client.py b/sdk/identity/azure-identity/azure/identity/_internal/aad_client.py index 216f601f3869..d4d9ff0ae536 100644 --- a/sdk/identity/azure-identity/azure/identity/_internal/aad_client.py +++ b/sdk/identity/azure-identity/azure/identity/_internal/aad_client.py @@ -7,7 +7,7 @@ from azure.core.credentials import AccessTokenInfo from azure.core.pipeline import Pipeline -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from .aad_client_base import AadClientBase from .aadclient_certificate import AadClientCertificate from .pipeline import build_pipeline diff --git a/sdk/identity/azure-identity/azure/identity/_internal/aad_client_base.py b/sdk/identity/azure-identity/azure/identity/_internal/aad_client_base.py index b66cb15ab1b1..e359cc50af8a 100644 --- a/sdk/identity/azure-identity/azure/identity/_internal/aad_client_base.py +++ b/sdk/identity/azure-identity/azure/identity/_internal/aad_client_base.py @@ -13,7 +13,7 @@ from azure.core.pipeline import PipelineResponse from azure.core.pipeline.policies import ContentDecodePolicy -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from azure.core.credentials import AccessTokenInfo from azure.core.exceptions import ClientAuthenticationError from .utils import get_default_authority, normalize_authority, resolve_tenant diff --git a/sdk/identity/azure-identity/azure/identity/_internal/managed_identity_client.py b/sdk/identity/azure-identity/azure/identity/_internal/managed_identity_client.py index 44b318e6bb19..d305ffe33abc 100644 --- a/sdk/identity/azure-identity/azure/identity/_internal/managed_identity_client.py +++ b/sdk/identity/azure-identity/azure/identity/_internal/managed_identity_client.py @@ -12,7 +12,7 @@ from azure.core.exceptions import ClientAuthenticationError, DecodeError from azure.core.pipeline.policies import ContentDecodePolicy from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from .. import CredentialUnavailableError from .._internal import _scopes_to_resource from .._internal.pipeline import build_pipeline diff --git a/sdk/identity/azure-identity/azure/identity/_internal/msal_client.py b/sdk/identity/azure-identity/azure/identity/_internal/msal_client.py index 0fc6cdbef569..b09bcbb6fc9e 100644 --- a/sdk/identity/azure-identity/azure/identity/_internal/msal_client.py +++ b/sdk/identity/azure-identity/azure/identity/_internal/msal_client.py @@ -7,10 +7,7 @@ from azure.core.exceptions import ClientAuthenticationError from azure.core.pipeline.policies import ContentDecodePolicy -from azure.core.pipeline.transport import ( # pylint:disable=no-legacy-azure-core-http-response-import - HttpRequest, - HttpResponse, -) +from azure.core.rest import HttpRequest, HttpResponse from azure.core.pipeline import PipelineResponse from .pipeline import build_pipeline @@ -22,7 +19,7 @@ class MsalResponse: """Wraps HttpResponse according to msal.oauth2cli.http. :param response: The response to wrap. - :type response: ~azure.core.pipeline.transport.HttpResponse + :type response: ~azure.core.rest.HttpResponse """ def __init__(self, response: PipelineResponse) -> None: @@ -84,19 +81,20 @@ def post( **kwargs: Any ) -> MsalResponse: # pylint:disable=unused-argument - request = HttpRequest("POST", url, headers=headers) - if params: - request.format_parameters(params) + request_headers = dict(headers) if headers else {} + content: Optional[bytes] = None + request_data: Optional[Dict[str, str]] = None + if data: if isinstance(data, dict): - request.headers["Content-Type"] = "application/x-www-form-urlencoded" - request.set_formdata_body(data) + request_headers["Content-Type"] = "application/x-www-form-urlencoded" + request_data = data elif isinstance(data, str): - body_bytes = data.encode("utf-8") - request.set_bytes_body(body_bytes) + content = data.encode("utf-8") else: raise ValueError('expected "data" to be text or a dict') + request = HttpRequest("POST", url, headers=request_headers, params=params, data=request_data, content=content) response = self._pipeline.run(request, stream=False, retry_on_methods=_POST) self._store_auth_error(response) return MsalResponse(response) @@ -105,9 +103,7 @@ def get( self, url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, **kwargs: Any ) -> MsalResponse: # pylint:disable=unused-argument - request = HttpRequest("GET", url, headers=headers) - if params: - request.format_parameters(params) + request = HttpRequest("GET", url, headers=headers, params=params) response = self._pipeline.run(request, stream=False) self._store_auth_error(response) return MsalResponse(response) @@ -118,7 +114,7 @@ def get_error_response(self, msal_result: Dict) -> Optional[HttpResponse]: :param msal_result: The result of an MSAL request. :type msal_result: dict :return: The HTTP response associated with the error, if any. - :rtype: ~azure.core.pipeline.transport.HttpResponse or None + :rtype: ~azure.core.rest.HttpResponse or None """ error_code, response = getattr(self._local, "error", (None, None)) if response and error_code == msal_result.get("error"): diff --git a/sdk/identity/azure-identity/azure/identity/aio/_internal/aad_client.py b/sdk/identity/azure-identity/azure/identity/aio/_internal/aad_client.py index 7b99f85ac912..bfe2625f24da 100644 --- a/sdk/identity/azure-identity/azure/identity/aio/_internal/aad_client.py +++ b/sdk/identity/azure-identity/azure/identity/aio/_internal/aad_client.py @@ -8,7 +8,7 @@ from azure.core.credentials import AccessTokenInfo from azure.core.pipeline import AsyncPipeline from azure.core.pipeline.policies import AsyncHTTPPolicy, SansIOHTTPPolicy -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from ..._internal import AadClientCertificate from ..._internal import AadClientBase from ..._internal.pipeline import build_async_pipeline diff --git a/sdk/identity/azure-identity/tests/perfstress_tests/bearer_token_auth_policy.py b/sdk/identity/azure-identity/tests/perfstress_tests/bearer_token_auth_policy.py index bb59a93c212c..48fdb57a13b6 100644 --- a/sdk/identity/azure-identity/tests/perfstress_tests/bearer_token_auth_policy.py +++ b/sdk/identity/azure-identity/tests/perfstress_tests/bearer_token_auth_policy.py @@ -12,7 +12,7 @@ from azure.core.credentials import AccessToken from azure.core.pipeline import AsyncPipeline, Pipeline from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy, BearerTokenCredentialPolicy -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest class BearerTokenPolicyTest(PerfStressTest): diff --git a/sdk/identity/azure-identity/tests/test_imds_credential.py b/sdk/identity/azure-identity/tests/test_imds_credential.py index a1d5ff3fa76f..1c66c2abad7b 100644 --- a/sdk/identity/azure-identity/tests/test_imds_credential.py +++ b/sdk/identity/azure-identity/tests/test_imds_credential.py @@ -16,7 +16,7 @@ ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.policies import RetryPolicy -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.rest import HttpRequest, HttpResponse import pytest from helpers import mock, mock_response, Request, validating_transport, GET_TOKEN_METHODS diff --git a/sdk/identity/azure-identity/tests/test_imds_credential_async.py b/sdk/identity/azure-identity/tests/test_imds_credential_async.py index 051f360fa660..edc92989e415 100644 --- a/sdk/identity/azure-identity/tests/test_imds_credential_async.py +++ b/sdk/identity/azure-identity/tests/test_imds_credential_async.py @@ -17,7 +17,7 @@ from azure.identity._credentials.imds import PIPELINE_SETTINGS from azure.core.pipeline import PipelineResponse from azure.core.pipeline.policies import AsyncRetryPolicy -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.rest import HttpRequest, HttpResponse import pytest from helpers import mock_response, Request, GET_TOKEN_METHODS diff --git a/sdk/identity/azure-identity/tests/test_managed_identity_client.py b/sdk/identity/azure-identity/tests/test_managed_identity_client.py index 0e9636ae047f..a96c7472f4c3 100644 --- a/sdk/identity/azure-identity/tests/test_managed_identity_client.py +++ b/sdk/identity/azure-identity/tests/test_managed_identity_client.py @@ -6,7 +6,7 @@ import time from azure.core.exceptions import ClientAuthenticationError, ServiceRequestError -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from azure.identity._internal.managed_identity_client import ManagedIdentityClient import pytest diff --git a/sdk/identity/azure-identity/tests/test_managed_identity_client_async.py b/sdk/identity/azure-identity/tests/test_managed_identity_client_async.py index 03a9d870aa4a..96ddfd70814b 100644 --- a/sdk/identity/azure-identity/tests/test_managed_identity_client_async.py +++ b/sdk/identity/azure-identity/tests/test_managed_identity_client_async.py @@ -7,7 +7,7 @@ from unittest.mock import Mock, patch from azure.core.exceptions import ClientAuthenticationError, ServiceRequestError -from azure.core.pipeline.transport import HttpRequest +from azure.core.rest import HttpRequest from azure.identity.aio._internal.managed_identity_client import AsyncManagedIdentityClient import pytest From f99f2fccbbc13e8d04dafb076c4f0065cd112228 Mon Sep 17 00:00:00 2001 From: Scott Beddall <45376673+scbedd@users.noreply.github.com> Date: Mon, 9 Feb 2026 11:48:06 -0800 Subject: [PATCH 83/84] Remove regression from PR run. no reason to generate there (#45085) --- eng/pipelines/templates/jobs/ci.yml | 81 +++++++++++++++-------------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/eng/pipelines/templates/jobs/ci.yml b/eng/pipelines/templates/jobs/ci.yml index 8ad87408ae29..bdfd70de39f9 100644 --- a/eng/pipelines/templates/jobs/ci.yml +++ b/eng/pipelines/templates/jobs/ci.yml @@ -305,43 +305,44 @@ jobs: UnsupportedToxEnvironments: ${{ parameters.UnsupportedToxEnvironments }} TestProxy: ${{ parameters.TestProxy }} - - template: /eng/common/pipelines/templates/jobs/generate-job-matrix.yml - parameters: - JobTemplatePath: /eng/pipelines/templates/jobs/regression.yml - OsVmImage: ubuntu-24.04 - Pool: azsdk-pool - GenerateJobName: generate_regression_matrix - SparseCheckoutPaths: [ "scripts/", "sdk/", "eng/tools/azure-sdk-tools/" ] - MatrixConfigs: - - Name: Python_regression_envs - Path: eng/pipelines/templates/stages/regression-job-matrix.json - Selection: sparse - GenerateVMJobs: true - PreGenerationSteps: - - task: UsePythonVersion@0 - inputs: - versionSpec: '3.12' - - template: /eng/pipelines/templates/steps/use-venv.yml - - pwsh: | - $ErrorActionPreference = 'Stop' - $PSNativeCommandUseErrorActionPreference = $true - $(PIP_EXE) install "./eng/tools/azure-sdk-tools[build]" - displayName: 'Prep Environment' - - task: PythonScript@0 - displayName: 'Ensure service coverage' - inputs: - scriptPath: '$(Build.SourcesDirectory)/scripts/devops_tasks/update_regression_services.py' - arguments: >- - "azure*" - --service="${{ parameters.ServiceDirectory }}" - --json=$(Build.SourcesDirectory)/eng/pipelines/templates/stages/regression-job-matrix.json - CloudConfig: - Cloud: Public - DependsOn: - - 'Build_Linux' - - 'Build_Windows' - - 'Build_MacOS' - AdditionalParameters: - BuildTargetingString: ${{ parameters.BuildTargetingString }} - ServiceDirectory: ${{ parameters.ServiceDirectory }} - TestTimeoutInMinutes: 90 + - ${{ if ne(parameters.ServiceDirectory, 'auto') }}: + - template: /eng/common/pipelines/templates/jobs/generate-job-matrix.yml + parameters: + JobTemplatePath: /eng/pipelines/templates/jobs/regression.yml + OsVmImage: ubuntu-24.04 + Pool: azsdk-pool + GenerateJobName: generate_regression_matrix + SparseCheckoutPaths: [ "scripts/", "sdk/", "eng/tools/azure-sdk-tools/" ] + MatrixConfigs: + - Name: Python_regression_envs + Path: eng/pipelines/templates/stages/regression-job-matrix.json + Selection: sparse + GenerateVMJobs: true + PreGenerationSteps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.12' + - template: /eng/pipelines/templates/steps/use-venv.yml + - pwsh: | + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $true + $(PIP_EXE) install "./eng/tools/azure-sdk-tools[build]" + displayName: 'Prep Environment' + - task: PythonScript@0 + displayName: 'Ensure service coverage' + inputs: + scriptPath: '$(Build.SourcesDirectory)/scripts/devops_tasks/update_regression_services.py' + arguments: >- + "azure*" + --service="${{ parameters.ServiceDirectory }}" + --json=$(Build.SourcesDirectory)/eng/pipelines/templates/stages/regression-job-matrix.json + CloudConfig: + Cloud: Public + DependsOn: + - 'Build_Linux' + - 'Build_Windows' + - 'Build_MacOS' + AdditionalParameters: + BuildTargetingString: ${{ parameters.BuildTargetingString }} + ServiceDirectory: ${{ parameters.ServiceDirectory }} + TestTimeoutInMinutes: 90 From fae04941b974480280273c57571f7eda21a211e8 Mon Sep 17 00:00:00 2001 From: Kashif Khan <361477+kashifkhan@users.noreply.github.com> Date: Mon, 9 Feb 2026 14:06:35 -0600 Subject: [PATCH 84/84] Container Registry TSP (#44848) * old generated files * new generated files with tsp * fix imports * formatting * fix url to endpoint * fix imports etc * update version * adjust pyproject.toml * fix tests * update to latest recorded tag * newline * mypy update * fix snippets * ci fixes * fix snippet * fix * point to tsp in specs repo * fix typing for model and remove some mypy ignores * fix black and snippet update * pylint * update snippets * formatting * formatting * sync snippets after black formatting * formatting fixes * sync snippets --- .../azure-containerregistry/MANIFEST.in | 5 +- .../azure-containerregistry/README.md | 3 +- .../azure-containerregistry/_metadata.json | 3 + .../apiview-properties.json | 96 + .../azure-containerregistry/assets.json | 2 +- .../azure-containerregistry/azure/__init__.py | 2 +- .../_anonymous_exchange_client.py | 4 +- .../azure/containerregistry/_base_client.py | 4 +- .../_container_registry_client.py | 167 +- .../containerregistry/_download_stream.py | 5 +- .../containerregistry/_exchange_client.py | 4 +- .../containerregistry/_generated/__init__.py | 21 +- .../containerregistry/_generated/_client.py | 80 +- .../_generated/_configuration.py | 40 +- .../containerregistry/_generated/_patch.py | 38 +- .../_generated/_utils/__init__.py | 6 + .../_generated/_utils/model_base.py | 1356 ++++++++++++ .../serialization.py} | 724 +++--- .../_generated/_utils/utils.py | 50 + .../containerregistry/_generated/_vendor.py | 15 - .../containerregistry/_generated/_version.py | 9 + .../_generated/aio/__init__.py | 18 +- .../_generated/aio/_client.py | 82 +- .../_generated/aio/_configuration.py | 40 +- .../_generated/aio/_patch.py | 38 +- .../_generated/aio/_vendor.py | 15 - .../_generated/aio/operations/__init__.py | 20 +- .../_generated/aio/operations/_operations.py | 1711 ++++++++++----- .../_generated/aio/operations/_patch.py | 79 +- .../_generated/models/__init__.py | 107 +- .../_generated/models/_enums.py | 41 +- .../_generated/models/_models.py | 1931 +++++++--------- .../_generated/models/_patch.py | 15 +- .../_generated/operations/__init__.py | 20 +- .../_generated/operations/_operations.py | 1946 +++++++++++------ .../_generated/operations/_patch.py | 173 +- .../azure/containerregistry/_models.py | 61 +- .../aio/_async_anonymous_exchange_client.py | 4 +- .../aio/_async_base_client.py | 4 +- .../aio/_async_container_registry_client.py | 336 +-- .../aio/_async_download_stream.py | 5 +- .../aio/_async_exchange_client.py | 4 +- .../azure-containerregistry/pyproject.toml | 63 + .../samples/sample_delete_images.py | 4 +- .../samples/sample_delete_images_async.py | 4 +- .../samples/sample_delete_tags.py | 4 +- .../samples/sample_delete_tags_async.py | 8 +- .../samples/sample_hello_world.py | 1 + .../samples/sample_hello_world_async.py | 9 +- .../samples/sample_list_tags.py | 1 + .../samples/sample_list_tags_async.py | 5 +- .../samples/sample_set_get_image.py | 6 +- .../samples/sample_set_get_image_async.py | 8 +- .../samples/sample_set_image_properties.py | 3 +- .../sample_set_image_properties_async.py | 1 + .../samples/utilities.py | 6 +- .../azure-containerregistry/setup.py | 66 - .../tests/asynctestcase.py | 7 +- .../tests/perfstress_tests/list_artifacts.py | 4 +- .../perfstress_tests/list_repositories.py | 4 +- .../tests/test_anon_access.py | 8 +- .../tests/test_anon_access_async.py | 8 +- .../tests/test_container_registry_client.py | 73 +- .../test_container_registry_client_async.py | 65 +- .../azure-containerregistry/tests/testcase.py | 6 +- .../azure-containerregistry/tsp-location.yaml | 4 + 66 files changed, 6170 insertions(+), 3482 deletions(-) create mode 100644 sdk/containerregistry/azure-containerregistry/_metadata.json create mode 100644 sdk/containerregistry/azure-containerregistry/apiview-properties.json create mode 100644 sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/__init__.py create mode 100644 sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/model_base.py rename sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/{_serialization.py => _utils/serialization.py} (77%) create mode 100644 sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/utils.py delete mode 100644 sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_vendor.py create mode 100644 sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_version.py delete mode 100644 sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_vendor.py delete mode 100644 sdk/containerregistry/azure-containerregistry/setup.py create mode 100644 sdk/containerregistry/azure-containerregistry/tsp-location.yaml diff --git a/sdk/containerregistry/azure-containerregistry/MANIFEST.in b/sdk/containerregistry/azure-containerregistry/MANIFEST.in index 442a31f67463..bce87c056b23 100644 --- a/sdk/containerregistry/azure-containerregistry/MANIFEST.in +++ b/sdk/containerregistry/azure-containerregistry/MANIFEST.in @@ -1,6 +1,7 @@ include *.md -include azure/__init__.py include LICENSE +include azure/containerregistry/_generated/py.typed recursive-include tests *.py recursive-include samples *.py *.md -include azure/containerregistry/py.typed +include azure/__init__.py +include azure/containerregistry/__init__.py diff --git a/sdk/containerregistry/azure-containerregistry/README.md b/sdk/containerregistry/azure-containerregistry/README.md index e2ffa0dbeaeb..f7985488e359 100644 --- a/sdk/containerregistry/azure-containerregistry/README.md +++ b/sdk/containerregistry/azure-containerregistry/README.md @@ -136,7 +136,8 @@ with ContainerRegistryClient(self.endpoint, self.credential) as client: # Keep the three most recent images, delete everything else manifest_count = 0 for manifest in client.list_manifest_properties( - repository, order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING + repository, + order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING, ): manifest_count += 1 if manifest_count > 3: diff --git a/sdk/containerregistry/azure-containerregistry/_metadata.json b/sdk/containerregistry/azure-containerregistry/_metadata.json new file mode 100644 index 000000000000..45610089d6c2 --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/_metadata.json @@ -0,0 +1,3 @@ +{ + "apiVersion": "2021-07-01" +} \ No newline at end of file diff --git a/sdk/containerregistry/azure-containerregistry/apiview-properties.json b/sdk/containerregistry/azure-containerregistry/apiview-properties.json new file mode 100644 index 000000000000..4ef262be081b --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/apiview-properties.json @@ -0,0 +1,96 @@ +{ + "CrossLanguagePackageId": "ContainerRegistry", + "CrossLanguageDefinitionId": { + "azure.containerregistry.models.AcrAccessToken": "ContainerRegistryService.AcrAccessToken", + "azure.containerregistry.models.AcrErrorInfo": "ContainerRegistryService.AcrErrorInfo", + "azure.containerregistry.models.AcrErrors": "ContainerRegistryService.AcrErrors", + "azure.containerregistry.models.AcrManifests": "ContainerRegistryService.AcrManifests", + "azure.containerregistry.models.AcrRefreshToken": "ContainerRegistryService.AcrRefreshToken", + "azure.containerregistry.models.Annotations": "ContainerRegistryService.Annotations", + "azure.containerregistry.models.ArtifactManifestPlatform": "ContainerRegistryService.ArtifactManifestPlatform", + "azure.containerregistry.models.ArtifactManifestProperties": "ContainerRegistryService.ArtifactManifestProperties", + "azure.containerregistry.models.ArtifactTagProperties": "ContainerRegistryService.ArtifactTagProperties", + "azure.containerregistry.models.ContainerRepositoryProperties": "ContainerRegistryService.ContainerRepositoryProperties", + "azure.containerregistry.models.Descriptor": "ContainerRegistryService.Descriptor", + "azure.containerregistry.models.FsLayer": "ContainerRegistryService.FsLayer", + "azure.containerregistry.models.History": "ContainerRegistryService.History", + "azure.containerregistry.models.ImageSignature": "ContainerRegistryService.ImageSignature", + "azure.containerregistry.models.JWK": "ContainerRegistryService.JWK", + "azure.containerregistry.models.JWKHeader": "ContainerRegistryService.JWKHeader", + "azure.containerregistry.models.Manifest": "ContainerRegistryService.Manifest", + "azure.containerregistry.models.ManifestAttributesBase": "ContainerRegistryService.ManifestAttributesBase", + "azure.containerregistry.models.ManifestListAttributes": "ContainerRegistryService.ManifestListAttributes", + "azure.containerregistry.models.ManifestWrapper": "ContainerRegistryService.ManifestWrapper", + "azure.containerregistry.models.ManifestWriteableProperties": "ContainerRegistryService.ManifestChangeableAttributes", + "azure.containerregistry.models.MultipartBodyParameter": "ContainerRegistryService.MultipartBodyParameter", + "azure.containerregistry.models.Platform": "ContainerRegistryService.Platform", + "azure.containerregistry.models.RepositoryWriteableProperties": "ContainerRegistryService.RepositoryChangeableAttributes", + "azure.containerregistry.models.TagAttributesBase": "ContainerRegistryService.TagAttributesBase", + "azure.containerregistry.models.TagList": "ContainerRegistryService.TagList", + "azure.containerregistry.models.TagWriteableProperties": "ContainerRegistryService.TagChangeableAttributes", + "azure.containerregistry.models.ArtifactTagOrder": "ContainerRegistryService.ArtifactTagOrder", + "azure.containerregistry.models.ArtifactArchitecture": "ContainerRegistryService.ArtifactArchitecture", + "azure.containerregistry.models.ArtifactOperatingSystem": "ContainerRegistryService.ArtifactOperatingSystem", + "azure.containerregistry.models.ArtifactManifestOrder": "ContainerRegistryService.ArtifactManifestOrder", + "azure.containerregistry.models.PostContentSchemaGrantType": "ContainerRegistryService.PostContentSchemaGrantType", + "azure.containerregistry.models.TokenGrantType": "ContainerRegistryService.TokenGrantType", + "azure.containerregistry.operations.ContainerRegistryOperations.check_docker_v2_support": "ContainerRegistryService.ContainerRegistry.checkDockerV2Support", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.check_docker_v2_support": "ContainerRegistryService.ContainerRegistry.checkDockerV2Support", + "azure.containerregistry.operations.ContainerRegistryOperations.get_manifest": "ContainerRegistryService.ContainerRegistry.getManifest", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_manifest": "ContainerRegistryService.ContainerRegistry.getManifest", + "azure.containerregistry.operations.ContainerRegistryOperations.create_manifest": "ContainerRegistryService.ContainerRegistry.createManifest", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.create_manifest": "ContainerRegistryService.ContainerRegistry.createManifest", + "azure.containerregistry.operations.ContainerRegistryOperations.delete_manifest": "ContainerRegistryService.ContainerRegistry.deleteManifest", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.delete_manifest": "ContainerRegistryService.ContainerRegistry.deleteManifest", + "azure.containerregistry.operations.ContainerRegistryOperations.get_repositories": "ContainerRegistryService.ContainerRegistry.getRepositories", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_repositories": "ContainerRegistryService.ContainerRegistry.getRepositories", + "azure.containerregistry.operations.ContainerRegistryOperations.get_properties": "ContainerRegistryService.ContainerRegistry.getProperties", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_properties": "ContainerRegistryService.ContainerRegistry.getProperties", + "azure.containerregistry.operations.ContainerRegistryOperations.delete_repository": "ContainerRegistryService.ContainerRegistry.deleteRepository", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.delete_repository": "ContainerRegistryService.ContainerRegistry.deleteRepository", + "azure.containerregistry.operations.ContainerRegistryOperations.update_properties": "ContainerRegistryService.ContainerRegistry.updateProperties", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.update_properties": "ContainerRegistryService.ContainerRegistry.updateProperties", + "azure.containerregistry.operations.ContainerRegistryOperations.get_tags": "ContainerRegistryService.ContainerRegistry.getTags", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_tags": "ContainerRegistryService.ContainerRegistry.getTags", + "azure.containerregistry.operations.ContainerRegistryOperations.get_tag_properties": "ContainerRegistryService.ContainerRegistry.getTagProperties", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_tag_properties": "ContainerRegistryService.ContainerRegistry.getTagProperties", + "azure.containerregistry.operations.ContainerRegistryOperations.update_tag_attributes": "ContainerRegistryService.ContainerRegistry.updateTagAttributes", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.update_tag_attributes": "ContainerRegistryService.ContainerRegistry.updateTagAttributes", + "azure.containerregistry.operations.ContainerRegistryOperations.delete_tag": "ContainerRegistryService.ContainerRegistry.deleteTag", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.delete_tag": "ContainerRegistryService.ContainerRegistry.deleteTag", + "azure.containerregistry.operations.ContainerRegistryOperations.get_manifests": "ContainerRegistryService.ContainerRegistry.getManifests", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_manifests": "ContainerRegistryService.ContainerRegistry.getManifests", + "azure.containerregistry.operations.ContainerRegistryOperations.get_manifest_properties": "ContainerRegistryService.ContainerRegistry.getManifestProperties", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.get_manifest_properties": "ContainerRegistryService.ContainerRegistry.getManifestProperties", + "azure.containerregistry.operations.ContainerRegistryOperations.update_manifest_properties": "ContainerRegistryService.ContainerRegistry.updateManifestProperties", + "azure.containerregistry.aio.operations.ContainerRegistryOperations.update_manifest_properties": "ContainerRegistryService.ContainerRegistry.updateManifestProperties", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.get_blob": "ContainerRegistryService.ContainerRegistryBlob.getBlob", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.get_blob": "ContainerRegistryService.ContainerRegistryBlob.getBlob", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.check_blob_exists": "ContainerRegistryService.ContainerRegistryBlob.checkBlobExists", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.check_blob_exists": "ContainerRegistryService.ContainerRegistryBlob.checkBlobExists", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.delete_blob": "ContainerRegistryService.ContainerRegistryBlob.deleteBlob", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.delete_blob": "ContainerRegistryService.ContainerRegistryBlob.deleteBlob", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.mount_blob": "ContainerRegistryService.ContainerRegistryBlob.mountBlob", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.mount_blob": "ContainerRegistryService.ContainerRegistryBlob.mountBlob", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.get_upload_status": "ContainerRegistryService.ContainerRegistryBlob.getUploadStatus", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.get_upload_status": "ContainerRegistryService.ContainerRegistryBlob.getUploadStatus", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.upload_chunk": "ContainerRegistryService.ContainerRegistryBlob.uploadChunk", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.upload_chunk": "ContainerRegistryService.ContainerRegistryBlob.uploadChunk", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.complete_upload": "ContainerRegistryService.ContainerRegistryBlob.completeUpload", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.complete_upload": "ContainerRegistryService.ContainerRegistryBlob.completeUpload", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.cancel_upload": "ContainerRegistryService.ContainerRegistryBlob.cancelUpload", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.cancel_upload": "ContainerRegistryService.ContainerRegistryBlob.cancelUpload", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.start_upload": "ContainerRegistryService.ContainerRegistryBlob.startUpload", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.start_upload": "ContainerRegistryService.ContainerRegistryBlob.startUpload", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.get_chunk": "ContainerRegistryService.ContainerRegistryBlob.getChunk", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.get_chunk": "ContainerRegistryService.ContainerRegistryBlob.getChunk", + "azure.containerregistry.operations.ContainerRegistryBlobOperations.check_chunk_exists": "ContainerRegistryService.ContainerRegistryBlob.checkChunkExists", + "azure.containerregistry.aio.operations.ContainerRegistryBlobOperations.check_chunk_exists": "ContainerRegistryService.ContainerRegistryBlob.checkChunkExists", + "azure.containerregistry.operations.AuthenticationOperations.exchange_aad_access_token_for_acr_refresh_token": "ContainerRegistryService.Authentication.exchangeAadAccessTokenForAcrRefreshToken", + "azure.containerregistry.aio.operations.AuthenticationOperations.exchange_aad_access_token_for_acr_refresh_token": "ContainerRegistryService.Authentication.exchangeAadAccessTokenForAcrRefreshToken", + "azure.containerregistry.operations.AuthenticationOperations.exchange_acr_refresh_token_for_acr_access_token": "ContainerRegistryService.Authentication.exchangeAcrRefreshTokenForAcrAccessToken", + "azure.containerregistry.aio.operations.AuthenticationOperations.exchange_acr_refresh_token_for_acr_access_token": "ContainerRegistryService.Authentication.exchangeAcrRefreshTokenForAcrAccessToken", + "azure.containerregistry.operations.AuthenticationOperations.get_acr_access_token_from_login": "ContainerRegistryService.Authentication.getAcrAccessTokenFromLogin", + "azure.containerregistry.aio.operations.AuthenticationOperations.get_acr_access_token_from_login": "ContainerRegistryService.Authentication.getAcrAccessTokenFromLogin" + } +} \ No newline at end of file diff --git a/sdk/containerregistry/azure-containerregistry/assets.json b/sdk/containerregistry/azure-containerregistry/assets.json index 86c3da43830b..0a6306e7fce2 100644 --- a/sdk/containerregistry/azure-containerregistry/assets.json +++ b/sdk/containerregistry/azure-containerregistry/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/containerregistry/azure-containerregistry", - "Tag": "python/containerregistry/azure-containerregistry_55d84769d4" + "Tag": "python/containerregistry/azure-containerregistry_98be10d599" } \ No newline at end of file diff --git a/sdk/containerregistry/azure-containerregistry/azure/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/__init__.py +++ b/sdk/containerregistry/azure-containerregistry/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_anonymous_exchange_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_anonymous_exchange_client.py index 1963936fde9f..605cb7b06b6b 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_anonymous_exchange_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_anonymous_exchange_client.py @@ -8,7 +8,7 @@ from azure.core.credentials import TokenCredential, AccessToken from ._exchange_client import ExchangeClientAuthenticationPolicy -from ._generated import ContainerRegistry +from ._generated import ContainerRegistryClient as ContainerRegistry from ._generated.models import TokenGrantType from ._generated.operations._patch import AuthenticationOperations from ._helpers import _parse_challenge @@ -38,8 +38,8 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential endpoint = "https://" + endpoint self._endpoint = endpoint self._client = ContainerRegistry( + endpoint=endpoint, credential=AnonymousAccessCredential(), - url=endpoint, sdk_moniker=USER_AGENT, authentication_policy=ExchangeClientAuthenticationPolicy(), **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_base_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_base_client.py index 042b3474e3b2..3ee3185281df 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_base_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_base_client.py @@ -12,7 +12,7 @@ from ._authentication_policy import ContainerRegistryChallengePolicy from ._anonymous_exchange_client import AnonymousAccessCredential -from ._generated import ContainerRegistry +from ._generated import ContainerRegistryClient as ContainerRegistry from ._user_agent import USER_AGENT ClientType = TypeVar("ClientType", bound="ContainerRegistryBaseClient") @@ -39,8 +39,8 @@ class ContainerRegistryBaseClient(object): def __init__(self, endpoint: str, credential: Optional[TokenCredential], **kwargs: Any) -> None: self._auth_policy = ContainerRegistryChallengePolicy(credential, endpoint, **kwargs) self._client = ContainerRegistry( + endpoint=endpoint, credential=credential or AnonymousAccessCredential(), - url=endpoint, sdk_moniker=USER_AGENT, authentication_policy=self._auth_policy, **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_container_registry_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_container_registry_client.py index 97a1d66e95dc..e0ed85151136 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_container_registry_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_container_registry_client.py @@ -1,14 +1,26 @@ +# pylint: disable=too-many-lines # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines, protected-access import functools import hashlib import json from io import BytesIO -from typing import Any, Dict, IO, Optional, overload, Union, cast, Tuple, MutableMapping, TYPE_CHECKING +from typing import ( + Any, + Dict, + IO, + Optional, + overload, + Union, + cast, + Tuple, + MutableMapping, + TYPE_CHECKING, +) from azure.core.credentials import TokenCredential from azure.core.exceptions import ( @@ -45,8 +57,12 @@ ArtifactManifestProperties, GetManifestResult, DigestValidationError, + TagAttributesBase, + ManifestAttributesBase, ) +from ._generated._utils.model_base import _deserialize + if TYPE_CHECKING: from ._generated.models import ArtifactManifestOrder, ArtifactTagOrder JSON = MutableMapping[str, Any] @@ -109,7 +125,10 @@ def __init__( self._endpoint = endpoint self._credential = credential super(ContainerRegistryClient, self).__init__( - endpoint=endpoint, credential=credential, credential_scopes=defaultScope, **kwargs + endpoint=endpoint, + credential=credential, + credential_scopes=defaultScope, + **kwargs, ) def _get_digest_from_tag(self, repository: str, tag: str) -> str: @@ -158,7 +177,11 @@ def list_repository_names(self, *, results_per_page: Optional[int] = None, **kwa """ last = kwargs.pop("last", None) cls = kwargs.pop("cls", None) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {})) accept = "application/json" @@ -173,14 +196,16 @@ def prepare_request(next_link=None): # Construct URL url = "/acr/v1/_catalog" path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), } - url = self._client._client.format_url(url, **path_format_arguments) # pylint: disable=protected-access + url = self._client._client.format_url( # pylint: disable=protected-access + url, **path_format_arguments + ) # pylint: disable=protected-access # Construct parameters query_parameters: Dict[str, Any] = {} if last is not None: @@ -199,24 +224,29 @@ def prepare_request(next_link=None): url = next_link query_parameters: Dict[str, Any] = {} path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), } - url = self._client._client.format_url(url, **path_format_arguments) # pylint: disable=protected-access + url = self._client._client.format_url( # pylint: disable=protected-access + url, **path_format_arguments + ) # pylint: disable=protected-access request = self._client._client.get( # pylint: disable=protected-access url, query_parameters, header_parameters ) return request def extract_data(pipeline_response): - deserialized = self._client._deserialize( # pylint: disable=protected-access - "Repositories", pipeline_response + list_of_elem = ( + _deserialize( + list[str], + pipeline_response.http_response.internal_response.json().get("repositories", []), + ) + or [] ) - list_of_elem = deserialized.repositories or [] if cls: list_of_elem = cls(list_of_elem) link = None @@ -236,7 +266,11 @@ def get_next(next_link=None): error = self._client._deserialize.failsafe_deserialize( # pylint: disable=protected-access AcrErrors, response ) - map_error(status_code=response.status_code, response=response, error_map=error_map) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -288,7 +322,11 @@ def list_manifest_properties( ], ) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {})) accept = "application/json" @@ -303,9 +341,9 @@ def prepare_request(next_link=None): # Construct URL url = "/acr/v1/{name}/_manifests" path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), @@ -334,9 +372,9 @@ def prepare_request(next_link=None): url = next_link query_parameters: Dict[str, Any] = {} path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), @@ -349,10 +387,10 @@ def prepare_request(next_link=None): return request def extract_data(pipeline_response): - deserialized = self._client._deserialize( # pylint: disable=protected-access - "AcrManifests", pipeline_response + list_of_elem = _deserialize( + list[ManifestAttributesBase], + pipeline_response.http_response.internal_response.json().get("manifests", []), ) - list_of_elem = deserialized.manifests or [] if cls: list_of_elem = cls(list_of_elem) link = None @@ -372,7 +410,11 @@ def get_next(next_link=None): error = self._client._deserialize.failsafe_deserialize( # pylint: disable=protected-access AcrErrors, response ) - map_error(status_code=response.status_code, response=response, error_map=error_map) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -505,7 +547,11 @@ def list_tag_properties( ], ) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {})) accept = "application/json" @@ -520,9 +566,9 @@ def prepare_request(next_link=None): # Construct URL url = "/acr/v1/{name}/_tags" path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), @@ -555,9 +601,9 @@ def prepare_request(next_link=None): url = next_link query_parameters: Dict[str, Any] = {} path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), @@ -570,8 +616,13 @@ def prepare_request(next_link=None): return request def extract_data(pipeline_response): - deserialized = self._client._deserialize("TagList", pipeline_response) # pylint: disable=protected-access - list_of_elem = deserialized.tag_attribute_bases or [] + list_of_elem = ( + _deserialize( + list[TagAttributesBase], + pipeline_response.http_response.internal_response.json().get("tags", []), + ) + or [] + ) if cls: list_of_elem = cls(list_of_elem) link = None @@ -591,7 +642,11 @@ def get_next(next_link=None): error = self._client._deserialize.failsafe_deserialize( # pylint: disable=protected-access AcrErrors, response ) - map_error(status_code=response.status_code, response=response, error_map=error_map) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -600,7 +655,11 @@ def get_next(next_link=None): @overload def update_manifest_properties( - self, repository: str, tag_or_digest: str, properties: ArtifactManifestProperties, **kwargs: Any + self, + repository: str, + tag_or_digest: str, + properties: ArtifactManifestProperties, + **kwargs: Any, ) -> ArtifactManifestProperties: """Set the permission properties for a manifest. @@ -698,7 +757,10 @@ def update_manifest_properties( tag_or_digest = self._get_digest_from_tag(repository, tag_or_digest) manifest_properties = self._client.container_registry.update_manifest_properties( - repository, tag_or_digest, value=properties._to_generated(), **kwargs # pylint: disable=protected-access + repository, + tag_or_digest, + value=properties._to_generated(), + **kwargs, # pylint: disable=protected-access ) return ArtifactManifestProperties._from_generated( # pylint: disable=protected-access manifest_properties.manifest, # type: ignore[arg-type] # The property "manifest" is required in response @@ -708,7 +770,11 @@ def update_manifest_properties( @overload def update_tag_properties( - self, repository: str, tag: str, properties: ArtifactTagProperties, **kwargs: Any + self, + repository: str, + tag: str, + properties: ArtifactTagProperties, + **kwargs: Any, ) -> ArtifactTagProperties: """Set the permission properties for a tag. @@ -797,7 +863,10 @@ def update_tag_properties(self, *args: Union[str, ArtifactTagProperties], **kwar properties.can_write = kwargs.pop("can_write", properties.can_write) tag_attributes = self._client.container_registry.update_tag_attributes( - repository, tag, value=properties._to_generated(), **kwargs # pylint: disable=protected-access + repository, + tag, + value=properties._to_generated(), + **kwargs, # pylint: disable=protected-access ) return ArtifactTagProperties._from_generated( # pylint: disable=protected-access tag_attributes.tag, # type: ignore[arg-type] # The property "tag" is required in response @@ -862,7 +931,9 @@ def update_repository_properties( return RepositoryProperties._from_generated( # pylint: disable=protected-access self._client.container_registry.update_properties( - repository, value=properties._to_generated(), **kwargs # pylint: disable=protected-access + repository, + value=properties._to_generated(), + **kwargs, # pylint: disable=protected-access ) ) @@ -911,7 +982,7 @@ def set_manifest( cls=_return_response_headers, **kwargs, ) - digest = response_headers["Docker-Content-Digest"] + digest = response_headers["Docker-Content-Digest"] # type: ignore[index] if not _validate_digest(data, digest): raise DigestValidationError("The server-computed digest does not match the client-computed digest.") except Exception as e: @@ -990,7 +1061,7 @@ def upload_blob(self, repository: str, data: IO[bytes], **kwargs: Any) -> Tuple[ complete_upload_response_headers = cast( Dict[str, str], self._client.container_registry_blob.complete_upload( - digest=digest, next_link=location, cls=_return_response_headers, **kwargs + location, digest=digest, cls=_return_response_headers, **kwargs ), ) if digest != complete_upload_response_headers["Docker-Content-Digest"]: @@ -1009,7 +1080,7 @@ def _upload_blob_chunk(self, location: str, data: IO[bytes], **kwargs) -> Tuple[ response_headers = cast( Dict[str, str], self._client.container_registry_blob.upload_chunk( - location, BytesIO(buffer), cls=_return_response_headers, **kwargs + location, BytesIO(buffer), cls=_return_response_headers, **kwargs # type: ignore[arg-type] ), ) location = response_headers["Location"] @@ -1034,7 +1105,11 @@ def download_blob(self, repository: str, digest: str, **kwargs: Any) -> Download first_chunk, headers = cast( Tuple[PipelineResponse, Dict[str, str]], self._client.container_registry_blob.get_chunk( - repository, digest, range_header=f"bytes=0-{end_range}", cls=_return_response_and_headers, **kwargs + repository, + digest, + range=f"bytes=0-{end_range}", + cls=_return_response_and_headers, + **kwargs, ), ) blob_size = _get_blob_size(headers) diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_download_stream.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_download_stream.py index 39c1d0d32f17..e21902145045 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_download_stream.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_download_stream.py @@ -58,7 +58,10 @@ def _yield_data(self) -> bytes: def _download_chunk(self) -> PipelineResponse: end_range = self._downloaded + self._chunk_size - 1 range_header = f"bytes={self._downloaded}-{end_range}" - next_chunk, headers = cast(Tuple[PipelineResponse, Dict[str, str]], self._next(range_header=range_header)) + next_chunk, headers = cast( + Tuple[PipelineResponse, Dict[str, str]], + self._next(range_header=range_header), + ) self._downloaded += int(headers["Content-Length"]) return next_chunk diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_exchange_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_exchange_client.py index 3fd6d3047a43..0b355591700b 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_exchange_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_exchange_client.py @@ -10,7 +10,7 @@ from azure.core.pipeline import PipelineRequest, PipelineResponse from azure.core.pipeline.policies import SansIOHTTPPolicy -from ._generated import ContainerRegistry +from ._generated import ContainerRegistryClient as ContainerRegistry from ._generated.models import PostContentSchemaGrantType from ._generated.operations._patch import AuthenticationOperations from ._helpers import _parse_challenge, _parse_exp_time @@ -46,8 +46,8 @@ def __init__(self, endpoint: str, credential: TokenCredential, **kwargs: Any) -> self._endpoint = endpoint self.credential_scopes = kwargs.get("credential_scopes", ["https://management.core.windows.net/.default"]) self._client = ContainerRegistry( + endpoint=endpoint, credential=credential, - url=endpoint, sdk_moniker=USER_AGENT, authentication_policy=ExchangeClientAuthenticationPolicy(), **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/__init__.py index 75020eabd3bb..36f67ce7b7c1 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/__init__.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/__init__.py @@ -1,21 +1,32 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import ContainerRegistry +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ContainerRegistryClient # type: ignore +from ._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ - "ContainerRegistry", + "ContainerRegistryClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_client.py index 21de7a387b90..69ee18b3eef4 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_client.py @@ -1,52 +1,76 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self from azure.core import PipelineClient +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import ContainerRegistryConfiguration -from ._serialization import Deserializer, Serializer -from .operations import AuthenticationOperations, ContainerRegistryBlobOperations, ContainerRegistryOperations +from ._configuration import ContainerRegistryClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + AuthenticationOperations, + ContainerRegistryBlobOperations, + ContainerRegistryOperations, +) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class ContainerRegistry: # pylint: disable=client-accepts-api-version-keyword +class ContainerRegistryClient: """Metadata API definition for the Azure Container Registry runtime. :ivar container_registry: ContainerRegistryOperations operations - :vartype container_registry: container_registry.operations.ContainerRegistryOperations + :vartype container_registry: + azure.containerregistry._generated.operations.ContainerRegistryOperations :ivar container_registry_blob: ContainerRegistryBlobOperations operations - :vartype container_registry_blob: container_registry.operations.ContainerRegistryBlobOperations + :vartype container_registry_blob: + azure.containerregistry._generated.operations.ContainerRegistryBlobOperations :ivar authentication: AuthenticationOperations operations - :vartype authentication: container_registry.operations.AuthenticationOperations - :param url: Registry login URL. Required. - :type url: str - :param credential: Credential needed for the client to connect to Azure. Required. + :vartype authentication: azure.containerregistry._generated.operations.AuthenticationOperations + :param endpoint: Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is "2021-07-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: - _endpoint = "{url}" - self._config = ContainerRegistryConfiguration(url=url, credential=credential, **kwargs) - self._client: PipelineClient = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)} - client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)}) - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = ContainerRegistryClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + (policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None), + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.container_registry = ContainerRegistryOperations( self._client, self._config, self._serialize, self._deserialize @@ -56,7 +80,7 @@ def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> No ) self.authentication = AuthenticationOperations(self._client, self._config, self._serialize, self._deserialize) - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -76,16 +100,16 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() - def __enter__(self) -> "ContainerRegistry": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_configuration.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_configuration.py index c564f6b32232..5198a0351a5e 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_configuration.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_configuration.py @@ -1,50 +1,50 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies +from ._version import VERSION + if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -VERSION = "unknown" - -class ContainerRegistryConfiguration(Configuration): # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for ContainerRegistry. +class ContainerRegistryClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ContainerRegistryClient. Note that all parameters used to create this instance are saved as instance attributes. - :param url: Registry login URL. Required. - :type url: str - :param credential: Credential needed for the client to connect to Azure. Required. + :param endpoint: Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is "2021-07-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: - super(ContainerRegistryConfiguration, self).__init__(**kwargs) + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2021-07-01") - if url is None: - raise ValueError("Parameter 'url' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") if credential is None: raise ValueError("Parameter 'credential' must not be None.") - self.url = url + self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", []) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://containerregistry.azure.net/.default"]) kwargs.setdefault("sdk_moniker", "containerregistry/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -53,12 +53,10 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") - if not self.credential_scopes and not self.authentication_policy: - raise ValueError("You must provide either credential_scopes or authentication_policy as kwargs") if self.credential and not self.authentication_policy: self.authentication_policy = policies.BearerTokenCredentialPolicy( self.credential, *self.credential_scopes, **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_patch.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_patch.py index 17dbc073e01b..ea765788358a 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_patch.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_patch.py @@ -1,32 +1,20 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/model_base.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/model_base.py new file mode 100644 index 000000000000..675f53135624 --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/model_base.py @@ -0,0 +1,1356 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__( + self, + *args, + exclude_readonly: bool = False, + format: typing.Optional[str] = None, + **kwargs, + ): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp( + attr: typing.Union[float, datetime], +) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), + module, + rf, # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", + exc_info=True, + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", + exc_info=True, + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, + meta.get("prefix") if meta else None, + meta.get("ns") if meta else None, + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element( + tag: typing.Any, + prefix: typing.Optional[str] = None, + ns: typing.Optional[str] = None, +) -> ET.Element: + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [ + dict_result[child.tag], + _convert_element(child), + ] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_serialization.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/serialization.py similarity index 77% rename from sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_serialization.py rename to sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/serialization.py index 9f3e29b11388..85361bf87da6 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_serialization.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -39,7 +21,6 @@ import sys import codecs from typing import ( - Dict, Any, cast, Optional, @@ -48,11 +29,7 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, - List, - Mapping, ) try: @@ -62,13 +39,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,6 +68,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +91,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -124,7 +103,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -143,7 +122,9 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -153,6 +134,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -170,13 +156,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -184,80 +163,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: - self.additional_properties: Dict[str, Any] = {} - for k in kwargs: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + _LOGGER.warning( + "%s is not a known attribute of class %s and will be ignored", + k, + self.__class__, + ) elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + _LOGGER.warning( + "Readonly attribute %s will be ignored in class %s", + k, + self.__class__, + ) else: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -331,16 +286,24 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: xml_map = {} - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + return _create_xml_node( + xml_map.get("name", cls.__name__), + xml_map.get("prefix", None), + xml_map.get("ns", None), + ) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -351,12 +314,14 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -385,12 +350,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -400,30 +368,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -431,9 +400,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -445,7 +416,7 @@ def from_dict( if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -453,21 +424,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -486,7 +461,11 @@ def _classify(cls, response, objects): ) break else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + _LOGGER.warning( + "Discriminator %s is absent or null, use base class %s.", + subtype_key, + cls.__name__, + ) break return cls @@ -506,11 +485,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -545,7 +526,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,17 +542,20 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -597,17 +581,19 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) + serialized |= target_obj.additional_properties continue try: @@ -638,7 +624,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -649,7 +636,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore @@ -668,18 +655,18 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized + raise SerializationError(msg) from err + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -708,20 +695,22 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -730,32 +719,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) - # https://github.com/Azure/autorest.python/issues/2063 output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] do_quote = not kwargs.get("skip_quote", False) - return str(self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs)) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -765,19 +752,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -786,37 +774,36 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: - if data is AzureCoreNull: + if data is CoreNull: return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -826,12 +813,11 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -847,23 +833,33 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -877,8 +873,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -888,15 +883,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -939,7 +932,11 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): if isinstance(el, ET.Element): el_node = el else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + el_node = _create_xml_node( + node_name, + xml_desc.get("prefix", None), + xml_desc.get("ns", None), + ) if el is not None: # Otherwise it writes "None" :-p el_node.text = str(el) final_result.append(el_node) @@ -951,9 +948,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -977,7 +973,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -985,6 +981,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -995,7 +992,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -1009,7 +1006,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1040,56 +1037,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1097,11 +1099,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1111,30 +1114,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1147,12 +1152,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1167,24 +1173,30 @@ def serialize_iso(attr, **kwargs): if microseconds: microseconds = "." + microseconds date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + utc.tm_year, + utc.tm_mon, + utc.tm_mday, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, ) return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1192,17 +1204,17 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data while "." in key: # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) + dict_keys = cast(list[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1211,14 +1223,15 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1232,7 +1245,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1240,17 +1252,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1287,7 +1311,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1339,22 +1363,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1362,7 +1385,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1371,9 +1394,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1393,7 +1416,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1409,27 +1432,32 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for ( + attr, + mapconfig, + ) in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1446,15 +1474,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1483,10 +1511,9 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1513,18 +1540,20 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1539,12 +1568,15 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", + exc_info=True, ) return None @@ -1560,10 +1592,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1580,31 +1614,42 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1613,15 +1658,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1635,7 +1681,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1654,15 +1704,15 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1679,6 +1729,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1689,20 +1740,21 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1728,11 +1780,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1740,8 +1791,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1751,24 +1803,27 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): @@ -1776,6 +1831,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1789,8 +1845,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1802,6 +1857,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1810,12 +1866,11 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1823,7 +1878,11 @@ def deserialize_enum(data, enum_obj): if enum_value.value.lower() == str(data).lower(): return enum_value # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + _LOGGER.warning( + "Deserializer is not able to find %s as valid enum in %s", + data, + enum_obj, + ) return Deserializer.deserialize_unicode(data) @staticmethod @@ -1831,8 +1890,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1843,8 +1903,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1858,24 +1919,26 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1886,8 +1949,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1895,17 +1959,17 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration + raise DeserializationError(msg) from err + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1919,8 +1983,9 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1933,31 +1998,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1984,9 +2050,8 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1994,15 +2059,16 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/utils.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/utils.py new file mode 100644 index 000000000000..707b7d8fac75 --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_utils/utils.py @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import json +from typing import Any, IO, Mapping, Optional, Union + +from .._utils.model_base import Model, SdkJSONEncoder + +# file-like tuple could be `(filename, IO (or bytes))` or `(filename, IO (or bytes), content_type)` +FileContent = Union[str, bytes, IO[str], IO[bytes]] + +FileType = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + tuple[Optional[str], FileContent, Optional[str]], +] + + +def serialize_multipart_data_entry(data_entry: Any) -> Any: + if isinstance(data_entry, (list, tuple, dict, Model)): + return json.dumps(data_entry, cls=SdkJSONEncoder, exclude_readonly=True) + return data_entry + + +def prepare_multipart_form_data( + body: Mapping[str, Any], multipart_fields: list[str], data_fields: list[str] +) -> list[FileType]: + files: list[FileType] = [] + for multipart_field in multipart_fields: + multipart_entry = body.get(multipart_field) + if isinstance(multipart_entry, list): + files.extend([(multipart_field, e) for e in multipart_entry]) + elif multipart_entry: + files.append((multipart_field, multipart_entry)) + + # if files is empty, sdk core library can't handle multipart/form-data correctly, so + # we put data fields into files with filename as None to avoid that scenario. + for data_field in data_fields: + data_entry = body.get(data_field) + if data_entry: + files.append((data_field, str(serialize_multipart_data_entry(data_entry)))) + + return files diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_vendor.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_vendor.py deleted file mode 100644 index b89fce811475..000000000000 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_vendor.py +++ /dev/null @@ -1,15 +0,0 @@ -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def raise_if_not_implemented(cls, abstract_methods): - not_implemented = [f for f in abstract_methods if not callable(getattr(cls, f, None))] - if not_implemented: - raise NotImplementedError( - "The following methods on operation group '{}' are not implemented: '{}'." - " Please refer to https://aka.ms/azsdk/python/dpcodegen/python/customize to learn how to customize.".format( - cls.__name__, "', '".join(not_implemented) - ) - ) diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_version.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_version.py new file mode 100644 index 000000000000..67abacd47f96 --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.2.1" diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/__init__.py index 75020eabd3bb..dc63d9d6ff49 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/__init__.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/__init__.py @@ -1,21 +1,29 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import ContainerRegistry +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ContainerRegistryClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ - "ContainerRegistry", + "ContainerRegistryClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_client.py index 8bbf9d670fb1..1dad77be1359 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_client.py @@ -1,53 +1,77 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models -from .._serialization import Deserializer, Serializer -from ._configuration import ContainerRegistryConfiguration -from .operations import AuthenticationOperations, ContainerRegistryBlobOperations, ContainerRegistryOperations +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ContainerRegistryClientConfiguration +from .operations import ( + AuthenticationOperations, + ContainerRegistryBlobOperations, + ContainerRegistryOperations, +) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class ContainerRegistry: # pylint: disable=client-accepts-api-version-keyword +class ContainerRegistryClient: """Metadata API definition for the Azure Container Registry runtime. :ivar container_registry: ContainerRegistryOperations operations - :vartype container_registry: container_registry.aio.operations.ContainerRegistryOperations + :vartype container_registry: + azure.containerregistry._generated.aio.operations.ContainerRegistryOperations :ivar container_registry_blob: ContainerRegistryBlobOperations operations :vartype container_registry_blob: - container_registry.aio.operations.ContainerRegistryBlobOperations + azure.containerregistry._generated.aio.operations.ContainerRegistryBlobOperations :ivar authentication: AuthenticationOperations operations - :vartype authentication: container_registry.aio.operations.AuthenticationOperations - :param url: Registry login URL. Required. - :type url: str - :param credential: Credential needed for the client to connect to Azure. Required. + :vartype authentication: + azure.containerregistry._generated.aio.operations.AuthenticationOperations + :param endpoint: Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is "2021-07-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - _endpoint = "{url}" - self._config = ContainerRegistryConfiguration(url=url, credential=credential, **kwargs) - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)} - client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)}) - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = ContainerRegistryClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + (policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None), + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.container_registry = ContainerRegistryOperations( self._client, self._config, self._serialize, self._deserialize @@ -57,7 +81,9 @@ def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) ) self.authentication = AuthenticationOperations(self._client, self._config, self._serialize, self._deserialize) - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -77,16 +103,16 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHt request_copy = deepcopy(request) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "ContainerRegistry": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_configuration.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_configuration.py index d423202b4dbd..3b4fcb474aeb 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_configuration.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_configuration.py @@ -1,50 +1,50 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies +from .._version import VERSION + if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -VERSION = "unknown" - -class ContainerRegistryConfiguration(Configuration): # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for ContainerRegistry. +class ContainerRegistryClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ContainerRegistryClient. Note that all parameters used to create this instance are saved as instance attributes. - :param url: Registry login URL. Required. - :type url: str - :param credential: Credential needed for the client to connect to Azure. Required. + :param endpoint: Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is "2021-07-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(ContainerRegistryConfiguration, self).__init__(**kwargs) + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2021-07-01") - if url is None: - raise ValueError("Parameter 'url' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") if credential is None: raise ValueError("Parameter 'credential' must not be None.") - self.url = url + self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", []) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://containerregistry.azure.net/.default"]) kwargs.setdefault("sdk_moniker", "containerregistry/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -53,12 +53,10 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") - if not self.credential_scopes and not self.authentication_policy: - raise ValueError("You must provide either credential_scopes or authentication_policy as kwargs") if self.credential and not self.authentication_policy: self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( self.credential, *self.credential_scopes, **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_patch.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_patch.py index 17dbc073e01b..ea765788358a 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_patch.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_patch.py @@ -1,32 +1,20 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_vendor.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_vendor.py deleted file mode 100644 index b89fce811475..000000000000 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/_vendor.py +++ /dev/null @@ -1,15 +0,0 @@ -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def raise_if_not_implemented(cls, abstract_methods): - not_implemented = [f for f in abstract_methods if not callable(getattr(cls, f, None))] - if not_implemented: - raise NotImplementedError( - "The following methods on operation group '{}' are not implemented: '{}'." - " Please refer to https://aka.ms/azsdk/python/dpcodegen/python/customize to learn how to customize.".format( - cls.__name__, "', '".join(not_implemented) - ) - ) diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/__init__.py index bcf2637fb304..461f85a3cebf 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/__init__.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/__init__.py @@ -1,15 +1,23 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import ContainerRegistryOperations -from ._operations import ContainerRegistryBlobOperations -from ._operations import AuthenticationOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ContainerRegistryOperations # type: ignore +from ._operations import ContainerRegistryBlobOperations # type: ignore +from ._operations import AuthenticationOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -17,5 +25,5 @@ "ContainerRegistryBlobOperations", "AuthenticationOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_operations.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_operations.py index f4264266a1dd..bd7874820008 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_operations.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_operations.py @@ -1,13 +1,18 @@ # pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, overload +import json +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,6 +20,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -24,7 +31,18 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models +from ..._utils.model_base import ( + Model as _Model, + SdkJSONEncoder, + _deserialize, + _failsafe_deserialize, +) +from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import prepare_multipart_form_data from ...operations._operations import ( + build_authentication_exchange_aad_access_token_for_acr_refresh_token_request, + build_authentication_exchange_acr_refresh_token_for_acr_access_token_request, + build_authentication_get_acr_access_token_from_login_request, build_container_registry_blob_cancel_upload_request, build_container_registry_blob_check_blob_exists_request, build_container_registry_blob_check_chunk_exists_request, @@ -52,10 +70,11 @@ build_container_registry_update_properties_request, build_container_registry_update_tag_attributes_request, ) -from .._vendor import raise_if_not_implemented +from .._configuration import ContainerRegistryClientConfiguration +JSON = MutableMapping[str, Any] T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] class ContainerRegistryOperations: @@ -64,28 +83,26 @@ class ContainerRegistryOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~container_registry.aio.ContainerRegistry`'s + :class:`~azure.containerregistry._generated.aio.ContainerRegistryClient`'s :attr:`container_registry` attribute. """ - models = _models - def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ContainerRegistryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def check_docker_v2_support(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def check_docker_v2_support(self, **kwargs: Any) -> None: """Tells whether this Docker Registry instance supports Docker Registry HTTP API v2. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -98,38 +115,40 @@ async def check_docker_v2_support(self, **kwargs: Any) -> None: # pylint: disab cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_check_docker_v2_support_request( + _request = build_container_registry_check_docker_v2_support_request( + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get_manifest( self, name: str, reference: str, *, accept: Optional[str] = None, **kwargs: Any - ) -> AsyncIterator[bytes]: - """Get the manifest identified by ``name`` and ``reference`` where ``reference`` can be a tag or - digest. + ) -> _models.ManifestWrapper: + """Get the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. :param name: Name of the image (including the namespace). Required. :type name: str @@ -138,11 +157,11 @@ async def get_manifest( :keyword accept: Accept header string delimited by comma. For example, application/vnd.docker.distribution.manifest.v2+json. Default value is None. :paramtype accept: str - :return: Async iterator of the response bytes - :rtype: AsyncIterator[bytes] + :return: ManifestWrapper. The ManifestWrapper is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ManifestWrapper :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -153,57 +172,151 @@ async def get_manifest( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + cls: ClsType[_models.ManifestWrapper] = kwargs.pop("cls", None) - request = build_container_registry_get_manifest_request( + _request = build_container_registry_get_manifest_request( name=name, reference=reference, accept=accept, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = True + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = response.iter_bytes() + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ManifestWrapper, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace_async - async def create_manifest(self, name: str, reference: str, payload: IO, **kwargs: Any) -> Any: - """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be a tag or - digest. + @overload + async def create_manifest( + self, + name: str, + reference: str, + payload: _models.Manifest, + *, + content_type: str = "application/vnd.docker.distribution.manifest.v2+json", + **kwargs: Any + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: A tag or a digest, pointing to a specific image. Required. + :type reference: str + :param payload: Manifest body, can take v1 or v2 values depending on accept header. Required. + :type payload: ~azure.containerregistry._generated.models.Manifest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/vnd.docker.distribution.manifest.v2+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_manifest( + self, + name: str, + reference: str, + payload: JSON, + *, + content_type: str = "application/vnd.docker.distribution.manifest.v2+json", + **kwargs: Any + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: A tag or a digest, pointing to a specific image. Required. + :type reference: str + :param payload: Manifest body, can take v1 or v2 values depending on accept header. Required. + :type payload: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/vnd.docker.distribution.manifest.v2+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_manifest( + self, + name: str, + reference: str, + payload: IO[bytes], + *, + content_type: str = "application/vnd.docker.distribution.manifest.v2+json", + **kwargs: Any + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. :param name: Name of the image (including the namespace). Required. :type name: str :param reference: A tag or a digest, pointing to a specific image. Required. :type reference: str :param payload: Manifest body, can take v1 or v2 values depending on accept header. Required. - :type payload: IO - :return: any - :rtype: any + :type payload: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/vnd.docker.distribution.manifest.v2+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_manifest( + self, name: str, reference: str, payload: Union[_models.Manifest, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: A tag or a digest, pointing to a specific image. Required. + :type reference: str + :param payload: Manifest body, can take v1 or v2 values depending on accept header. Is one of + the following types: Manifest, JSON, IO[bytes] Required. + :type payload: ~azure.containerregistry._generated.models.Manifest or JSON or IO[bytes] + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -214,60 +327,59 @@ async def create_manifest(self, name: str, reference: str, payload: IO, **kwargs _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") - ) - cls: ClsType[Any] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) - _content = payload + content_type = content_type or "application/vnd.docker.distribution.manifest.v2+json" + _content = None + if isinstance(payload, (IOBase, bytes)): + _content = payload + else: + _content = json.dumps(payload, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_container_registry_create_manifest_request( + _request = build_container_registry_create_manifest_request( name=name, reference=reference, content_type=content_type, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) response_headers["Docker-Content-Digest"] = self._deserialize( "str", response.headers.get("Docker-Content-Digest") ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - - deserialized = self._deserialize("object", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def delete_manifest( # pylint: disable=inconsistent-return-statements - self, name: str, reference: str, **kwargs: Any - ) -> None: - """Delete the manifest identified by ``name`` and ``reference``. Note that a manifest can *only* - be deleted by ``digest``. + async def delete_manifest(self, name: str, reference: str, **kwargs: Any) -> None: + """Delete the manifest identified by ``name`` and ``reference``. Note that a manifest + can *only* be deleted by ``digest``. :param name: Name of the image (including the namespace). Required. :type name: str @@ -277,7 +389,7 @@ async def delete_manifest( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -290,44 +402,46 @@ async def delete_manifest( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_delete_manifest_request( + _request = build_container_registry_delete_manifest_request( name=name, reference=reference, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 404]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get_repositories( self, *, last: Optional[str] = None, n: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[str]: + ) -> AsyncItemPaged[str]: """List repositories. :keyword last: Query parameter for the last item in previous query. Result set will include values lexically after last. Default value is None. :paramtype last: str - :keyword n: query parameter for max number of items. Default value is None. + :keyword n: Query parameter for max number of items. Default value is None. :paramtype n: int :return: An iterator like instance of str :rtype: ~azure.core.async_paging.AsyncItemPaged[str] @@ -336,9 +450,9 @@ def get_repositories( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.Repositories] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[list[str]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -349,7 +463,7 @@ def get_repositories( def prepare_request(next_link=None): if not next_link: - request = build_container_registry_get_repositories_request( + _request = build_container_registry_get_repositories_request( last=last, n=n, api_version=self._config.api_version, @@ -357,9 +471,14 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url( + "self._config.endpoint", + self._config.endpoint, + "str", + skip_quote=True, + ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -371,39 +490,49 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + params=_next_request_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url( + "self._config.endpoint", + self._config.endpoint, + "str", + skip_quote=True, + ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize( - _models._models.Repositories, pipeline_response # pylint: disable=protected-access - ) - list_of_elem = deserialized.repositories + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[str], deserialized.get("repositories", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.link or None, AsyncList(list_of_elem) + return deserialized.get("link") or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -416,11 +545,12 @@ async def get_properties(self, name: str, **kwargs: Any) -> _models.ContainerRep :param name: Name of the image (including the namespace). Required. :type name: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -433,42 +563,49 @@ async def get_properties(self, name: str, **kwargs: Any) -> _models.ContainerRep cls: ClsType[_models.ContainerRepositoryProperties] = kwargs.pop("cls", None) - request = build_container_registry_get_properties_request( + _request = build_container_registry_get_properties_request( name=name, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ContainerRepositoryProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ContainerRepositoryProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async - async def delete_repository( # pylint: disable=inconsistent-return-statements - self, name: str, **kwargs: Any - ) -> None: + async def delete_repository(self, name: str, **kwargs: Any) -> None: """Delete the repository identified by ``name``. :param name: Name of the image (including the namespace). Required. @@ -477,7 +614,7 @@ async def delete_repository( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -490,33 +627,34 @@ async def delete_repository( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_delete_repository_request( + _request = build_container_registry_delete_repository_request( name=name, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 404]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @overload async def update_properties( @@ -527,57 +665,84 @@ async def update_properties( content_type: str = "application/json", **kwargs: Any ) -> _models.ContainerRepositoryProperties: - """Update the attribute identified by ``name`` where ``reference`` is the name of the repository. + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param value: Repository attribute value. Default value is None. + :type value: ~azure.containerregistry._generated.models.RepositoryWriteableProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_properties( + self, name: str, value: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ContainerRepositoryProperties: + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. :param name: Name of the image (including the namespace). Required. :type name: str :param value: Repository attribute value. Default value is None. - :type value: ~container_registry.models.RepositoryWriteableProperties + :type value: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update_properties( - self, name: str, value: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any + self, name: str, value: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ContainerRepositoryProperties: - """Update the attribute identified by ``name`` where ``reference`` is the name of the repository. + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. :param name: Name of the image (including the namespace). Required. :type name: str :param value: Repository attribute value. Default value is None. - :type value: IO + :type value: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update_properties( - self, name: str, value: Optional[Union[_models.RepositoryWriteableProperties, IO]] = None, **kwargs: Any + self, + name: str, + value: Optional[Union[_models.RepositoryWriteableProperties, JSON, IO[bytes]]] = None, + **kwargs: Any ) -> _models.ContainerRepositoryProperties: - """Update the attribute identified by ``name`` where ``reference`` is the name of the repository. + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. :param name: Name of the image (including the namespace). Required. :type name: str - :param value: Repository attribute value. Is either a RepositoryWriteableProperties type or a - IO type. Default value is None. - :type value: ~container_registry.models.RepositoryWriteableProperties or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :param value: Repository attribute value. Is one of the following types: + RepositoryWriteableProperties, JSON, IO[bytes] Default value is None. + :type value: ~azure.containerregistry._generated.models.RepositoryWriteableProperties or JSON + or IO[bytes] + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -589,65 +754,73 @@ async def update_properties( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if value else None cls: ClsType[_models.ContainerRepositoryProperties] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None + content_type = content_type or "application/json" if value else None _content = None if isinstance(value, (IOBase, bytes)): _content = value else: if value is not None: - _json = self._serialize.body(value, "RepositoryWriteableProperties") + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - request = build_container_registry_update_properties_request( + _request = build_container_registry_update_properties_request( name=name, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ContainerRepositoryProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ContainerRepositoryProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - @distributed_trace - def get_tags( + @distributed_trace_async + async def get_tags( self, name: str, *, last: Optional[str] = None, n: Optional[int] = None, - orderby: Optional[str] = None, + orderby: Optional[Union[str, _models.ArtifactTagOrder]] = None, digest: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.TagAttributesBase"]: + ) -> _models.TagList: """List tags of a repository. :param name: Name of the image (including the namespace). Required. @@ -657,20 +830,16 @@ def get_tags( :paramtype last: str :keyword n: query parameter for max number of items. Default value is None. :paramtype n: int - :keyword orderby: orderby query parameter. Default value is None. - :paramtype orderby: str + :keyword orderby: orderby query parameter. Known values are: "none", "timedesc", and "timeasc". + Default value is None. + :paramtype orderby: str or ~azure.containerregistry._generated.models.ArtifactTagOrder :keyword digest: filter by digest. Default value is None. :paramtype digest: str - :return: An iterator like instance of TagAttributesBase - :rtype: ~azure.core.async_paging.AsyncItemPaged[~container_registry.models.TagAttributesBase] + :return: TagList. The TagList is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.TagList :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models._models.TagList] = kwargs.pop("cls", None) # pylint: disable=protected-access - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -678,72 +847,58 @@ def get_tags( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - request = build_container_registry_get_tags_request( - name=name, - last=last, - n=n, - orderby=orderby, - digest=digest, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + cls: ClsType[_models.TagList] = kwargs.pop("cls", None) - return request + _request = build_container_registry_get_tags_request( + name=name, + last=last, + n=n, + orderby=orderby, + digest=digest, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - async def extract_data(pipeline_response): - deserialized = self._deserialize( - _models._models.TagList, pipeline_response # pylint: disable=protected-access - ) - list_of_elem = deserialized.tag_attribute_bases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.link or None, AsyncList(list_of_elem) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) - raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) - return pipeline_response + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.TagList, response.json()) - return AsyncItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async async def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> _models.ArtifactTagProperties: @@ -753,11 +908,11 @@ async def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> :type name: str :param reference: Tag name. Required. :type reference: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -770,7 +925,7 @@ async def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> cls: ClsType[_models.ArtifactTagProperties] = kwargs.pop("cls", None) - request = build_container_registry_get_tag_properties_request( + _request = build_container_registry_get_tag_properties_request( name=name, reference=reference, api_version=self._config.api_version, @@ -778,30 +933,39 @@ async def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactTagProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactTagProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @overload async def update_tag_attributes( @@ -820,12 +984,38 @@ async def update_tag_attributes( :param reference: Tag name. Required. :type reference: str :param value: Tag attribute value. Default value is None. - :type value: ~container_registry.models.TagWriteableProperties + :type value: ~azure.containerregistry._generated.models.TagWriteableProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_tag_attributes( + self, + name: str, + reference: str, + value: Optional[JSON] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArtifactTagProperties: + """Update tag attributes. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: Tag name. Required. + :type reference: str + :param value: Tag attribute value. Default value is None. + :type value: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -834,7 +1024,7 @@ async def update_tag_attributes( self, name: str, reference: str, - value: Optional[IO] = None, + value: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -846,12 +1036,12 @@ async def update_tag_attributes( :param reference: Tag name. Required. :type reference: str :param value: Tag attribute value. Default value is None. - :type value: IO + :type value: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -860,7 +1050,7 @@ async def update_tag_attributes( self, name: str, reference: str, - value: Optional[Union[_models.TagWriteableProperties, IO]] = None, + value: Optional[Union[_models.TagWriteableProperties, JSON, IO[bytes]]] = None, **kwargs: Any ) -> _models.ArtifactTagProperties: """Update tag attributes. @@ -869,17 +1059,15 @@ async def update_tag_attributes( :type name: str :param reference: Tag name. Required. :type reference: str - :param value: Tag attribute value. Is either a TagWriteableProperties type or a IO type. - Default value is None. - :type value: ~container_registry.models.TagWriteableProperties or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :param value: Tag attribute value. Is one of the following types: TagWriteableProperties, JSON, + IO[bytes] Default value is None. + :type value: ~azure.containerregistry._generated.models.TagWriteableProperties or JSON or + IO[bytes] + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -891,59 +1079,65 @@ async def update_tag_attributes( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if value else None cls: ClsType[_models.ArtifactTagProperties] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None + content_type = content_type or "application/json" if value else None _content = None if isinstance(value, (IOBase, bytes)): _content = value else: if value is not None: - _json = self._serialize.body(value, "TagWriteableProperties") + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - request = build_container_registry_update_tag_attributes_request( + _request = build_container_registry_update_tag_attributes_request( name=name, reference=reference, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactTagProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactTagProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async - async def delete_tag( # pylint: disable=inconsistent-return-statements - self, name: str, reference: str, **kwargs: Any - ) -> None: + async def delete_tag(self, name: str, reference: str, **kwargs: Any) -> None: """Delete tag. :param name: Name of the image (including the namespace). Required. @@ -954,7 +1148,7 @@ async def delete_tag( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -967,7 +1161,7 @@ async def delete_tag( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_delete_tag_request( + _request = build_container_registry_delete_tag_request( name=name, reference=reference, api_version=self._config.api_version, @@ -975,37 +1169,38 @@ async def delete_tag( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 404]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore - @distributed_trace - def get_manifests( + @distributed_trace_async + async def get_manifests( self, name: str, *, last: Optional[str] = None, n: Optional[int] = None, - orderby: Optional[str] = None, + orderby: Optional[Union[str, _models.ArtifactManifestOrder]] = None, **kwargs: Any - ) -> AsyncIterable["_models.ManifestAttributesBase"]: + ) -> _models.AcrManifests: """List manifests of a repository. :param name: Name of the image (including the namespace). Required. @@ -1015,19 +1210,14 @@ def get_manifests( :paramtype last: str :keyword n: query parameter for max number of items. Default value is None. :paramtype n: int - :keyword orderby: orderby query parameter. Default value is None. - :paramtype orderby: str - :return: An iterator like instance of ManifestAttributesBase - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~container_registry.models.ManifestAttributesBase] + :keyword orderby: orderby query parameter. Known values are: "none", "timedesc", and "timeasc". + Default value is None. + :paramtype orderby: str or ~azure.containerregistry._generated.models.ArtifactManifestOrder + :return: AcrManifests. The AcrManifests is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrManifests :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models._models.AcrManifests] = kwargs.pop("cls", None) # pylint: disable=protected-access - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1035,71 +1225,57 @@ def get_manifests( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - request = build_container_registry_get_manifests_request( - name=name, - last=last, - n=n, - orderby=orderby, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + cls: ClsType[_models.AcrManifests] = kwargs.pop("cls", None) - return request + _request = build_container_registry_get_manifests_request( + name=name, + last=last, + n=n, + orderby=orderby, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - async def extract_data(pipeline_response): - deserialized = self._deserialize( - _models._models.AcrManifests, pipeline_response # pylint: disable=protected-access - ) - list_of_elem = deserialized.manifests - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.link or None, AsyncList(list_of_elem) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) - raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) - return pipeline_response + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrManifests, response.json()) - return AsyncItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async async def get_manifest_properties( @@ -1111,11 +1287,12 @@ async def get_manifest_properties( :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1128,7 +1305,7 @@ async def get_manifest_properties( cls: ClsType[_models.ArtifactManifestProperties] = kwargs.pop("cls", None) - request = build_container_registry_get_manifest_properties_request( + _request = build_container_registry_get_manifest_properties_request( name=name, digest=digest, api_version=self._config.api_version, @@ -1136,30 +1313,39 @@ async def get_manifest_properties( params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactManifestProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactManifestProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @overload async def update_manifest_properties( @@ -1178,12 +1364,13 @@ async def update_manifest_properties( :param digest: Digest of a BLOB. Required. :type digest: str :param value: Manifest attribute value. Default value is None. - :type value: ~container_registry.models.ManifestWriteableProperties + :type value: ~azure.containerregistry._generated.models.ManifestWriteableProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1192,7 +1379,7 @@ async def update_manifest_properties( self, name: str, digest: str, - value: Optional[IO] = None, + value: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any @@ -1204,12 +1391,40 @@ async def update_manifest_properties( :param digest: Digest of a BLOB. Required. :type digest: str :param value: Manifest attribute value. Default value is None. - :type value: IO + :type value: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_manifest_properties( + self, + name: str, + digest: str, + value: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArtifactManifestProperties: + """Update properties of a manifest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param digest: Digest of a BLOB. Required. + :type digest: str + :param value: Manifest attribute value. Default value is None. + :type value: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1218,7 +1433,7 @@ async def update_manifest_properties( self, name: str, digest: str, - value: Optional[Union[_models.ManifestWriteableProperties, IO]] = None, + value: Optional[Union[_models.ManifestWriteableProperties, JSON, IO[bytes]]] = None, **kwargs: Any ) -> _models.ArtifactManifestProperties: """Update properties of a manifest. @@ -1227,17 +1442,16 @@ async def update_manifest_properties( :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :param value: Manifest attribute value. Is either a ManifestWriteableProperties type or a IO - type. Default value is None. - :type value: ~container_registry.models.ManifestWriteableProperties or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :param value: Manifest attribute value. Is one of the following types: + ManifestWriteableProperties, JSON, IO[bytes] Default value is None. + :type value: ~azure.containerregistry._generated.models.ManifestWriteableProperties or JSON or + IO[bytes] + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1249,54 +1463,62 @@ async def update_manifest_properties( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if value else None cls: ClsType[_models.ArtifactManifestProperties] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None + content_type = content_type or "application/json" if value else None _content = None if isinstance(value, (IOBase, bytes)): _content = value else: if value is not None: - _json = self._serialize.body(value, "ManifestWriteableProperties") + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - request = build_container_registry_update_manifest_properties_request( + _request = build_container_registry_update_manifest_properties_request( name=name, digest=digest, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactManifestProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactManifestProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore class ContainerRegistryBlobOperations: @@ -1305,18 +1527,16 @@ class ContainerRegistryBlobOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~container_registry.aio.ContainerRegistry`'s + :class:`~azure.containerregistry._generated.aio.ContainerRegistryClient`'s :attr:`container_registry_blob` attribute. """ - models = _models - def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ContainerRegistryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[AsyncIterator[bytes]]: @@ -1326,11 +1546,11 @@ async def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Asyn :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :return: Async iterator of the response bytes or None + :return: AsyncIterator[bytes] or None :rtype: AsyncIterator[bytes] or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1343,29 +1563,37 @@ async def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Asyn cls: ClsType[Optional[AsyncIterator[bytes]]] = kwargs.pop("cls", None) - request = build_container_registry_blob_get_blob_request( + _request = build_container_registry_blob_get_blob_request( name=name, digest=digest, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = True + _stream = kwargs.pop("stream", True) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 307]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) deserialized = None response_headers = {} @@ -1375,31 +1603,29 @@ async def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Asyn "str", response.headers.get("Docker-Content-Digest") ) - deserialized = response.iter_bytes() - if response.status_code == 307: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async - async def check_blob_exists( # pylint: disable=inconsistent-return-statements - self, name: str, digest: str, **kwargs: Any - ) -> None: + async def check_blob_exists(self, name: str, digest: str, **kwargs: Any) -> bool: """Same as GET, except only the headers are returned. :param name: Name of the image (including the namespace). Required. :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :return: None - :rtype: None + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1412,29 +1638,31 @@ async def check_blob_exists( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_check_blob_exists_request( + _request = build_container_registry_blob_check_blob_exists_request( name=name, digest=digest, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 307]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1448,12 +1676,11 @@ async def check_blob_exists( # pylint: disable=inconsistent-return-statements response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace_async - async def delete_blob( # pylint: disable=inconsistent-return-statements - self, name: str, digest: str, **kwargs: Any - ) -> None: + async def delete_blob(self, name: str, digest: str, **kwargs: Any) -> None: """Removes an already uploaded blob. :param name: Name of the image (including the namespace). Required. @@ -1464,7 +1691,7 @@ async def delete_blob( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1477,29 +1704,32 @@ async def delete_blob( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_delete_blob_request( + _request = build_container_registry_blob_delete_blob_request( name=name, digest=digest, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Docker-Content-Digest"] = self._deserialize( @@ -1507,12 +1737,10 @@ async def delete_blob( # pylint: disable=inconsistent-return-statements ) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def mount_blob( # pylint: disable=inconsistent-return-statements - self, name: str, *, from_parameter: str, mount: str, **kwargs: Any - ) -> None: + async def mount_blob(self, name: str, *, from_parameter: str, mount: str, **kwargs: Any) -> None: """Mount a blob identified by the ``mount`` parameter from another repository. :param name: Name of the image (including the namespace). Required. @@ -1525,7 +1753,7 @@ async def mount_blob( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1538,30 +1766,32 @@ async def mount_blob( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_mount_blob_request( + _request = build_container_registry_blob_mount_blob_request( name=name, from_parameter=from_parameter, mount=mount, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1572,23 +1802,22 @@ async def mount_blob( # pylint: disable=inconsistent-return-statements ) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_upload_status( # pylint: disable=inconsistent-return-statements - self, next_link: str, **kwargs: Any - ) -> None: - """Retrieve status of upload identified by uuid. The primary purpose of this endpoint is to - resolve the current status of a resumable upload. - - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + async def get_upload_status(self, next_blob_uuid_link: str, **kwargs: Any) -> None: + """Retrieve status of upload identified by uuid. The primary purpose of this + endpoint is to resolve the current status of a resumable upload. + + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1601,28 +1830,30 @@ async def get_upload_status( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_get_upload_status_request( - next_link=next_link, + _request = build_container_registry_blob_get_upload_status_request( + next_blob_uuid_link=next_blob_uuid_link, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1630,24 +1861,23 @@ async def get_upload_status( # pylint: disable=inconsistent-return-statements response_headers["Docker-Upload-UUID"] = self._deserialize("str", response.headers.get("Docker-Upload-UUID")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def upload_chunk( # pylint: disable=inconsistent-return-statements - self, next_link: str, value: IO, **kwargs: Any - ) -> None: + async def upload_chunk(self, next_blob_uuid_link: str, value: bytes, **kwargs: Any) -> None: """Upload a stream of data without completing the upload. - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :param value: Raw data of blob. Required. - :type value: IO + :type value: bytes :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1663,30 +1893,32 @@ async def upload_chunk( # pylint: disable=inconsistent-return-statements _content = value - request = build_container_registry_blob_upload_chunk_request( - next_link=next_link, + _request = build_container_registry_blob_upload_chunk_request( + next_blob_uuid_link=next_blob_uuid_link, content_type=content_type, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1695,27 +1927,29 @@ async def upload_chunk( # pylint: disable=inconsistent-return-statements response_headers["Docker-Upload-UUID"] = self._deserialize("str", response.headers.get("Docker-Upload-UUID")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def complete_upload( # pylint: disable=inconsistent-return-statements - self, next_link: str, value: Optional[IO] = None, *, digest: str, **kwargs: Any + async def complete_upload( + self, next_blob_uuid_link: str, value: Optional[bytes] = None, *, digest: str, **kwargs: Any ) -> None: - """Complete the upload, providing all the data in the body, if necessary. A request without a body - will just complete the upload with previously uploaded content. + """Complete the upload, providing all the data in the body, if necessary. A + request without a body will just complete the upload with previously uploaded + content. - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :param value: Optional raw data of blob. Default value is None. - :type value: IO + :type value: bytes :keyword digest: Digest of a BLOB. Required. :paramtype digest: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1726,36 +1960,41 @@ async def complete_upload( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/octet-stream")) + content_type: Optional[str] = kwargs.pop( + "content_type", _headers.pop("Content-Type", "application/octet-stream") + ) + content_type = content_type if value else None cls: ClsType[None] = kwargs.pop("cls", None) _content = value - request = build_container_registry_blob_complete_upload_request( - next_link=next_link, + _request = build_container_registry_blob_complete_upload_request( + next_blob_uuid_link=next_blob_uuid_link, digest=digest, content_type=content_type, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1766,23 +2005,22 @@ async def complete_upload( # pylint: disable=inconsistent-return-statements ) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def cancel_upload( # pylint: disable=inconsistent-return-statements - self, next_link: str, **kwargs: Any - ) -> None: - """Cancel outstanding upload processes, releasing associated resources. If this is not called, the - unfinished uploads will eventually timeout. - - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + async def cancel_upload(self, next_blob_uuid_link: str, **kwargs: Any) -> None: + """Cancel outstanding upload processes, releasing associated resources. If this is + not called, the unfinished uploads will eventually timeout. + + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1795,35 +2033,37 @@ async def cancel_upload( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_cancel_upload_request( - next_link=next_link, + _request = build_container_registry_blob_cancel_upload_request( + next_blob_uuid_link=next_blob_uuid_link, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def start_upload(self, name: str, **kwargs: Any) -> None: """Initiate a resumable blob upload with an empty request body. :param name: Name of the image (including the namespace). Required. @@ -1832,7 +2072,7 @@ async def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disab :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1845,28 +2085,30 @@ async def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disab cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_start_upload_request( + _request = build_container_registry_blob_start_upload_request( name=name, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1875,27 +2117,27 @@ async def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disab response_headers["Docker-Upload-UUID"] = self._deserialize("str", response.headers.get("Docker-Upload-UUID")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_chunk(self, name: str, digest: str, *, range_header: str, **kwargs: Any) -> AsyncIterator[bytes]: - """Retrieve the blob from the registry identified by ``digest``. This endpoint may also support - RFC7233 compliant range requests. Support can be detected by issuing a HEAD request. If the - header ``Accept-Range: bytes`` is returned, range requests can be used to fetch partial - content. + async def get_chunk(self, name: str, digest: str, *, range: str, **kwargs: Any) -> AsyncIterator[bytes]: + """Retrieve the blob from the registry identified by ``digest``. This endpoint may + also support RFC7233 compliant range requests. Support can be detected by + issuing a HEAD request. If the header ``Accept-Range: bytes`` is returned, range + requests can be used to fetch partial content. :param name: Name of the image (including the namespace). Required. :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :keyword range_header: Format : bytes=:code:``-:code:``, HTTP Range header - specifying blob chunk. Required. - :paramtype range_header: str - :return: Async iterator of the response bytes + :keyword range: Format : bytes=-, HTTP Range header specifying blob chunk. + Required. + :paramtype range: str + :return: AsyncIterator[bytes] :rtype: AsyncIterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1908,30 +2150,38 @@ async def get_chunk(self, name: str, digest: str, *, range_header: str, **kwargs cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_container_registry_blob_get_chunk_request( + _request = build_container_registry_blob_get_chunk_request( name=name, digest=digest, - range_header=range_header, + range=range, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = True + _stream = kwargs.pop("stream", True) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [206]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) @@ -1945,23 +2195,21 @@ async def get_chunk(self, name: str, digest: str, *, range_header: str, **kwargs return deserialized # type: ignore @distributed_trace_async - async def check_chunk_exists( # pylint: disable=inconsistent-return-statements - self, name: str, digest: str, *, range_header: str, **kwargs: Any - ) -> None: + async def check_chunk_exists(self, name: str, digest: str, *, range: str, **kwargs: Any) -> bool: """Same as GET, except only the headers are returned. :param name: Name of the image (including the namespace). Required. :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :keyword range_header: Format : bytes=:code:``-:code:``, HTTP Range header - specifying blob chunk. Required. - :paramtype range_header: str - :return: None - :rtype: None + :keyword range: Format : bytes=-, HTTP Range header specifying blob chunk. + Required. + :paramtype range: str + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1974,30 +2222,32 @@ async def check_chunk_exists( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_check_chunk_exists_request( + _request = build_container_registry_blob_check_chunk_exists_request( name=name, digest=digest, - range_header=range_header, + range=range, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2005,31 +2255,300 @@ async def check_chunk_exists( # pylint: disable=inconsistent-return-statements response_headers["Content-Range"] = self._deserialize("str", response.headers.get("Content-Range")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 -class AuthenticationOperations: # pylint: disable=abstract-class-instantiated +class AuthenticationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~container_registry.aio.ContainerRegistry`'s + :class:`~azure.containerregistry._generated.aio.ContainerRegistryClient`'s :attr:`authentication` attribute. """ - models = _models - def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - raise_if_not_implemented( - self.__class__, - [ - "exchange_aad_access_token_for_acr_refresh_token", - "exchange_acr_refresh_token_for_acr_access_token", - ], + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ContainerRegistryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def exchange_aad_access_token_for_acr_refresh_token( # pylint: disable=name-too-long + self, body: _models.MultipartBodyParameter, **kwargs: Any + ) -> _models.AcrRefreshToken: + """Exchange AAD tokens for an ACR refresh Token. + + :param body: The body of the request. Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter + :return: AcrRefreshToken. The AcrRefreshToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrRefreshToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def exchange_aad_access_token_for_acr_refresh_token( # pylint: disable=name-too-long + self, body: JSON, **kwargs: Any + ) -> _models.AcrRefreshToken: + """Exchange AAD tokens for an ACR refresh Token. + + :param body: The body of the request. Required. + :type body: JSON + :return: AcrRefreshToken. The AcrRefreshToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrRefreshToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def exchange_aad_access_token_for_acr_refresh_token( # pylint: disable=name-too-long + self, body: Union[_models.MultipartBodyParameter, JSON], **kwargs: Any + ) -> _models.AcrRefreshToken: + """Exchange AAD tokens for an ACR refresh Token. + + :param body: The body of the request. Is either a MultipartBodyParameter type or a JSON type. + Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter or JSON + :return: AcrRefreshToken. The AcrRefreshToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrRefreshToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AcrRefreshToken] = kwargs.pop("cls", None) + + _body = body.as_dict() if isinstance(body, _Model) else body + _file_fields: list[str] = [] + _data_fields: list[str] = [ + "grantType", + "service", + "tenant", + "refreshToken", + "accessToken", + ] + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) + + _request = build_authentication_exchange_aad_access_token_for_acr_refresh_token_request( + files=_files, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrRefreshToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def exchange_acr_refresh_token_for_acr_access_token( # pylint: disable=name-too-long + self, body: _models.MultipartBodyParameter, **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange ACR Refresh token for an ACR Access Token. + + :param body: The body of the request. Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def exchange_acr_refresh_token_for_acr_access_token( # pylint: disable=name-too-long + self, body: JSON, **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange ACR Refresh token for an ACR Access Token. + + :param body: The body of the request. Required. + :type body: JSON + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def exchange_acr_refresh_token_for_acr_access_token( # pylint: disable=name-too-long + self, body: Union[_models.MultipartBodyParameter, JSON], **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange ACR Refresh token for an ACR Access Token. + + :param body: The body of the request. Is either a MultipartBodyParameter type or a JSON type. + Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter or JSON + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AcrAccessToken] = kwargs.pop("cls", None) + + _body = body.as_dict() if isinstance(body, _Model) else body + _file_fields: list[str] = [] + _data_fields: list[str] = [ + "grantType", + "service", + "tenant", + "refreshToken", + "accessToken", + ] + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) + + _request = build_authentication_exchange_acr_refresh_token_for_acr_access_token_request( + files=_files, + headers=_headers, + params=_params, ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrAccessToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_acr_access_token_from_login( + self, *, service: str, scope: str, **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange Username, Password and Scope for an ACR Access Token. + + :keyword service: Indicates the name of your Azure container registry. Required. + :paramtype service: str + :keyword scope: Expected to be a valid scope, and can be specified more than once for multiple + scope requests. You can obtain this from the Www-Authenticate response header + from the challenge. Required. + :paramtype scope: str + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AcrAccessToken] = kwargs.pop("cls", None) + + _request = build_authentication_get_acr_access_token_from_login_request( + service=service, + scope=scope, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrAccessToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_patch.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_patch.py index 28f7b7d642e0..87048bb0e1f8 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_patch.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_patch.py @@ -1,12 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Callable, Dict, Optional, TypeVar, Union + +from typing import Any, Optional, TypeVar, Union from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,26 +18,24 @@ ResourceNotFoundError, map_error, ) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from ... import models as _models -from ._operations import AuthenticationOperations as AuthenticationOperationsGenerated +from ...operations import AuthenticationOperations as AuthenticationOperationsGenerated from ...operations._patch import ( build_exchange_aad_access_token_for_acr_refresh_token_request, build_exchange_acr_refresh_token_for_acr_access_token_request, ) +from ..._utils.model_base import _deserialize, _failsafe_deserialize + T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AuthenticationOperations(AuthenticationOperationsGenerated): @distributed_trace_async - async def exchange_aad_access_token_for_acr_refresh_token( + async def exchange_aad_access_token_for_acr_refresh_token( # type: ignore[override] # pylint: disable=name-too-long, docstring-keyword-should-match-keyword-only, invalid-overridden-method self, grant_type: Union[str, "_models.PostContentSchemaGrantType"], service: str, @@ -44,25 +45,30 @@ async def exchange_aad_access_token_for_acr_refresh_token( **kwargs: Any ) -> _models.AcrRefreshToken: """Exchange AAD tokens for an ACR refresh Token. + :param grant_type: Can take a value of access_token_refresh_token, or access_token, or - refresh_token. + refresh_token. :type grant_type: str or ~container_registry.models.PostContentSchemaGrantType :param service: Indicates the name of your Azure container registry. :type service: str :param tenant: AAD tenant associated to the AAD credentials. Default value is None. :type tenant: str :param refresh_token: AAD refresh token, mandatory when grant_type is - access_token_refresh_token or refresh_token. Default value is None. + access_token_refresh_token or refresh_token. Default value is None. :type refresh_token: str :param access_token: AAD access token, mandatory when grant_type is access_token_refresh_token - or access_token. Default value is None. + or access_token. Default value is None. :type access_token: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AcrRefreshToken, or the result of cls(response) :rtype: ~container_registry.models.AcrRefreshToken :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -70,9 +76,10 @@ async def exchange_aad_access_token_for_acr_refresh_token( api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # type: str content_type = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/x-www-form-urlencoded") + "content_type", + _headers.pop("Content-Type", "application/x-www-form-urlencoded"), ) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AcrRefreshToken] + cls = kwargs.pop("cls", None) # Construct form data _data = { @@ -91,7 +98,7 @@ async def exchange_aad_access_token_for_acr_refresh_token( params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore @@ -102,16 +109,16 @@ async def exchange_aad_access_token_for_acr_refresh_token( if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize(_models.AcrErrors, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("AcrRefreshToken", pipeline_response) + deserialized = _deserialize(_models.AcrRefreshToken, response.json()) if cls: return cls(pipeline_response, deserialized, {}) return deserialized @distributed_trace_async - async def exchange_acr_refresh_token_for_acr_access_token( + async def exchange_acr_refresh_token_for_acr_access_token( # type: ignore[override] # pylint: disable=name-too-long, docstring-keyword-should-match-keyword-only, invalid-overridden-method self, service: str, scope: str, @@ -120,23 +127,28 @@ async def exchange_acr_refresh_token_for_acr_access_token( **kwargs: Any ) -> _models.AcrAccessToken: """Exchange ACR Refresh token for an ACR Access Token. + :param service: Indicates the name of your Azure container registry. :type service: str :param scope: Which is expected to be a valid scope, and can be specified more than once for - multiple scope requests. You obtained this from the Www-Authenticate response header from the - challenge. + multiple scope requests. You obtained this from the Www-Authenticate response header from the + challenge. :type scope: str :param refresh_token: Must be a valid ACR refresh token. :type refresh_token: str :param grant_type: Grant type is expected to be refresh_token. Default value is - "refresh_token". + "refresh_token". :type grant_type: str or ~container_registry.models.TokenGrantType :keyword callable cls: A custom type or function that will be passed the direct response :return: AcrAccessToken, or the result of cls(response) :rtype: ~container_registry.models.AcrAccessToken :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -144,9 +156,10 @@ async def exchange_acr_refresh_token_for_acr_access_token( api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # type: str content_type = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/x-www-form-urlencoded") + "content_type", + _headers.pop("Content-Type", "application/x-www-form-urlencoded"), ) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AcrAccessToken] + cls = kwargs.pop("cls", None) # Construct form data _data = { @@ -164,7 +177,7 @@ async def exchange_acr_refresh_token_for_acr_access_token( params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore @@ -175,18 +188,18 @@ async def exchange_acr_refresh_token_for_acr_access_token( if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize(_models.AcrErrors, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("AcrAccessToken", pipeline_response) + deserialized = _deserialize(_models.AcrAccessToken, response.json()) if cls: return cls(pipeline_response, deserialized, {}) return deserialized -__all__ = [ - "AuthenticationOperations" -] # type: List[str] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [ + "AuthenticationOperations", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/__init__.py index c1a4cd394315..09fd77bff8c5 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/__init__.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/__init__.py @@ -1,66 +1,71 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models import AcrAccessToken -from ._models import AcrErrorInfo -from ._models import AcrErrors -from ._models import AcrRefreshToken -from ._models import Annotations -from ._models import ArtifactManifestPlatform -from ._models import ArtifactManifestProperties -from ._models import ArtifactTagProperties -from ._models import ContainerRepositoryProperties -from ._models import DeleteRepositoryResult -from ._models import Descriptor -from ._models import FsLayer -from ._models import History -from ._models import ImageSignature -from ._models import JWK -from ._models import JWKHeader -from ._models import Manifest -from ._models import ManifestAttributesBase -from ._models import ManifestAttributesManifest -from ._models import ManifestList -from ._models import ManifestListAttributes -from ._models import ManifestWrapper -from ._models import ManifestWriteableProperties -from ._models import OCIIndex -from ._models import OCIManifest -from ._models import Paths108HwamOauth2ExchangePostRequestbodyContentApplicationXWwwFormUrlencodedSchema -from ._models import PathsV3R3RxOauth2TokenPostRequestbodyContentApplicationXWwwFormUrlencodedSchema -from ._models import Platform -from ._models import RepositoryTags -from ._models import RepositoryWriteableProperties -from ._models import TagAttributesBase -from ._models import TagAttributesTag -from ._models import TagWriteableProperties -from ._models import V1Manifest -from ._models import V2Manifest +from typing import TYPE_CHECKING -from ._enums import ArtifactArchitecture -from ._enums import ArtifactManifestOrder -from ._enums import ArtifactOperatingSystem -from ._enums import ArtifactTagOrder -from ._enums import PostContentSchemaGrantType -from ._enums import TokenGrantType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AcrAccessToken, + AcrErrorInfo, + AcrErrors, + AcrManifests, + AcrRefreshToken, + Annotations, + ArtifactManifestPlatform, + ArtifactManifestProperties, + ArtifactTagProperties, + ContainerRepositoryProperties, + Descriptor, + FsLayer, + History, + ImageSignature, + JWK, + JWKHeader, + Manifest, + ManifestAttributesBase, + ManifestListAttributes, + ManifestWrapper, + ManifestWriteableProperties, + MultipartBodyParameter, + Platform, + RepositoryWriteableProperties, + TagAttributesBase, + TagList, + TagWriteableProperties, +) + +from ._enums import ( # type: ignore + ArtifactArchitecture, + ArtifactManifestOrder, + ArtifactOperatingSystem, + ArtifactTagOrder, + PostContentSchemaGrantType, + TokenGrantType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "AcrAccessToken", "AcrErrorInfo", "AcrErrors", + "AcrManifests", "AcrRefreshToken", "Annotations", "ArtifactManifestPlatform", "ArtifactManifestProperties", "ArtifactTagProperties", "ContainerRepositoryProperties", - "DeleteRepositoryResult", "Descriptor", "FsLayer", "History", @@ -69,23 +74,15 @@ "JWKHeader", "Manifest", "ManifestAttributesBase", - "ManifestAttributesManifest", - "ManifestList", "ManifestListAttributes", "ManifestWrapper", "ManifestWriteableProperties", - "OCIIndex", - "OCIManifest", - "Paths108HwamOauth2ExchangePostRequestbodyContentApplicationXWwwFormUrlencodedSchema", - "PathsV3R3RxOauth2TokenPostRequestbodyContentApplicationXWwwFormUrlencodedSchema", + "MultipartBodyParameter", "Platform", - "RepositoryTags", "RepositoryWriteableProperties", "TagAttributesBase", - "TagAttributesTag", + "TagList", "TagWriteableProperties", - "V1Manifest", - "V2Manifest", "ArtifactArchitecture", "ArtifactManifestOrder", "ArtifactOperatingSystem", @@ -93,5 +90,5 @@ "PostContentSchemaGrantType", "TokenGrantType", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_enums.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_enums.py index 2182c99cc41e..268c6e53a664 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_enums.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_enums.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -45,28 +47,44 @@ class ArtifactManifestOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): NONE = "none" """Do not provide an orderby value in the request.""" LAST_UPDATED_ON_DESCENDING = "timedesc" - """Order manifests by LastUpdatedOn field, from most recently updated to least recently updated.""" + """Order manifests by LastUpdatedOn field, from most recently updated to least + recently updated.""" LAST_UPDATED_ON_ASCENDING = "timeasc" - """Order manifest by LastUpdatedOn field, from least recently updated to most recently updated.""" + """Order manifest by LastUpdatedOn field, from least recently updated to most + recently updated.""" class ArtifactOperatingSystem(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ArtifactOperatingSystem.""" + """The artifact platform's operating system.""" AIX = "aix" + """AIX operating system""" ANDROID = "android" + """Android operating system""" DARWIN = "darwin" + """Darwin operating system""" DRAGONFLY = "dragonfly" + """Dragonfly operating system""" FREE_BSD = "freebsd" + """FreeBSD operating system""" ILLUMOS = "illumos" + """Illumos operating system""" I_OS = "ios" + """iOS operating system""" JS = "js" + """JavaScript operating system""" LINUX = "linux" + """Linux operating system""" NET_BSD = "netbsd" + """NetBSD operating system""" OPEN_BSD = "openbsd" + """OpenBSD operating system""" PLAN9 = "plan9" + """Plan 9 operating system""" SOLARIS = "solaris" + """Solaris operating system""" WINDOWS = "windows" + """Windows operating system""" class ArtifactTagOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -75,21 +93,30 @@ class ArtifactTagOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): NONE = "none" """Do not provide an orderby value in the request.""" LAST_UPDATED_ON_DESCENDING = "timedesc" - """Order tags by LastUpdatedOn field, from most recently updated to least recently updated.""" + """Order tags by LastUpdatedOn field, from most recently updated to least recently + updated.""" LAST_UPDATED_ON_ASCENDING = "timeasc" - """Order tags by LastUpdatedOn field, from least recently updated to most recently updated.""" + """Order tags by LastUpdatedOn field, from least recently updated to most recently + updated.""" class PostContentSchemaGrantType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Can take a value of access_token_refresh_token, or access_token, or refresh_token.""" + """Can take a value of access_token_refresh_token, or access_token, or + refresh_token. + """ ACCESS_TOKEN_REFRESH_TOKEN = "access_token_refresh_token" + """Grant type for exchanging both access token and refresh token""" ACCESS_TOKEN = "access_token" + """Grant type for exchanging access token only""" REFRESH_TOKEN = "refresh_token" + """Grant type for exchanging refresh token only""" class TokenGrantType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Grant type is expected to be refresh_token.""" REFRESH_TOKEN = "refresh_token" + """Grant type for refreshing the token""" PASSWORD = "password" + """Grant type for password authentication""" diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_models.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_models.py index 7c2d829ebf55..8457c145d7ac 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_models.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_models.py @@ -1,48 +1,51 @@ -# coding=utf-8 # pylint: disable=too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation import datetime -import sys -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union +from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload -from .. import _serialization - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class AcrAccessToken(_serialization.Model): - """AcrAccessToken. +class AcrAccessToken(_Model): + """The ACR access token response containing the access token for authentication. :ivar access_token: The access token for performing authenticated requests. :vartype access_token: str """ - _attribute_map = { - "access_token": {"key": "access_token", "type": "str"}, - } + access_token: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The access token for performing authenticated requests.""" + + @overload + def __init__( + self, + *, + access_token: Optional[str] = None, + ) -> None: ... - def __init__(self, *, access_token: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword access_token: The access token for performing authenticated requests. - :paramtype access_token: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.access_token = access_token + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class AcrErrorInfo(_serialization.Model): +class AcrErrorInfo(_Model): """Error information. :ivar code: Error code. @@ -50,53 +53,67 @@ class AcrErrorInfo(_serialization.Model): :ivar message: Error message. :vartype message: str :ivar detail: Error details. - :vartype detail: JSON + :vartype detail: any """ - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "detail": {"key": "detail", "type": "object"}, - } + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error code.""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error message.""" + detail: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error details.""" + @overload def __init__( - self, *, code: Optional[str] = None, message: Optional[str] = None, detail: Optional[JSON] = None, **kwargs: Any - ) -> None: + self, + *, + code: Optional[str] = None, + message: Optional[str] = None, + detail: Optional[Any] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword code: Error code. - :paramtype code: str - :keyword message: Error message. - :paramtype message: str - :keyword detail: Error details. - :paramtype detail: JSON + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.code = code - self.message = message - self.detail = detail + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class AcrErrors(_serialization.Model): +class AcrErrors(_Model): """Acr error response describing why the operation failed. :ivar errors: Array of detailed error. - :vartype errors: list[~container_registry.models.AcrErrorInfo] + :vartype errors: list[~azure.containerregistry._generated.models.AcrErrorInfo] """ - _attribute_map = { - "errors": {"key": "errors", "type": "[AcrErrorInfo]"}, - } + errors: Optional[list["_models.AcrErrorInfo"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Array of detailed error.""" + + @overload + def __init__( + self, + *, + errors: Optional[list["_models.AcrErrorInfo"]] = None, + ) -> None: ... - def __init__(self, *, errors: Optional[List["_models.AcrErrorInfo"]] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword errors: Array of detailed error. - :paramtype errors: list[~container_registry.models.AcrErrorInfo] + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.errors = errors + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class AcrManifests(_serialization.Model): + +class AcrManifests(_Model): """Manifest attributes. :ivar registry_login_server: Registry login server name. This is likely to be similar to @@ -105,73 +122,80 @@ class AcrManifests(_serialization.Model): :ivar repository: Image name. :vartype repository: str :ivar manifests: List of manifests. - :vartype manifests: list[~container_registry.models.ManifestAttributesBase] - :ivar link: + :vartype manifests: list[~azure.containerregistry._generated.models.ManifestAttributesBase] + :ivar link: Link to the next page of results. :vartype link: str """ - _attribute_map = { - "registry_login_server": {"key": "registry", "type": "str"}, - "repository": {"key": "imageName", "type": "str"}, - "manifests": {"key": "manifests", "type": "[ManifestAttributesBase]"}, - "link": {"key": "link", "type": "str"}, - } - + registry_login_server: Optional[str] = rest_field( + name="registry", visibility=["read", "create", "update", "delete", "query"] + ) + """Registry login server name. This is likely to be similar to + {registry-name}.azurecr.io.""" + repository: Optional[str] = rest_field(name="imageName", visibility=["read", "create", "update", "delete", "query"]) + """Image name.""" + manifests: Optional[list["_models.ManifestAttributesBase"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """List of manifests.""" + link: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Link to the next page of results.""" + + @overload def __init__( self, *, registry_login_server: Optional[str] = None, repository: Optional[str] = None, - manifests: Optional[List["_models.ManifestAttributesBase"]] = None, + manifests: Optional[list["_models.ManifestAttributesBase"]] = None, link: Optional[str] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword registry_login_server: Registry login server name. This is likely to be similar to - {registry-name}.azurecr.io. - :paramtype registry_login_server: str - :keyword repository: Image name. - :paramtype repository: str - :keyword manifests: List of manifests. - :paramtype manifests: list[~container_registry.models.ManifestAttributesBase] - :keyword link: - :paramtype link: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.registry_login_server = registry_login_server - self.repository = repository - self.manifests = manifests - self.link = link + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class AcrRefreshToken(_serialization.Model): - """AcrRefreshToken. +class AcrRefreshToken(_Model): + """The ACR refresh token response containing the refresh token for authentication. :ivar refresh_token: The refresh token to be used for generating access tokens. :vartype refresh_token: str """ - _attribute_map = { - "refresh_token": {"key": "refresh_token", "type": "str"}, - } + refresh_token: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The refresh token to be used for generating access tokens.""" - def __init__(self, *, refresh_token: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__( + self, + *, + refresh_token: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword refresh_token: The refresh token to be used for generating access tokens. - :paramtype refresh_token: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.refresh_token = refresh_token + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class Annotations(_serialization.Model): # pylint: disable=too-many-instance-attributes +class Annotations(_Model): """Additional information provided through arbitrary metadata. - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, JSON] :ivar created: Date and time on which the image was built (string, date-time as defined by - https://tools.ietf.org/html/rfc3339#section-5.6). + `https://tools.ietf.org/html/rfc3339#section-5.6 + `_). :vartype created: ~datetime.datetime :ivar authors: Contact details of the people or organization responsible for the image. :vartype authors: str @@ -199,26 +223,76 @@ class Annotations(_serialization.Model): # pylint: disable=too-many-instance-at :vartype description: str """ - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "created": {"key": "org\\.opencontainers\\.image\\.created", "type": "iso-8601"}, - "authors": {"key": "org\\.opencontainers\\.image\\.authors", "type": "str"}, - "url": {"key": "org\\.opencontainers\\.image\\.url", "type": "str"}, - "documentation": {"key": "org\\.opencontainers\\.image\\.documentation", "type": "str"}, - "source": {"key": "org\\.opencontainers\\.image\\.source", "type": "str"}, - "version": {"key": "org\\.opencontainers\\.image\\.version", "type": "str"}, - "revision": {"key": "org\\.opencontainers\\.image\\.revision", "type": "str"}, - "vendor": {"key": "org\\.opencontainers\\.image\\.vendor", "type": "str"}, - "licenses": {"key": "org\\.opencontainers\\.image\\.licenses", "type": "str"}, - "name": {"key": "org\\.opencontainers\\.image\\.ref\\.name", "type": "str"}, - "title": {"key": "org\\.opencontainers\\.image\\.title", "type": "str"}, - "description": {"key": "org\\.opencontainers\\.image\\.description", "type": "str"}, - } - + created: Optional[datetime.datetime] = rest_field( + name="org.opencontainers.image.created", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + ) + """Date and time on which the image was built (string, date-time as defined by + `https://tools.ietf.org/html/rfc3339#section-5.6 + `_).""" + authors: Optional[str] = rest_field( + name="org.opencontainers.image.authors", + visibility=["read", "create", "update", "delete", "query"], + ) + """Contact details of the people or organization responsible for the image.""" + url: Optional[str] = rest_field( + name="org.opencontainers.image.url", + visibility=["read", "create", "update", "delete", "query"], + ) + """URL to find more information on the image.""" + documentation: Optional[str] = rest_field( + name="org.opencontainers.image.documentation", + visibility=["read", "create", "update", "delete", "query"], + ) + """URL to get documentation on the image.""" + source: Optional[str] = rest_field( + name="org.opencontainers.image.source", + visibility=["read", "create", "update", "delete", "query"], + ) + """URL to get source code for building the image.""" + version: Optional[str] = rest_field( + name="org.opencontainers.image.version", + visibility=["read", "create", "update", "delete", "query"], + ) + """Version of the packaged software. The version MAY match a label or tag in the + source code repository, may also be Semantic versioning-compatible.""" + revision: Optional[str] = rest_field( + name="org.opencontainers.image.revision", + visibility=["read", "create", "update", "delete", "query"], + ) + """Source control revision identifier for the packaged software.""" + vendor: Optional[str] = rest_field( + name="org.opencontainers.image.vendor", + visibility=["read", "create", "update", "delete", "query"], + ) + """Name of the distributing entity, organization or individual.""" + licenses: Optional[str] = rest_field( + name="org.opencontainers.image.licenses", + visibility=["read", "create", "update", "delete", "query"], + ) + """License(s) under which contained software is distributed as an SPDX License + Expression.""" + name: Optional[str] = rest_field( + name="org.opencontainers.image.ref.name", + visibility=["read", "create", "update", "delete", "query"], + ) + """Name of the reference for a target.""" + title: Optional[str] = rest_field( + name="org.opencontainers.image.title", + visibility=["read", "create", "update", "delete", "query"], + ) + """Human-readable title of the image.""" + description: Optional[str] = rest_field( + name="org.opencontainers.image.description", + visibility=["read", "create", "update", "delete", "query"], + ) + """Human-readable description of the software packaged in the image.""" + + @overload def __init__( self, *, - additional_properties: Optional[Dict[str, JSON]] = None, created: Optional[datetime.datetime] = None, authors: Optional[str] = None, url: Optional[str] = None, @@ -231,173 +305,93 @@ def __init__( name: Optional[str] = None, title: Optional[str] = None, description: Optional[str] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, JSON] - :keyword created: Date and time on which the image was built (string, date-time as defined by - https://tools.ietf.org/html/rfc3339#section-5.6). - :paramtype created: ~datetime.datetime - :keyword authors: Contact details of the people or organization responsible for the image. - :paramtype authors: str - :keyword url: URL to find more information on the image. - :paramtype url: str - :keyword documentation: URL to get documentation on the image. - :paramtype documentation: str - :keyword source: URL to get source code for building the image. - :paramtype source: str - :keyword version: Version of the packaged software. The version MAY match a label or tag in the - source code repository, may also be Semantic versioning-compatible. - :paramtype version: str - :keyword revision: Source control revision identifier for the packaged software. - :paramtype revision: str - :keyword vendor: Name of the distributing entity, organization or individual. - :paramtype vendor: str - :keyword licenses: License(s) under which contained software is distributed as an SPDX License - Expression. - :paramtype licenses: str - :keyword name: Name of the reference for a target. - :paramtype name: str - :keyword title: Human-readable title of the image. - :paramtype title: str - :keyword description: Human-readable description of the software packaged in the image. - :paramtype description: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.created = created - self.authors = authors - self.url = url - self.documentation = documentation - self.source = source - self.version = version - self.revision = revision - self.vendor = vendor - self.licenses = licenses - self.name = name - self.title = title - self.description = description - - -class ArtifactManifestPlatform(_serialization.Model): - """The artifact's platform, consisting of operating system and architecture. - Variables are only populated by the server, and will be ignored when sending a request. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + - All required parameters must be populated in order to send to Azure. +class ArtifactManifestPlatform(_Model): + """The artifact's platform, consisting of operating system and architecture. :ivar digest: Manifest digest. Required. :vartype digest: str :ivar architecture: CPU architecture. Known values are: "386", "amd64", "arm", "arm64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", and "wasm". - :vartype architecture: str or ~container_registry.models.ArtifactArchitecture + :vartype architecture: str or ~azure.containerregistry._generated.models.ArtifactArchitecture :ivar operating_system: Operating system. Known values are: "aix", "android", "darwin", "dragonfly", "freebsd", "illumos", "ios", "js", "linux", "netbsd", "openbsd", "plan9", "solaris", and "windows". - :vartype operating_system: str or ~container_registry.models.ArtifactOperatingSystem + :vartype operating_system: str or + ~azure.containerregistry._generated.models.ArtifactOperatingSystem """ - _validation = { - "digest": {"required": True, "readonly": True}, - "architecture": {"readonly": True}, - "operating_system": {"readonly": True}, - } - - _attribute_map = { - "digest": {"key": "digest", "type": "str"}, - "architecture": {"key": "architecture", "type": "str"}, - "operating_system": {"key": "os", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.digest = None - self.architecture = None - self.operating_system = None - - -class ArtifactManifestProperties(_serialization.Model): + digest: str = rest_field(visibility=["read"]) + """Manifest digest. Required.""" + architecture: Optional[Union[str, "_models.ArtifactArchitecture"]] = rest_field(visibility=["read"]) + """CPU architecture. Known values are: \"386\", \"amd64\", \"arm\", \"arm64\", \"mips\", + \"mipsle\", \"mips64\", \"mips64le\", \"ppc64\", \"ppc64le\", \"riscv64\", \"s390x\", and + \"wasm\".""" + operating_system: Optional[Union[str, "_models.ArtifactOperatingSystem"]] = rest_field( + name="os", visibility=["read"] + ) + """Operating system. Known values are: \"aix\", \"android\", \"darwin\", \"dragonfly\", + \"freebsd\", \"illumos\", \"ios\", \"js\", \"linux\", \"netbsd\", \"openbsd\", \"plan9\", + \"solaris\", and \"windows\".""" + + +class ArtifactManifestProperties(_Model): """Manifest attributes details. - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - :ivar registry_login_server: Registry login server name. This is likely to be similar to {registry-name}.azurecr.io. :vartype registry_login_server: str :ivar repository_name: Repository name. :vartype repository_name: str :ivar manifest: Manifest attributes. Required. - :vartype manifest: ~container_registry.models.ManifestAttributesBase + :vartype manifest: ~azure.containerregistry._generated.models.ManifestAttributesBase """ - _validation = { - "registry_login_server": {"readonly": True}, - "repository_name": {"readonly": True}, - "manifest": {"required": True, "readonly": True}, - } - - _attribute_map = { - "registry_login_server": {"key": "registry", "type": "str"}, - "repository_name": {"key": "imageName", "type": "str"}, - "manifest": {"key": "manifest", "type": "ManifestAttributesBase"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.registry_login_server = None - self.repository_name = None - self.manifest = None + registry_login_server: Optional[str] = rest_field(name="registry", visibility=["read"]) + """Registry login server name. This is likely to be similar to + {registry-name}.azurecr.io.""" + repository_name: Optional[str] = rest_field(name="imageName", visibility=["read"]) + """Repository name.""" + manifest: "_models.ManifestAttributesBase" = rest_field(visibility=["read"]) + """Manifest attributes. Required.""" -class ArtifactTagProperties(_serialization.Model): +class ArtifactTagProperties(_Model): """Tag attributes. - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - :ivar registry_login_server: Registry login server name. This is likely to be similar to {registry-name}.azurecr.io. Required. :vartype registry_login_server: str :ivar repository_name: Image name. Required. :vartype repository_name: str :ivar tag: List of tag attribute details. Required. - :vartype tag: ~container_registry.models.TagAttributesBase + :vartype tag: ~azure.containerregistry._generated.models.TagAttributesBase """ - _validation = { - "registry_login_server": {"required": True, "readonly": True}, - "repository_name": {"required": True, "readonly": True}, - "tag": {"required": True, "readonly": True}, - } - - _attribute_map = { - "registry_login_server": {"key": "registry", "type": "str"}, - "repository_name": {"key": "imageName", "type": "str"}, - "tag": {"key": "tag", "type": "TagAttributesBase"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.registry_login_server = None - self.repository_name = None - self.tag = None + registry_login_server: str = rest_field(name="registry", visibility=["read"]) + """Registry login server name. This is likely to be similar to + {registry-name}.azurecr.io. Required.""" + repository_name: str = rest_field(name="imageName", visibility=["read"]) + """Image name. Required.""" + tag: "_models.TagAttributesBase" = rest_field(visibility=["read"]) + """List of tag attribute details. Required.""" -class ContainerRepositoryProperties(_serialization.Model): +class ContainerRepositoryProperties(_Model): """Properties of this repository. - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - :ivar registry_login_server: Registry login server name. This is likely to be similar to {registry-name}.azurecr.io. Required. :vartype registry_login_server: str @@ -412,73 +406,48 @@ class ContainerRepositoryProperties(_serialization.Model): :ivar tag_count: Number of the tags. Required. :vartype tag_count: int :ivar changeable_attributes: Writeable properties of the resource. Required. - :vartype changeable_attributes: ~container_registry.models.RepositoryWriteableProperties + :vartype changeable_attributes: + ~azure.containerregistry._generated.models.RepositoryWriteableProperties """ - _validation = { - "registry_login_server": {"required": True, "readonly": True}, - "name": {"required": True, "readonly": True}, - "created_on": {"required": True, "readonly": True}, - "last_updated_on": {"required": True, "readonly": True}, - "manifest_count": {"required": True, "readonly": True}, - "tag_count": {"required": True, "readonly": True}, - "changeable_attributes": {"required": True}, - } - - _attribute_map = { - "registry_login_server": {"key": "registry", "type": "str"}, - "name": {"key": "imageName", "type": "str"}, - "created_on": {"key": "createdTime", "type": "iso-8601"}, - "last_updated_on": {"key": "lastUpdateTime", "type": "iso-8601"}, - "manifest_count": {"key": "manifestCount", "type": "int"}, - "tag_count": {"key": "tagCount", "type": "int"}, - "changeable_attributes": {"key": "changeableAttributes", "type": "RepositoryWriteableProperties"}, - } - - def __init__(self, *, changeable_attributes: "_models.RepositoryWriteableProperties", **kwargs: Any) -> None: + registry_login_server: str = rest_field(name="registry", visibility=["read"]) + """Registry login server name. This is likely to be similar to + {registry-name}.azurecr.io. Required.""" + name: str = rest_field(name="imageName", visibility=["read"]) + """Image name. Required.""" + created_on: datetime.datetime = rest_field(name="createdTime", visibility=["read"], format="rfc3339") + """Image created time. Required.""" + last_updated_on: datetime.datetime = rest_field(name="lastUpdateTime", visibility=["read"], format="rfc3339") + """Image last update time. Required.""" + manifest_count: int = rest_field(name="manifestCount", visibility=["read"]) + """Number of the manifests. Required.""" + tag_count: int = rest_field(name="tagCount", visibility=["read"]) + """Number of the tags. Required.""" + changeable_attributes: "_models.RepositoryWriteableProperties" = rest_field( + name="changeableAttributes", + visibility=["read", "create", "update", "delete", "query"], + ) + """Writeable properties of the resource. Required.""" + + @overload + def __init__( + self, + *, + changeable_attributes: "_models.RepositoryWriteableProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword changeable_attributes: Writeable properties of the resource. Required. - :paramtype changeable_attributes: ~container_registry.models.RepositoryWriteableProperties + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.registry_login_server = None - self.name = None - self.created_on = None - self.last_updated_on = None - self.manifest_count = None - self.tag_count = None - self.changeable_attributes = changeable_attributes - - -class DeleteRepositoryResult(_serialization.Model): - """Deleted repository. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar deleted_manifests: SHA of the deleted image. - :vartype deleted_manifests: list[str] - :ivar deleted_tags: Tag of the deleted image. - :vartype deleted_tags: list[str] - """ - - _validation = { - "deleted_manifests": {"readonly": True}, - "deleted_tags": {"readonly": True}, - } - _attribute_map = { - "deleted_manifests": {"key": "manifestsDeleted", "type": "[str]"}, - "deleted_tags": {"key": "tagsDeleted", "type": "[str]"}, - } + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.deleted_manifests = None - self.deleted_tags = None - -class Descriptor(_serialization.Model): +class Descriptor(_Model): """Docker V2 image layer descriptor including config and layers. :ivar media_type: Layer media type. @@ -490,153 +459,175 @@ class Descriptor(_serialization.Model): :ivar urls: Specifies a list of URIs from which this object may be downloaded. :vartype urls: list[str] :ivar annotations: Additional information provided through arbitrary metadata. - :vartype annotations: ~container_registry.models.Annotations + :vartype annotations: ~azure.containerregistry._generated.models.Annotations """ - _attribute_map = { - "media_type": {"key": "mediaType", "type": "str"}, - "size": {"key": "size", "type": "int"}, - "digest": {"key": "digest", "type": "str"}, - "urls": {"key": "urls", "type": "[str]"}, - "annotations": {"key": "annotations", "type": "Annotations"}, - } - + media_type: Optional[str] = rest_field(name="mediaType", visibility=["read", "create", "update", "delete", "query"]) + """Layer media type.""" + size: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Layer size.""" + digest: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Layer digest.""" + urls: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies a list of URIs from which this object may be downloaded.""" + annotations: Optional["_models.Annotations"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Additional information provided through arbitrary metadata.""" + + @overload def __init__( self, *, media_type: Optional[str] = None, size: Optional[int] = None, digest: Optional[str] = None, - urls: Optional[List[str]] = None, + urls: Optional[list[str]] = None, annotations: Optional["_models.Annotations"] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword media_type: Layer media type. - :paramtype media_type: str - :keyword size: Layer size. - :paramtype size: int - :keyword digest: Layer digest. - :paramtype digest: str - :keyword urls: Specifies a list of URIs from which this object may be downloaded. - :paramtype urls: list[str] - :keyword annotations: Additional information provided through arbitrary metadata. - :paramtype annotations: ~container_registry.models.Annotations + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.media_type = media_type - self.size = size - self.digest = digest - self.urls = urls - self.annotations = annotations + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class FsLayer(_serialization.Model): +class FsLayer(_Model): """Image layer information. :ivar blob_sum: SHA of an image layer. :vartype blob_sum: str """ - _attribute_map = { - "blob_sum": {"key": "blobSum", "type": "str"}, - } + blob_sum: Optional[str] = rest_field(name="blobSum", visibility=["read", "create", "update", "delete", "query"]) + """SHA of an image layer.""" + + @overload + def __init__( + self, + *, + blob_sum: Optional[str] = None, + ) -> None: ... - def __init__(self, *, blob_sum: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword blob_sum: SHA of an image layer. - :paramtype blob_sum: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.blob_sum = blob_sum + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class History(_serialization.Model): +class History(_Model): """A list of unstructured historical data for v1 compatibility. :ivar v1_compatibility: The raw v1 compatibility information. :vartype v1_compatibility: str """ - _attribute_map = { - "v1_compatibility": {"key": "v1Compatibility", "type": "str"}, - } + v1_compatibility: Optional[str] = rest_field( + name="v1Compatibility", + visibility=["read", "create", "update", "delete", "query"], + ) + """The raw v1 compatibility information.""" + + @overload + def __init__( + self, + *, + v1_compatibility: Optional[str] = None, + ) -> None: ... - def __init__(self, *, v1_compatibility: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword v1_compatibility: The raw v1 compatibility information. - :paramtype v1_compatibility: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.v1_compatibility = v1_compatibility + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class ImageSignature(_serialization.Model): + +class ImageSignature(_Model): """Signature of a signed manifest. :ivar header: A JSON web signature. - :vartype header: ~container_registry.models.JWK + :vartype header: ~azure.containerregistry._generated.models.JWK :ivar signature: A signature for the image manifest, signed by a libtrust private key. :vartype signature: str :ivar protected: The signed protected header. :vartype protected: str """ - _attribute_map = { - "header": {"key": "header", "type": "JWK"}, - "signature": {"key": "signature", "type": "str"}, - "protected": {"key": "protected", "type": "str"}, - } + header: Optional["_models.JWK"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A JSON web signature.""" + signature: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A signature for the image manifest, signed by a libtrust private key.""" + protected: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The signed protected header.""" + @overload def __init__( self, *, header: Optional["_models.JWK"] = None, signature: Optional[str] = None, protected: Optional[str] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword header: A JSON web signature. - :paramtype header: ~container_registry.models.JWK - :keyword signature: A signature for the image manifest, signed by a libtrust private key. - :paramtype signature: str - :keyword protected: The signed protected header. - :paramtype protected: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.header = header - self.signature = signature - self.protected = protected + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class JWK(_serialization.Model): + +class JWK(_Model): """A JSON web signature. :ivar jwk: JSON web key parameter. - :vartype jwk: ~container_registry.models.JWKHeader + :vartype jwk: ~azure.containerregistry._generated.models.JWKHeader :ivar alg: The algorithm used to sign or encrypt the JWT. :vartype alg: str """ - _attribute_map = { - "jwk": {"key": "jwk", "type": "JWKHeader"}, - "alg": {"key": "alg", "type": "str"}, - } + jwk: Optional["_models.JWKHeader"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """JSON web key parameter.""" + alg: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The algorithm used to sign or encrypt the JWT.""" + + @overload + def __init__( + self, + *, + jwk: Optional["_models.JWKHeader"] = None, + alg: Optional[str] = None, + ) -> None: ... - def __init__(self, *, jwk: Optional["_models.JWKHeader"] = None, alg: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword jwk: JSON web key parameter. - :paramtype jwk: ~container_registry.models.JWKHeader - :keyword alg: The algorithm used to sign or encrypt the JWT. - :paramtype alg: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.jwk = jwk - self.alg = alg + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class JWKHeader(_serialization.Model): +class JWKHeader(_Model): """JSON web key parameter. :ivar crv: crv value. @@ -651,14 +642,18 @@ class JWKHeader(_serialization.Model): :vartype y: str """ - _attribute_map = { - "crv": {"key": "crv", "type": "str"}, - "kid": {"key": "kid", "type": "str"}, - "kty": {"key": "kty", "type": "str"}, - "x": {"key": "x", "type": "str"}, - "y": {"key": "y", "type": "str"}, - } - + crv: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """crv value.""" + kid: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """kid value.""" + kty: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """kty value.""" + x: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """x value.""" + y: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """y value.""" + + @overload def __init__( self, *, @@ -667,54 +662,51 @@ def __init__( kty: Optional[str] = None, x: Optional[str] = None, y: Optional[str] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword crv: crv value. - :paramtype crv: str - :keyword kid: kid value. - :paramtype kid: str - :keyword kty: kty value. - :paramtype kty: str - :keyword x: x value. - :paramtype x: str - :keyword y: y value. - :paramtype y: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.crv = crv - self.kid = kid - self.kty = kty - self.x = x - self.y = y + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class Manifest(_serialization.Model): + +class Manifest(_Model): """Returns the requested manifest file. :ivar schema_version: Schema version. :vartype schema_version: int """ - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - } + schema_version: Optional[int] = rest_field( + name="schemaVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """Schema version.""" + + @overload + def __init__( + self, + *, + schema_version: Optional[int] = None, + ) -> None: ... - def __init__(self, *, schema_version: Optional[int] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword schema_version: Schema version. - :paramtype schema_version: int + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.schema_version = schema_version + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class ManifestAttributesBase(_serialization.Model): - """Manifest details. - - Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. +class ManifestAttributesBase(_Model): + """Manifest details. :ivar digest: Manifest. Required. :vartype digest: str @@ -726,123 +718,85 @@ class ManifestAttributesBase(_serialization.Model): :vartype last_updated_on: ~datetime.datetime :ivar architecture: CPU architecture. Known values are: "386", "amd64", "arm", "arm64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", and "wasm". - :vartype architecture: str or ~container_registry.models.ArtifactArchitecture + :vartype architecture: str or ~azure.containerregistry._generated.models.ArtifactArchitecture :ivar operating_system: Operating system. Known values are: "aix", "android", "darwin", "dragonfly", "freebsd", "illumos", "ios", "js", "linux", "netbsd", "openbsd", "plan9", "solaris", and "windows". - :vartype operating_system: str or ~container_registry.models.ArtifactOperatingSystem + :vartype operating_system: str or + ~azure.containerregistry._generated.models.ArtifactOperatingSystem :ivar related_artifacts: List of artifacts that are referenced by this manifest list, with - information about the platform each supports. This list will be empty if this is a leaf + information + about the platform each supports. This list will be empty if this is a leaf manifest and not a manifest list. - :vartype related_artifacts: list[~container_registry.models.ArtifactManifestPlatform] + :vartype related_artifacts: + list[~azure.containerregistry._generated.models.ArtifactManifestPlatform] + :ivar config_media_type: Config blob media type. + :vartype config_media_type: str :ivar tags: List of tags. :vartype tags: list[str] :ivar changeable_attributes: Writeable properties of the resource. - :vartype changeable_attributes: ~container_registry.models.ManifestWriteableProperties - """ - - _validation = { - "digest": {"required": True, "readonly": True}, - "size": {"readonly": True}, - "created_on": {"required": True, "readonly": True}, - "last_updated_on": {"required": True, "readonly": True}, - "architecture": {"readonly": True}, - "operating_system": {"readonly": True}, - "related_artifacts": {"readonly": True}, - "tags": {"readonly": True}, - } - - _attribute_map = { - "digest": {"key": "digest", "type": "str"}, - "size": {"key": "imageSize", "type": "int"}, - "created_on": {"key": "createdTime", "type": "iso-8601"}, - "last_updated_on": {"key": "lastUpdateTime", "type": "iso-8601"}, - "architecture": {"key": "architecture", "type": "str"}, - "operating_system": {"key": "os", "type": "str"}, - "related_artifacts": {"key": "references", "type": "[ArtifactManifestPlatform]"}, - "tags": {"key": "tags", "type": "[str]"}, - "changeable_attributes": {"key": "changeableAttributes", "type": "ManifestWriteableProperties"}, - } - - def __init__( - self, *, changeable_attributes: Optional["_models.ManifestWriteableProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword changeable_attributes: Writeable properties of the resource. - :paramtype changeable_attributes: ~container_registry.models.ManifestWriteableProperties - """ - super().__init__(**kwargs) - self.digest = None - self.size = None - self.created_on = None - self.last_updated_on = None - self.architecture = None - self.operating_system = None - self.related_artifacts = None - self.tags = None - self.changeable_attributes = changeable_attributes - - -class ManifestAttributesManifest(_serialization.Model): - """List of manifest attributes. - - :ivar references: List of manifest attributes details. - :vartype references: list[~container_registry.models.ArtifactManifestPlatform] + :vartype changeable_attributes: + ~azure.containerregistry._generated.models.ManifestWriteableProperties """ - _attribute_map = { - "references": {"key": "references", "type": "[ArtifactManifestPlatform]"}, - } - - def __init__(self, *, references: Optional[List["_models.ArtifactManifestPlatform"]] = None, **kwargs: Any) -> None: - """ - :keyword references: List of manifest attributes details. - :paramtype references: list[~container_registry.models.ArtifactManifestPlatform] - """ - super().__init__(**kwargs) - self.references = references - - -class ManifestList(Manifest): - """Returns the requested Docker multi-arch-manifest file. - - :ivar schema_version: Schema version. - :vartype schema_version: int - :ivar media_type: Media type for this Manifest. - :vartype media_type: str - :ivar manifests: List of V2 image layer information. - :vartype manifests: list[~container_registry.models.ManifestListAttributes] - """ - - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - "media_type": {"key": "mediaType", "type": "str"}, - "manifests": {"key": "manifests", "type": "[ManifestListAttributes]"}, - } - + digest: str = rest_field(visibility=["read"]) + """Manifest. Required.""" + size: Optional[int] = rest_field(name="imageSize", visibility=["read"]) + """Image size.""" + created_on: datetime.datetime = rest_field(name="createdTime", visibility=["read"], format="rfc3339") + """Created time. Required.""" + last_updated_on: datetime.datetime = rest_field(name="lastUpdateTime", visibility=["read"], format="rfc3339") + """Last update time. Required.""" + architecture: Optional[Union[str, "_models.ArtifactArchitecture"]] = rest_field(visibility=["read"]) + """CPU architecture. Known values are: \"386\", \"amd64\", \"arm\", \"arm64\", \"mips\", + \"mipsle\", \"mips64\", \"mips64le\", \"ppc64\", \"ppc64le\", \"riscv64\", \"s390x\", and + \"wasm\".""" + operating_system: Optional[Union[str, "_models.ArtifactOperatingSystem"]] = rest_field( + name="os", visibility=["read"] + ) + """Operating system. Known values are: \"aix\", \"android\", \"darwin\", \"dragonfly\", + \"freebsd\", \"illumos\", \"ios\", \"js\", \"linux\", \"netbsd\", \"openbsd\", \"plan9\", + \"solaris\", and \"windows\".""" + related_artifacts: Optional[list["_models.ArtifactManifestPlatform"]] = rest_field( + name="references", visibility=["read"] + ) + """List of artifacts that are referenced by this manifest list, with information + about the platform each supports. This list will be empty if this is a leaf + manifest and not a manifest list.""" + config_media_type: Optional[str] = rest_field( + name="configMediaType", + visibility=["read", "create", "update", "delete", "query"], + ) + """Config blob media type.""" + tags: Optional[list[str]] = rest_field(visibility=["read"]) + """List of tags.""" + changeable_attributes: Optional["_models.ManifestWriteableProperties"] = rest_field( + name="changeableAttributes", + visibility=["read", "create", "update", "delete", "query"], + ) + """Writeable properties of the resource.""" + + @overload def __init__( self, *, - schema_version: Optional[int] = None, - media_type: Optional[str] = None, - manifests: Optional[List["_models.ManifestListAttributes"]] = None, - **kwargs: Any - ) -> None: + config_media_type: Optional[str] = None, + changeable_attributes: Optional["_models.ManifestWriteableProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword schema_version: Schema version. - :paramtype schema_version: int - :keyword media_type: Media type for this Manifest. - :paramtype media_type: str - :keyword manifests: List of V2 image layer information. - :paramtype manifests: list[~container_registry.models.ManifestListAttributes] + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(schema_version=schema_version, **kwargs) - self.media_type = media_type - self.manifests = manifests + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class ManifestListAttributes(_serialization.Model): - """ManifestListAttributes. + +class ManifestListAttributes(_Model): + """Attributes of a manifest in a manifest list. :ivar media_type: The MIME type of the referenced object. This will generally be application/vnd.docker.image.manifest.v2+json, but it could also be @@ -853,18 +807,25 @@ class ManifestListAttributes(_serialization.Model): :ivar digest: The digest of the content, as defined by the Registry V2 HTTP API Specification. :vartype digest: str :ivar platform: The platform object describes the platform which the image in the manifest runs - on. A full list of valid operating system and architecture values are listed in the Go language - documentation for $GOOS and $GOARCH. - :vartype platform: ~container_registry.models.Platform + on. A full list of valid operating system and architecture values are listed in + the Go language documentation for $GOOS and $GOARCH. + :vartype platform: ~azure.containerregistry._generated.models.Platform """ - _attribute_map = { - "media_type": {"key": "mediaType", "type": "str"}, - "size": {"key": "size", "type": "int"}, - "digest": {"key": "digest", "type": "str"}, - "platform": {"key": "platform", "type": "Platform"}, - } - + media_type: Optional[str] = rest_field(name="mediaType", visibility=["read", "create", "update", "delete", "query"]) + """The MIME type of the referenced object. This will generally be + application/vnd.docker.image.manifest.v2+json, but it could also be + application/vnd.docker.image.manifest.v1+json.""" + size: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The size in bytes of the object.""" + digest: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The digest of the content, as defined by the Registry V2 HTTP API Specification.""" + platform: Optional["_models.Platform"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The platform object describes the platform which the image in the manifest runs + on. A full list of valid operating system and architecture values are listed in + the Go language documentation for $GOOS and $GOARCH.""" + + @overload def __init__( self, *, @@ -872,31 +833,20 @@ def __init__( size: Optional[int] = None, digest: Optional[str] = None, platform: Optional["_models.Platform"] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword media_type: The MIME type of the referenced object. This will generally be - application/vnd.docker.image.manifest.v2+json, but it could also be - application/vnd.docker.image.manifest.v1+json. - :paramtype media_type: str - :keyword size: The size in bytes of the object. - :paramtype size: int - :keyword digest: The digest of the content, as defined by the Registry V2 HTTP API - Specification. - :paramtype digest: str - :keyword platform: The platform object describes the platform which the image in the manifest - runs on. A full list of valid operating system and architecture values are listed in the Go - language documentation for $GOOS and $GOARCH. - :paramtype platform: ~container_registry.models.Platform + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.media_type = media_type - self.size = size - self.digest = digest - self.platform = platform + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class ManifestWrapper(Manifest): # pylint: disable=too-many-instance-attributes + +class ManifestWrapper(Manifest): """Returns the requested manifest file. :ivar schema_version: Schema version. @@ -904,13 +854,13 @@ class ManifestWrapper(Manifest): # pylint: disable=too-many-instance-attributes :ivar media_type: Media type for this Manifest. :vartype media_type: str :ivar manifests: (ManifestList, OCIIndex) List of V2 image layer information. - :vartype manifests: list[~container_registry.models.ManifestListAttributes] + :vartype manifests: list[~azure.containerregistry._generated.models.ManifestListAttributes] :ivar config: (V2, OCI) Image config descriptor. - :vartype config: ~container_registry.models.Descriptor + :vartype config: ~azure.containerregistry._generated.models.Descriptor :ivar layers: (V2, OCI) List of V2 image layer information. - :vartype layers: list[~container_registry.models.Descriptor] + :vartype layers: list[~azure.containerregistry._generated.models.Descriptor] :ivar annotations: (OCI, OCIIndex) Additional metadata. - :vartype annotations: ~container_registry.models.Annotations + :vartype annotations: ~azure.containerregistry._generated.models.Annotations :ivar architecture: (V1) CPU architecture. :vartype architecture: str :ivar name: (V1) Image name. @@ -918,86 +868,76 @@ class ManifestWrapper(Manifest): # pylint: disable=too-many-instance-attributes :ivar tag: (V1) Image tag. :vartype tag: str :ivar fs_layers: (V1) List of layer information. - :vartype fs_layers: list[~container_registry.models.FsLayer] + :vartype fs_layers: list[~azure.containerregistry._generated.models.FsLayer] :ivar history: (V1) Image history. - :vartype history: list[~container_registry.models.History] + :vartype history: list[~azure.containerregistry._generated.models.History] :ivar signatures: (V1) Image signature. - :vartype signatures: list[~container_registry.models.ImageSignature] + :vartype signatures: list[~azure.containerregistry._generated.models.ImageSignature] """ - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - "media_type": {"key": "mediaType", "type": "str"}, - "manifests": {"key": "manifests", "type": "[ManifestListAttributes]"}, - "config": {"key": "config", "type": "Descriptor"}, - "layers": {"key": "layers", "type": "[Descriptor]"}, - "annotations": {"key": "annotations", "type": "Annotations"}, - "architecture": {"key": "architecture", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "tag": {"key": "tag", "type": "str"}, - "fs_layers": {"key": "fsLayers", "type": "[FsLayer]"}, - "history": {"key": "history", "type": "[History]"}, - "signatures": {"key": "signatures", "type": "[ImageSignature]"}, - } - + media_type: Optional[str] = rest_field(name="mediaType", visibility=["read", "create", "update", "delete", "query"]) + """Media type for this Manifest.""" + manifests: Optional[list["_models.ManifestListAttributes"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """(ManifestList, OCIIndex) List of V2 image layer information.""" + config: Optional["_models.Descriptor"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(V2, OCI) Image config descriptor.""" + layers: Optional[list["_models.Descriptor"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """(V2, OCI) List of V2 image layer information.""" + annotations: Optional["_models.Annotations"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """(OCI, OCIIndex) Additional metadata.""" + architecture: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(V1) CPU architecture.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(V1) Image name.""" + tag: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(V1) Image tag.""" + fs_layers: Optional[list["_models.FsLayer"]] = rest_field( + name="fsLayers", visibility=["read", "create", "update", "delete", "query"] + ) + """(V1) List of layer information.""" + history: Optional[list["_models.History"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(V1) Image history.""" + signatures: Optional[list["_models.ImageSignature"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """(V1) Image signature.""" + + @overload def __init__( self, *, schema_version: Optional[int] = None, media_type: Optional[str] = None, - manifests: Optional[List["_models.ManifestListAttributes"]] = None, + manifests: Optional[list["_models.ManifestListAttributes"]] = None, config: Optional["_models.Descriptor"] = None, - layers: Optional[List["_models.Descriptor"]] = None, + layers: Optional[list["_models.Descriptor"]] = None, annotations: Optional["_models.Annotations"] = None, architecture: Optional[str] = None, name: Optional[str] = None, tag: Optional[str] = None, - fs_layers: Optional[List["_models.FsLayer"]] = None, - history: Optional[List["_models.History"]] = None, - signatures: Optional[List["_models.ImageSignature"]] = None, - **kwargs: Any - ) -> None: + fs_layers: Optional[list["_models.FsLayer"]] = None, + history: Optional[list["_models.History"]] = None, + signatures: Optional[list["_models.ImageSignature"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword schema_version: Schema version. - :paramtype schema_version: int - :keyword media_type: Media type for this Manifest. - :paramtype media_type: str - :keyword manifests: (ManifestList, OCIIndex) List of V2 image layer information. - :paramtype manifests: list[~container_registry.models.ManifestListAttributes] - :keyword config: (V2, OCI) Image config descriptor. - :paramtype config: ~container_registry.models.Descriptor - :keyword layers: (V2, OCI) List of V2 image layer information. - :paramtype layers: list[~container_registry.models.Descriptor] - :keyword annotations: (OCI, OCIIndex) Additional metadata. - :paramtype annotations: ~container_registry.models.Annotations - :keyword architecture: (V1) CPU architecture. - :paramtype architecture: str - :keyword name: (V1) Image name. - :paramtype name: str - :keyword tag: (V1) Image tag. - :paramtype tag: str - :keyword fs_layers: (V1) List of layer information. - :paramtype fs_layers: list[~container_registry.models.FsLayer] - :keyword history: (V1) Image history. - :paramtype history: list[~container_registry.models.History] - :keyword signatures: (V1) Image signature. - :paramtype signatures: list[~container_registry.models.ImageSignature] + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(schema_version=schema_version, **kwargs) - self.media_type = media_type - self.manifests = manifests - self.config = config - self.layers = layers - self.annotations = annotations - self.architecture = architecture - self.name = name - self.tag = tag - self.fs_layers = fs_layers - self.history = history - self.signatures = signatures - - -class ManifestWriteableProperties(_serialization.Model): + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ManifestWriteableProperties(_Model): """Changeable attributes. :ivar can_delete: Delete enabled. @@ -1010,13 +950,24 @@ class ManifestWriteableProperties(_serialization.Model): :vartype can_read: bool """ - _attribute_map = { - "can_delete": {"key": "deleteEnabled", "type": "bool"}, - "can_write": {"key": "writeEnabled", "type": "bool"}, - "can_list": {"key": "listEnabled", "type": "bool"}, - "can_read": {"key": "readEnabled", "type": "bool"}, - } - + can_delete: Optional[bool] = rest_field( + name="deleteEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Delete enabled.""" + can_write: Optional[bool] = rest_field( + name="writeEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Write enabled.""" + can_list: Optional[bool] = rest_field( + name="listEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """List enabled.""" + can_read: Optional[bool] = rest_field( + name="readEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Read enabled.""" + + @overload def __init__( self, *, @@ -1024,142 +975,63 @@ def __init__( can_write: Optional[bool] = None, can_list: Optional[bool] = None, can_read: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword can_delete: Delete enabled. - :paramtype can_delete: bool - :keyword can_write: Write enabled. - :paramtype can_write: bool - :keyword can_list: List enabled. - :paramtype can_list: bool - :keyword can_read: Read enabled. - :paramtype can_read: bool - """ - super().__init__(**kwargs) - self.can_delete = can_delete - self.can_write = can_write - self.can_list = can_list - self.can_read = can_read - - -class OCIIndex(Manifest): - """Returns the requested OCI index file. + ) -> None: ... - :ivar schema_version: Schema version. - :vartype schema_version: int - :ivar manifests: List of OCI image layer information. - :vartype manifests: list[~container_registry.models.ManifestListAttributes] - :ivar annotations: Additional information provided through arbitrary metadata. - :vartype annotations: ~container_registry.models.Annotations - """ - - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - "manifests": {"key": "manifests", "type": "[ManifestListAttributes]"}, - "annotations": {"key": "annotations", "type": "Annotations"}, - } - - def __init__( - self, - *, - schema_version: Optional[int] = None, - manifests: Optional[List["_models.ManifestListAttributes"]] = None, - annotations: Optional["_models.Annotations"] = None, - **kwargs: Any - ) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword schema_version: Schema version. - :paramtype schema_version: int - :keyword manifests: List of OCI image layer information. - :paramtype manifests: list[~container_registry.models.ManifestListAttributes] - :keyword annotations: Additional information provided through arbitrary metadata. - :paramtype annotations: ~container_registry.models.Annotations + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(schema_version=schema_version, **kwargs) - self.manifests = manifests - self.annotations = annotations - -class OCIManifest(Manifest): - """Returns the requested OCI Manifest file. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) - :ivar schema_version: Schema version. - :vartype schema_version: int - :ivar config: V2 image config descriptor. - :vartype config: ~container_registry.models.Descriptor - :ivar layers: List of V2 image layer information. - :vartype layers: list[~container_registry.models.Descriptor] - :ivar annotations: Additional information provided through arbitrary metadata. - :vartype annotations: ~container_registry.models.Annotations - """ - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - "config": {"key": "config", "type": "Descriptor"}, - "layers": {"key": "layers", "type": "[Descriptor]"}, - "annotations": {"key": "annotations", "type": "Annotations"}, - } - - def __init__( - self, - *, - schema_version: Optional[int] = None, - config: Optional["_models.Descriptor"] = None, - layers: Optional[List["_models.Descriptor"]] = None, - annotations: Optional["_models.Annotations"] = None, - **kwargs: Any - ) -> None: - """ - :keyword schema_version: Schema version. - :paramtype schema_version: int - :keyword config: V2 image config descriptor. - :paramtype config: ~container_registry.models.Descriptor - :keyword layers: List of V2 image layer information. - :paramtype layers: list[~container_registry.models.Descriptor] - :keyword annotations: Additional information provided through arbitrary metadata. - :paramtype annotations: ~container_registry.models.Annotations - """ - super().__init__(schema_version=schema_version, **kwargs) - self.config = config - self.layers = layers - self.annotations = annotations - - -class Paths108HwamOauth2ExchangePostRequestbodyContentApplicationXWwwFormUrlencodedSchema(_serialization.Model): - """Paths108HwamOauth2ExchangePostRequestbodyContentApplicationXWwwFormUrlencodedSchema. - - All required parameters must be populated in order to send to Azure. +class MultipartBodyParameter(_Model): + """The multipart body parameter for AAD token exchange. :ivar grant_type: Can take a value of access_token_refresh_token, or access_token, or refresh_token. Required. Known values are: "access_token_refresh_token", "access_token", and "refresh_token". - :vartype grant_type: str or ~container_registry.models.PostContentSchemaGrantType + :vartype grant_type: str or + ~azure.containerregistry._generated.models.PostContentSchemaGrantType :ivar service: Indicates the name of your Azure container registry. Required. :vartype service: str :ivar tenant: AAD tenant associated to the AAD credentials. :vartype tenant: str :ivar refresh_token: AAD refresh token, mandatory when grant_type is access_token_refresh_token - or refresh_token. + or + refresh_token. :vartype refresh_token: str - :ivar aad_access_token: AAD access token, mandatory when grant_type is - access_token_refresh_token or access_token. - :vartype aad_access_token: str + :ivar access_token: AAD access token, mandatory when grant_type is access_token_refresh_token + or + access_token. + :vartype access_token: str """ - _validation = { - "grant_type": {"required": True}, - "service": {"required": True}, - } - - _attribute_map = { - "grant_type": {"key": "grant_type", "type": "str"}, - "service": {"key": "service", "type": "str"}, - "tenant": {"key": "tenant", "type": "str"}, - "refresh_token": {"key": "refresh_token", "type": "str"}, - "aad_access_token": {"key": "access_token", "type": "str"}, - } - + grant_type: Union[str, "_models.PostContentSchemaGrantType"] = rest_field( + name="grantType", visibility=["read", "create", "update", "delete", "query"] + ) + """Can take a value of access_token_refresh_token, or access_token, or + refresh_token. Required. Known values are: \"access_token_refresh_token\", \"access_token\", + and \"refresh_token\".""" + service: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Indicates the name of your Azure container registry. Required.""" + tenant: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """AAD tenant associated to the AAD credentials.""" + refresh_token: Optional[str] = rest_field( + name="refreshToken", visibility=["read", "create", "update", "delete", "query"] + ) + """AAD refresh token, mandatory when grant_type is access_token_refresh_token or + refresh_token.""" + access_token: Optional[str] = rest_field( + name="accessToken", visibility=["read", "create", "update", "delete", "query"] + ) + """AAD access token, mandatory when grant_type is access_token_refresh_token or + access_token.""" + + @overload def __init__( self, *, @@ -1167,98 +1039,24 @@ def __init__( service: str, tenant: Optional[str] = None, refresh_token: Optional[str] = None, - aad_access_token: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword grant_type: Can take a value of access_token_refresh_token, or access_token, or - refresh_token. Required. Known values are: "access_token_refresh_token", "access_token", and - "refresh_token". - :paramtype grant_type: str or ~container_registry.models.PostContentSchemaGrantType - :keyword service: Indicates the name of your Azure container registry. Required. - :paramtype service: str - :keyword tenant: AAD tenant associated to the AAD credentials. - :paramtype tenant: str - :keyword refresh_token: AAD refresh token, mandatory when grant_type is - access_token_refresh_token or refresh_token. - :paramtype refresh_token: str - :keyword aad_access_token: AAD access token, mandatory when grant_type is - access_token_refresh_token or access_token. - :paramtype aad_access_token: str - """ - super().__init__(**kwargs) - self.grant_type = grant_type - self.service = service - self.tenant = tenant - self.refresh_token = refresh_token - self.aad_access_token = aad_access_token - - -class PathsV3R3RxOauth2TokenPostRequestbodyContentApplicationXWwwFormUrlencodedSchema(_serialization.Model): - """PathsV3R3RxOauth2TokenPostRequestbodyContentApplicationXWwwFormUrlencodedSchema. - - All required parameters must be populated in order to send to Azure. - - :ivar service: Indicates the name of your Azure container registry. Required. - :vartype service: str - :ivar scope: Which is expected to be a valid scope, and can be specified more than once for - multiple scope requests. You obtained this from the Www-Authenticate response header from the - challenge. Required. - :vartype scope: str - :ivar acr_refresh_token: Must be a valid ACR refresh token. Required. - :vartype acr_refresh_token: str - :ivar grant_type: Grant type is expected to be refresh_token. Known values are: "refresh_token" - and "password". - :vartype grant_type: str or ~container_registry.models.TokenGrantType - """ - - _validation = { - "service": {"required": True}, - "scope": {"required": True}, - "acr_refresh_token": {"required": True}, - "grant_type": {"required": True}, - } + access_token: Optional[str] = None, + ) -> None: ... - _attribute_map = { - "service": {"key": "service", "type": "str"}, - "scope": {"key": "scope", "type": "str"}, - "acr_refresh_token": {"key": "refresh_token", "type": "str"}, - "grant_type": {"key": "grant_type", "type": "str"}, - } - - def __init__( - self, - *, - service: str, - scope: str, - acr_refresh_token: str, - grant_type: Union[str, "_models.TokenGrantType"] = "refresh_token", - **kwargs: Any - ) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword service: Indicates the name of your Azure container registry. Required. - :paramtype service: str - :keyword scope: Which is expected to be a valid scope, and can be specified more than once for - multiple scope requests. You obtained this from the Www-Authenticate response header from the - challenge. Required. - :paramtype scope: str - :keyword acr_refresh_token: Must be a valid ACR refresh token. Required. - :paramtype acr_refresh_token: str - :keyword grant_type: Grant type is expected to be refresh_token. Known values are: - "refresh_token" and "password". - :paramtype grant_type: str or ~container_registry.models.TokenGrantType + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.service = service - self.scope = scope - self.acr_refresh_token = acr_refresh_token - self.grant_type = grant_type + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class Platform(_serialization.Model): - """The platform object describes the platform which the image in the manifest runs on. A full list - of valid operating system and architecture values are listed in the Go language documentation - for $GOOS and $GOARCH. +class Platform(_Model): + """The platform object describes the platform which the image in the manifest runs + on. A full list of valid operating system and architecture values are listed in + the Go language documentation for $GOOS and $GOARCH. :ivar architecture: Specifies the CPU architecture, for example amd64 or ppc64le. :vartype architecture: str @@ -1270,114 +1068,59 @@ class Platform(_serialization.Model): :ivar os_features: The optional os.features field specifies an array of strings, each listing a required OS feature (for example on Windows win32k. :vartype os_features: list[str] - :ivar variant: The optional variant field specifies a variant of the CPU, for example armv6l to - specify a particular CPU variant of the ARM CPU. + :ivar variant: The optional variant field specifies a variant of the CPU, for example armv6l + to specify a particular CPU variant of the ARM CPU. :vartype variant: str :ivar features: The optional features field specifies an array of strings, each listing a required CPU feature (for example sse4 or aes. :vartype features: list[str] """ - _attribute_map = { - "architecture": {"key": "architecture", "type": "str"}, - "os": {"key": "os", "type": "str"}, - "os_version": {"key": "os\\.version", "type": "str"}, - "os_features": {"key": "os\\.features", "type": "[str]"}, - "variant": {"key": "variant", "type": "str"}, - "features": {"key": "features", "type": "[str]"}, - } - + architecture: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies the CPU architecture, for example amd64 or ppc64le.""" + os: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The os field specifies the operating system, for example linux or windows.""" + os_version: Optional[str] = rest_field( + name="os.version", visibility=["read", "create", "update", "delete", "query"] + ) + """The optional os.version field specifies the operating system version, for + example 10.0.10586.""" + os_features: Optional[list[str]] = rest_field( + name="os.features", visibility=["read", "create", "update", "delete", "query"] + ) + """The optional os.features field specifies an array of strings, each listing a + required OS feature (for example on Windows win32k.""" + variant: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The optional variant field specifies a variant of the CPU, for example armv6l + to specify a particular CPU variant of the ARM CPU.""" + features: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The optional features field specifies an array of strings, each listing a + required CPU feature (for example sse4 or aes.""" + + @overload def __init__( self, *, architecture: Optional[str] = None, os: Optional[str] = None, os_version: Optional[str] = None, - os_features: Optional[List[str]] = None, + os_features: Optional[list[str]] = None, variant: Optional[str] = None, - features: Optional[List[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword architecture: Specifies the CPU architecture, for example amd64 or ppc64le. - :paramtype architecture: str - :keyword os: The os field specifies the operating system, for example linux or windows. - :paramtype os: str - :keyword os_version: The optional os.version field specifies the operating system version, for - example 10.0.10586. - :paramtype os_version: str - :keyword os_features: The optional os.features field specifies an array of strings, each - listing a required OS feature (for example on Windows win32k. - :paramtype os_features: list[str] - :keyword variant: The optional variant field specifies a variant of the CPU, for example armv6l - to specify a particular CPU variant of the ARM CPU. - :paramtype variant: str - :keyword features: The optional features field specifies an array of strings, each listing a - required CPU feature (for example sse4 or aes. - :paramtype features: list[str] - """ - super().__init__(**kwargs) - self.architecture = architecture - self.os = os - self.os_version = os_version - self.os_features = os_features - self.variant = variant - self.features = features - - -class Repositories(_serialization.Model): - """List of repositories. - - :ivar repositories: Repository names. - :vartype repositories: list[str] - :ivar link: - :vartype link: str - """ + features: Optional[list[str]] = None, + ) -> None: ... - _attribute_map = { - "repositories": {"key": "repositories", "type": "[str]"}, - "link": {"key": "link", "type": "str"}, - } - - def __init__(self, *, repositories: Optional[List[str]] = None, link: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword repositories: Repository names. - :paramtype repositories: list[str] - :keyword link: - :paramtype link: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.repositories = repositories - self.link = link - - -class RepositoryTags(_serialization.Model): - """Result of the request to list tags of the image. - - :ivar name: Name of the image. - :vartype name: str - :ivar tags: List of tags. - :vartype tags: list[str] - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "tags": {"key": "tags", "type": "[str]"}, - } - def __init__(self, *, name: Optional[str] = None, tags: Optional[List[str]] = None, **kwargs: Any) -> None: - """ - :keyword name: Name of the image. - :paramtype name: str - :keyword tags: List of tags. - :paramtype tags: list[str] - """ - super().__init__(**kwargs) - self.name = name - self.tags = tags + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class RepositoryWriteableProperties(_serialization.Model): +class RepositoryWriteableProperties(_Model): """Changeable attributes for Repository. :ivar can_delete: Delete enabled. @@ -1390,13 +1133,24 @@ class RepositoryWriteableProperties(_serialization.Model): :vartype can_read: bool """ - _attribute_map = { - "can_delete": {"key": "deleteEnabled", "type": "bool"}, - "can_write": {"key": "writeEnabled", "type": "bool"}, - "can_list": {"key": "listEnabled", "type": "bool"}, - "can_read": {"key": "readEnabled", "type": "bool"}, - } - + can_delete: Optional[bool] = rest_field( + name="deleteEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Delete enabled.""" + can_write: Optional[bool] = rest_field( + name="writeEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Write enabled.""" + can_list: Optional[bool] = rest_field( + name="listEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """List enabled.""" + can_read: Optional[bool] = rest_field( + name="readEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Read enabled.""" + + @overload def __init__( self, *, @@ -1404,31 +1158,21 @@ def __init__( can_write: Optional[bool] = None, can_list: Optional[bool] = None, can_read: Optional[bool] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword can_delete: Delete enabled. - :paramtype can_delete: bool - :keyword can_write: Write enabled. - :paramtype can_write: bool - :keyword can_list: List enabled. - :paramtype can_list: bool - :keyword can_read: Read enabled. - :paramtype can_read: bool + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.can_delete = can_delete - self.can_write = can_write - self.can_list = can_list - self.can_read = can_read + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class TagAttributesBase(_serialization.Model): - """Tag attribute details. - - Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. +class TagAttributesBase(_Model): + """Tag attribute details. :ivar name: Tag name. Required. :vartype name: str @@ -1438,63 +1182,50 @@ class TagAttributesBase(_serialization.Model): :vartype created_on: ~datetime.datetime :ivar last_updated_on: Tag last update time. Required. :vartype last_updated_on: ~datetime.datetime + :ivar signed: Is signed. + :vartype signed: bool :ivar changeable_attributes: Writeable properties of the resource. Required. - :vartype changeable_attributes: ~container_registry.models.TagWriteableProperties - """ - - _validation = { - "name": {"required": True, "readonly": True}, - "digest": {"required": True, "readonly": True}, - "created_on": {"required": True, "readonly": True}, - "last_updated_on": {"required": True, "readonly": True}, - "changeable_attributes": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "digest": {"key": "digest", "type": "str"}, - "created_on": {"key": "createdTime", "type": "iso-8601"}, - "last_updated_on": {"key": "lastUpdateTime", "type": "iso-8601"}, - "changeable_attributes": {"key": "changeableAttributes", "type": "TagWriteableProperties"}, - } - - def __init__(self, *, changeable_attributes: "_models.TagWriteableProperties", **kwargs: Any) -> None: - """ - :keyword changeable_attributes: Writeable properties of the resource. Required. - :paramtype changeable_attributes: ~container_registry.models.TagWriteableProperties - """ - super().__init__(**kwargs) - self.name = None - self.digest = None - self.created_on = None - self.last_updated_on = None - self.changeable_attributes = changeable_attributes - - -class TagAttributesTag(_serialization.Model): - """Tag. - - :ivar signature_record: SignatureRecord value. - :vartype signature_record: str + :vartype changeable_attributes: + ~azure.containerregistry._generated.models.TagWriteableProperties """ - _attribute_map = { - "signature_record": {"key": "signatureRecord", "type": "str"}, - } + name: str = rest_field(visibility=["read"]) + """Tag name. Required.""" + digest: str = rest_field(visibility=["read"]) + """Tag digest. Required.""" + created_on: datetime.datetime = rest_field(name="createdTime", visibility=["read"], format="rfc3339") + """Tag created time. Required.""" + last_updated_on: datetime.datetime = rest_field(name="lastUpdateTime", visibility=["read"], format="rfc3339") + """Tag last update time. Required.""" + signed: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Is signed.""" + changeable_attributes: "_models.TagWriteableProperties" = rest_field( + name="changeableAttributes", + visibility=["read", "create", "update", "delete", "query"], + ) + """Writeable properties of the resource. Required.""" + + @overload + def __init__( + self, + *, + changeable_attributes: "_models.TagWriteableProperties", + signed: Optional[bool] = None, + ) -> None: ... - def __init__(self, *, signature_record: Optional[str] = None, **kwargs: Any) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword signature_record: SignatureRecord value. - :paramtype signature_record: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.signature_record = signature_record + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class TagList(_serialization.Model): - """List of tag details. - All required parameters must be populated in order to send to Azure. +class TagList(_Model): + """List of tag details. :ivar registry_login_server: Registry login server name. This is likely to be similar to {registry-name}.azurecr.io. Required. @@ -1502,52 +1233,46 @@ class TagList(_serialization.Model): :ivar repository: Image name. Required. :vartype repository: str :ivar tag_attribute_bases: List of tag attribute details. Required. - :vartype tag_attribute_bases: list[~container_registry.models.TagAttributesBase] - :ivar link: + :vartype tag_attribute_bases: + list[~azure.containerregistry._generated.models.TagAttributesBase] + :ivar link: Link to the next page of results. :vartype link: str """ - _validation = { - "registry_login_server": {"required": True}, - "repository": {"required": True}, - "tag_attribute_bases": {"required": True}, - } - - _attribute_map = { - "registry_login_server": {"key": "registry", "type": "str"}, - "repository": {"key": "imageName", "type": "str"}, - "tag_attribute_bases": {"key": "tags", "type": "[TagAttributesBase]"}, - "link": {"key": "link", "type": "str"}, - } - + registry_login_server: str = rest_field(name="registry", visibility=["read", "create", "update", "delete", "query"]) + """Registry login server name. This is likely to be similar to + {registry-name}.azurecr.io. Required.""" + repository: str = rest_field(name="imageName", visibility=["read", "create", "update", "delete", "query"]) + """Image name. Required.""" + tag_attribute_bases: list["_models.TagAttributesBase"] = rest_field( + name="tags", visibility=["read", "create", "update", "delete", "query"] + ) + """List of tag attribute details. Required.""" + link: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Link to the next page of results.""" + + @overload def __init__( self, *, registry_login_server: str, repository: str, - tag_attribute_bases: List["_models.TagAttributesBase"], + tag_attribute_bases: list["_models.TagAttributesBase"], link: Optional[str] = None, - **kwargs: Any - ) -> None: + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword registry_login_server: Registry login server name. This is likely to be similar to - {registry-name}.azurecr.io. Required. - :paramtype registry_login_server: str - :keyword repository: Image name. Required. - :paramtype repository: str - :keyword tag_attribute_bases: List of tag attribute details. Required. - :paramtype tag_attribute_bases: list[~container_registry.models.TagAttributesBase] - :keyword link: - :paramtype link: str + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(**kwargs) - self.registry_login_server = registry_login_server - self.repository = repository - self.tag_attribute_bases = tag_attribute_bases - self.link = link + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) -class TagWriteableProperties(_serialization.Model): + +class TagWriteableProperties(_Model): """Changeable attributes. :ivar can_delete: Delete enabled. @@ -1560,13 +1285,24 @@ class TagWriteableProperties(_serialization.Model): :vartype can_read: bool """ - _attribute_map = { - "can_delete": {"key": "deleteEnabled", "type": "bool"}, - "can_write": {"key": "writeEnabled", "type": "bool"}, - "can_list": {"key": "listEnabled", "type": "bool"}, - "can_read": {"key": "readEnabled", "type": "bool"}, - } - + can_delete: Optional[bool] = rest_field( + name="deleteEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Delete enabled.""" + can_write: Optional[bool] = rest_field( + name="writeEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Write enabled.""" + can_list: Optional[bool] = rest_field( + name="listEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """List enabled.""" + can_read: Optional[bool] = rest_field( + name="readEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Read enabled.""" + + @overload def __init__( self, *, @@ -1574,131 +1310,14 @@ def __init__( can_write: Optional[bool] = None, can_list: Optional[bool] = None, can_read: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword can_delete: Delete enabled. - :paramtype can_delete: bool - :keyword can_write: Write enabled. - :paramtype can_write: bool - :keyword can_list: List enabled. - :paramtype can_list: bool - :keyword can_read: Read enabled. - :paramtype can_read: bool - """ - super().__init__(**kwargs) - self.can_delete = can_delete - self.can_write = can_write - self.can_list = can_list - self.can_read = can_read - - -class V1Manifest(Manifest): - """Returns the requested V1 manifest file. - - :ivar schema_version: Schema version. - :vartype schema_version: int - :ivar architecture: CPU architecture. - :vartype architecture: str - :ivar name: Image name. - :vartype name: str - :ivar tag: Image tag. - :vartype tag: str - :ivar fs_layers: List of layer information. - :vartype fs_layers: list[~container_registry.models.FsLayer] - :ivar history: Image history. - :vartype history: list[~container_registry.models.History] - :ivar signatures: Image signature. - :vartype signatures: list[~container_registry.models.ImageSignature] - """ + ) -> None: ... - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - "architecture": {"key": "architecture", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "tag": {"key": "tag", "type": "str"}, - "fs_layers": {"key": "fsLayers", "type": "[FsLayer]"}, - "history": {"key": "history", "type": "[History]"}, - "signatures": {"key": "signatures", "type": "[ImageSignature]"}, - } - - def __init__( - self, - *, - schema_version: Optional[int] = None, - architecture: Optional[str] = None, - name: Optional[str] = None, - tag: Optional[str] = None, - fs_layers: Optional[List["_models.FsLayer"]] = None, - history: Optional[List["_models.History"]] = None, - signatures: Optional[List["_models.ImageSignature"]] = None, - **kwargs: Any - ) -> None: + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: """ - :keyword schema_version: Schema version. - :paramtype schema_version: int - :keyword architecture: CPU architecture. - :paramtype architecture: str - :keyword name: Image name. - :paramtype name: str - :keyword tag: Image tag. - :paramtype tag: str - :keyword fs_layers: List of layer information. - :paramtype fs_layers: list[~container_registry.models.FsLayer] - :keyword history: Image history. - :paramtype history: list[~container_registry.models.History] - :keyword signatures: Image signature. - :paramtype signatures: list[~container_registry.models.ImageSignature] + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] """ - super().__init__(schema_version=schema_version, **kwargs) - self.architecture = architecture - self.name = name - self.tag = tag - self.fs_layers = fs_layers - self.history = history - self.signatures = signatures - - -class V2Manifest(Manifest): - """Returns the requested Docker V2 Manifest file. - :ivar schema_version: Schema version. - :vartype schema_version: int - :ivar media_type: Media type for this Manifest. - :vartype media_type: str - :ivar config: V2 image config descriptor. - :vartype config: ~container_registry.models.Descriptor - :ivar layers: List of V2 image layer information. - :vartype layers: list[~container_registry.models.Descriptor] - """ - - _attribute_map = { - "schema_version": {"key": "schemaVersion", "type": "int"}, - "media_type": {"key": "mediaType", "type": "str"}, - "config": {"key": "config", "type": "Descriptor"}, - "layers": {"key": "layers", "type": "[Descriptor]"}, - } - - def __init__( - self, - *, - schema_version: Optional[int] = None, - media_type: Optional[str] = None, - config: Optional["_models.Descriptor"] = None, - layers: Optional[List["_models.Descriptor"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword schema_version: Schema version. - :paramtype schema_version: int - :keyword media_type: Media type for this Manifest. - :paramtype media_type: str - :keyword config: V2 image config descriptor. - :paramtype config: ~container_registry.models.Descriptor - :keyword layers: List of V2 image layer information. - :paramtype layers: list[~container_registry.models.Descriptor] - """ - super().__init__(schema_version=schema_version, **kwargs) - self.media_type = media_type - self.config = config - self.layers = layers + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_patch.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_patch.py index 029b47fe4787..ea765788358a 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_patch.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/models/_patch.py @@ -1,17 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import List -__all__ = [] # type: List[str] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/__init__.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/__init__.py index bcf2637fb304..461f85a3cebf 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/__init__.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/__init__.py @@ -1,15 +1,23 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import ContainerRegistryOperations -from ._operations import ContainerRegistryBlobOperations -from ._operations import AuthenticationOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ContainerRegistryOperations # type: ignore +from ._operations import ContainerRegistryBlobOperations # type: ignore +from ._operations import AuthenticationOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -17,5 +25,5 @@ "ContainerRegistryBlobOperations", "AuthenticationOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_operations.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_operations.py index b15ebfa53cb0..b90a60eda5f4 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_operations.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_operations.py @@ -1,19 +1,26 @@ # pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.7.8) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, overload +import json +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged @@ -23,11 +30,19 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._serialization import Serializer -from .._vendor import raise_if_not_implemented +from .._configuration import ContainerRegistryClientConfiguration +from .._utils.model_base import ( + Model as _Model, + SdkJSONEncoder, + _deserialize, + _failsafe_deserialize, +) +from .._utils.serialization import Deserializer, Serializer +from .._utils.utils import prepare_multipart_form_data +JSON = MutableMapping[str, Any] T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -36,24 +51,25 @@ def build_container_registry_check_docker_v2_support_request( # pylint: disable=name-too-long **kwargs: Any, ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/" - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_container_registry_get_manifest_request( # pylint: disable=name-too-long name: str, reference: str, *, accept: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/manifests/{reference}" path_format_arguments = { @@ -63,21 +79,24 @@ def build_container_registry_get_manifest_request( # pylint: disable=name-too-l _url: str = _url.format(**path_format_arguments) # type: ignore + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + # Construct headers if accept is not None: _headers["accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_container_registry_create_manifest_request( # pylint: disable=name-too-long - name: str, reference: str, *, content: IO, **kwargs: Any + name: str, reference: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/manifests/{reference}" path_format_arguments = { @@ -87,21 +106,22 @@ def build_container_registry_create_manifest_request( # pylint: disable=name-to _url: str = _url.format(**path_format_arguments) # type: ignore + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_container_registry_delete_manifest_request( # pylint: disable=name-too-long name: str, reference: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/manifests/{reference}" path_format_arguments = { @@ -111,10 +131,10 @@ def build_container_registry_delete_manifest_request( # pylint: disable=name-to _url: str = _url.format(**path_format_arguments) # type: ignore - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_container_registry_get_repositories_request( # pylint: disable=name-too-long @@ -130,11 +150,11 @@ def build_container_registry_get_repositories_request( # pylint: disable=name-t _url = "/acr/v1/_catalog" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if last is not None: _params["last"] = _SERIALIZER.query("last", last, "str") if n is not None: _params["n"] = _SERIALIZER.query("n", n, "int") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -171,12 +191,9 @@ def build_container_registry_get_properties_request( # pylint: disable=name-too def build_container_registry_delete_repository_request( # pylint: disable=name-too-long name: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/acr/v1/{name}" path_format_arguments = { @@ -188,10 +205,7 @@ def build_container_registry_delete_repository_request( # pylint: disable=name- # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_container_registry_update_properties_request( # pylint: disable=name-too-long @@ -228,7 +242,7 @@ def build_container_registry_get_tags_request( # pylint: disable=name-too-long *, last: Optional[str] = None, n: Optional[int] = None, - orderby: Optional[str] = None, + orderby: Optional[Union[str, _models.ArtifactTagOrder]] = None, digest: Optional[str] = None, **kwargs: Any, ) -> HttpRequest: @@ -247,6 +261,7 @@ def build_container_registry_get_tags_request( # pylint: disable=name-too-long _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if last is not None: _params["last"] = _SERIALIZER.query("last", last, "str") if n is not None: @@ -255,7 +270,6 @@ def build_container_registry_get_tags_request( # pylint: disable=name-too-long _params["orderby"] = _SERIALIZER.query("orderby", orderby, "str") if digest is not None: _params["digest"] = _SERIALIZER.query("digest", digest, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -323,12 +337,9 @@ def build_container_registry_update_tag_attributes_request( # pylint: disable=n def build_container_registry_delete_tag_request( # pylint: disable=name-too-long name: str, reference: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/acr/v1/{name}/_tags/{reference}" path_format_arguments = { @@ -341,14 +352,16 @@ def build_container_registry_delete_tag_request( # pylint: disable=name-too-lon # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_container_registry_get_manifests_request( # pylint: disable=name-too-long - name: str, *, last: Optional[str] = None, n: Optional[int] = None, orderby: Optional[str] = None, **kwargs: Any + name: str, + *, + last: Optional[str] = None, + n: Optional[int] = None, + orderby: Optional[Union[str, _models.ArtifactManifestOrder]] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -365,13 +378,13 @@ def build_container_registry_get_manifests_request( # pylint: disable=name-too- _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if last is not None: _params["last"] = _SERIALIZER.query("last", last, "str") if n is not None: _params["n"] = _SERIALIZER.query("n", n, "int") if orderby is not None: _params["orderby"] = _SERIALIZER.query("orderby", orderby, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -440,7 +453,9 @@ def build_container_registry_blob_get_blob_request( # pylint: disable=name-too- name: str, digest: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) accept = _headers.pop("Accept", "application/octet-stream") # Construct URL @@ -452,19 +467,21 @@ def build_container_registry_blob_get_blob_request( # pylint: disable=name-too- _url: str = _url.format(**path_format_arguments) # type: ignore + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_container_registry_blob_check_blob_exists_request( # pylint: disable=name-too-long name: str, digest: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/blobs/{digest}" path_format_arguments = { @@ -474,15 +491,18 @@ def build_container_registry_blob_check_blob_exists_request( # pylint: disable= _url: str = _url.format(**path_format_arguments) # type: ignore - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) def build_container_registry_blob_delete_blob_request( # pylint: disable=name-too-long name: str, digest: str, **kwargs: Any ) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/blobs/{digest}" path_format_arguments = { @@ -492,17 +512,18 @@ def build_container_registry_blob_delete_blob_request( # pylint: disable=name-t _url: str = _url.format(**path_format_arguments) # type: ignore - return HttpRequest(method="DELETE", url=_url, **kwargs) + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_container_registry_blob_mount_blob_request( # pylint: disable=name-too-long name: str, *, from_parameter: str, mount: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - accept = _headers.pop("Accept", "application/json") - + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/blobs/uploads/" path_format_arguments = { @@ -512,116 +533,111 @@ def build_container_registry_blob_mount_blob_request( # pylint: disable=name-to _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "str") _params["mount"] = _SERIALIZER.query("mount", mount, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) def build_container_registry_blob_get_upload_status_request( # pylint: disable=name-too-long - next_link: str, **kwargs: Any + next_blob_uuid_link: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/{nextBlobUuidLink}" path_format_arguments = { - "nextBlobUuidLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + "nextBlobUuidLink": _SERIALIZER.url("next_blob_uuid_link", next_blob_uuid_link, "str", skip_quote=True), } _url: str = _url.format(**path_format_arguments) # type: ignore - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_container_registry_blob_upload_chunk_request( # pylint: disable=name-too-long - next_link: str, *, content: IO, **kwargs: Any + next_blob_uuid_link: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - + content_type: str = kwargs.pop("content_type") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/{nextBlobUuidLink}" path_format_arguments = { - "nextBlobUuidLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + "nextBlobUuidLink": _SERIALIZER.url("next_blob_uuid_link", next_blob_uuid_link, "str", skip_quote=True), } _url: str = _url.format(**path_format_arguments) # type: ignore + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="PATCH", url=_url, headers=_headers, content=content, **kwargs) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_container_registry_blob_complete_upload_request( # pylint: disable=name-too-long - next_link: str, *, digest: str, content: Optional[IO] = None, **kwargs: Any + next_blob_uuid_link: str, *, digest: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/{nextBlobUuidLink}" path_format_arguments = { - "nextBlobUuidLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + "nextBlobUuidLink": _SERIALIZER.url("next_blob_uuid_link", next_blob_uuid_link, "str", skip_quote=True), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["digest"] = _SERIALIZER.query("digest", digest, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_container_registry_blob_cancel_upload_request( # pylint: disable=name-too-long - next_link: str, **kwargs: Any + next_blob_uuid_link: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/{nextBlobUuidLink}" path_format_arguments = { - "nextBlobUuidLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + "nextBlobUuidLink": _SERIALIZER.url("next_blob_uuid_link", next_blob_uuid_link, "str", skip_quote=True), } _url: str = _url.format(**path_format_arguments) # type: ignore - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_container_registry_blob_start_upload_request( # pylint: disable=name-too-long name: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/blobs/uploads/" path_format_arguments = { @@ -630,17 +646,19 @@ def build_container_registry_blob_start_upload_request( # pylint: disable=name- _url: str = _url.format(**path_format_arguments) # type: ignore - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) def build_container_registry_blob_get_chunk_request( # pylint: disable=name-too-long - name: str, digest: str, *, range_header: str, **kwargs: Any + name: str, digest: str, *, range: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) accept = _headers.pop("Accept", "application/octet-stream") # Construct URL @@ -652,20 +670,23 @@ def build_container_registry_blob_get_chunk_request( # pylint: disable=name-too _url: str = _url.format(**path_format_arguments) # type: ignore + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + # Construct headers - _headers["Range"] = _SERIALIZER.header("range_header", range_header, "str") + _headers["range"] = _SERIALIZER.header("range", range, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_container_registry_blob_check_chunk_exists_request( # pylint: disable=name-too-long - name: str, digest: str, *, range_header: str, **kwargs: Any + name: str, digest: str, *, range: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - accept = _headers.pop("Accept", "application/json") - + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # Construct URL _url = "/v2/{name}/blobs/{digest}" path_format_arguments = { @@ -675,11 +696,68 @@ def build_container_registry_blob_check_chunk_exists_request( # pylint: disable _url: str = _url.format(**path_format_arguments) # type: ignore + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["range"] = _SERIALIZER.header("range", range, "str") + + return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_authentication_exchange_aad_access_token_for_acr_refresh_token_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/oauth2/exchange" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_authentication_exchange_acr_refresh_token_for_acr_access_token_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/oauth2/token" + # Construct headers - _headers["Range"] = _SERIALIZER.header("range_header", range_header, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_authentication_get_acr_access_token_from_login_request( # pylint: disable=name-too-long + *, service: str, scope: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/oauth2/token" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["service"] = _SERIALIZER.query("service", service, "str") + _params["scope"] = _SERIALIZER.query("scope", scope, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ContainerRegistryOperations: @@ -688,18 +766,16 @@ class ContainerRegistryOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~container_registry.ContainerRegistry`'s + :class:`~azure.containerregistry._generated.ContainerRegistryClient`'s :attr:`container_registry` attribute. """ - models = _models - - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ContainerRegistryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def check_docker_v2_support(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -709,7 +785,7 @@ def check_docker_v2_support(self, **kwargs: Any) -> None: # pylint: disable=inc :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -722,38 +798,40 @@ def check_docker_v2_support(self, **kwargs: Any) -> None: # pylint: disable=inc cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_check_docker_v2_support_request( + _request = build_container_registry_check_docker_v2_support_request( + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get_manifest( self, name: str, reference: str, *, accept: Optional[str] = None, **kwargs: Any - ) -> Iterator[bytes]: - """Get the manifest identified by ``name`` and ``reference`` where ``reference`` can be a tag or - digest. + ) -> _models.ManifestWrapper: + """Get the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. :param name: Name of the image (including the namespace). Required. :type name: str @@ -762,11 +840,11 @@ def get_manifest( :keyword accept: Accept header string delimited by comma. For example, application/vnd.docker.distribution.manifest.v2+json. Default value is None. :paramtype accept: str - :return: Iterator of the response bytes - :rtype: Iterator[bytes] + :return: ManifestWrapper. The ManifestWrapper is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ManifestWrapper :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -777,57 +855,155 @@ def get_manifest( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + cls: ClsType[_models.ManifestWrapper] = kwargs.pop("cls", None) - request = build_container_registry_get_manifest_request( + _request = build_container_registry_get_manifest_request( name=name, reference=reference, accept=accept, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = True + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = response.iter_bytes() + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ManifestWrapper, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def create_manifest(self, name: str, reference: str, payload: IO, **kwargs: Any) -> Any: - """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be a tag or - digest. + @overload + def create_manifest( + self, + name: str, + reference: str, + payload: _models.Manifest, + *, + content_type: str = "application/vnd.docker.distribution.manifest.v2+json", + **kwargs: Any, + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: A tag or a digest, pointing to a specific image. Required. + :type reference: str + :param payload: Manifest body, can take v1 or v2 values depending on accept header. Required. + :type payload: ~azure.containerregistry._generated.models.Manifest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/vnd.docker.distribution.manifest.v2+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_manifest( + self, + name: str, + reference: str, + payload: JSON, + *, + content_type: str = "application/vnd.docker.distribution.manifest.v2+json", + **kwargs: Any, + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. :param name: Name of the image (including the namespace). Required. :type name: str :param reference: A tag or a digest, pointing to a specific image. Required. :type reference: str :param payload: Manifest body, can take v1 or v2 values depending on accept header. Required. - :type payload: IO - :return: any - :rtype: any + :type payload: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/vnd.docker.distribution.manifest.v2+json". + :paramtype content_type: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + + @overload + def create_manifest( + self, + name: str, + reference: str, + payload: IO[bytes], + *, + content_type: str = "application/vnd.docker.distribution.manifest.v2+json", + **kwargs: Any, + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: A tag or a digest, pointing to a specific image. Required. + :type reference: str + :param payload: Manifest body, can take v1 or v2 values depending on accept header. Required. + :type payload: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/vnd.docker.distribution.manifest.v2+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_manifest( # pylint: disable=inconsistent-return-statements + self, + name: str, + reference: str, + payload: Union[_models.Manifest, JSON, IO[bytes]], + **kwargs: Any, + ) -> None: + """Put the manifest identified by ``name`` and ``reference`` where ``reference`` can be + a tag or digest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: A tag or a digest, pointing to a specific image. Required. + :type reference: str + :param payload: Manifest body, can take v1 or v2 values depending on accept header. Is one of + the following types: Manifest, JSON, IO[bytes] Required. + :type payload: ~azure.containerregistry._generated.models.Manifest or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -838,60 +1014,61 @@ def create_manifest(self, name: str, reference: str, payload: IO, **kwargs: Any) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") - ) - cls: ClsType[Any] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) - _content = payload + content_type = content_type or "application/vnd.docker.distribution.manifest.v2+json" + _content = None + if isinstance(payload, (IOBase, bytes)): + _content = payload + else: + _content = json.dumps(payload, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_container_registry_create_manifest_request( + _request = build_container_registry_create_manifest_request( name=name, reference=reference, content_type=content_type, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) response_headers["Docker-Content-Digest"] = self._deserialize( "str", response.headers.get("Docker-Content-Digest") ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - - deserialized = self._deserialize("object", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace def delete_manifest( # pylint: disable=inconsistent-return-statements self, name: str, reference: str, **kwargs: Any ) -> None: - """Delete the manifest identified by ``name`` and ``reference``. Note that a manifest can *only* - be deleted by ``digest``. + """Delete the manifest identified by ``name`` and ``reference``. Note that a manifest + can *only* be deleted by ``digest``. :param name: Name of the image (including the namespace). Required. :type name: str @@ -901,7 +1078,7 @@ def delete_manifest( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -914,42 +1091,44 @@ def delete_manifest( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_delete_manifest_request( + _request = build_container_registry_delete_manifest_request( name=name, reference=reference, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 404]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get_repositories(self, *, last: Optional[str] = None, n: Optional[int] = None, **kwargs: Any) -> Iterable[str]: + def get_repositories(self, *, last: Optional[str] = None, n: Optional[int] = None, **kwargs: Any) -> ItemPaged[str]: """List repositories. :keyword last: Query parameter for the last item in previous query. Result set will include values lexically after last. Default value is None. :paramtype last: str - :keyword n: query parameter for max number of items. Default value is None. + :keyword n: Query parameter for max number of items. Default value is None. :paramtype n: int :return: An iterator like instance of str :rtype: ~azure.core.paging.ItemPaged[str] @@ -958,9 +1137,9 @@ def get_repositories(self, *, last: Optional[str] = None, n: Optional[int] = Non _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.Repositories] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[list[str]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -971,7 +1150,7 @@ def get_repositories(self, *, last: Optional[str] = None, n: Optional[int] = Non def prepare_request(next_link=None): if not next_link: - request = build_container_registry_get_repositories_request( + _request = build_container_registry_get_repositories_request( last=last, n=n, api_version=self._config.api_version, @@ -979,9 +1158,14 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url( + "self._config.endpoint", + self._config.endpoint, + "str", + skip_quote=True, + ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -993,39 +1177,49 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + params=_next_request_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url( + "self._config.endpoint", + self._config.endpoint, + "str", + skip_quote=True, + ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): - deserialized = self._deserialize( - _models._models.Repositories, pipeline_response # pylint: disable=protected-access - ) - list_of_elem = deserialized.repositories + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[str], deserialized.get("repositories", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.link or None, iter(list_of_elem) + return deserialized.get("link") or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1038,11 +1232,12 @@ def get_properties(self, name: str, **kwargs: Any) -> _models.ContainerRepositor :param name: Name of the image (including the namespace). Required. :type name: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1055,37 +1250,46 @@ def get_properties(self, name: str, **kwargs: Any) -> _models.ContainerRepositor cls: ClsType[_models.ContainerRepositoryProperties] = kwargs.pop("cls", None) - request = build_container_registry_get_properties_request( + _request = build_container_registry_get_properties_request( name=name, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ContainerRepositoryProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ContainerRepositoryProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def delete_repository(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -1097,7 +1301,7 @@ def delete_repository(self, name: str, **kwargs: Any) -> None: # pylint: disabl :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1110,33 +1314,34 @@ def delete_repository(self, name: str, **kwargs: Any) -> None: # pylint: disabl cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_delete_repository_request( + _request = build_container_registry_delete_repository_request( name=name, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 404]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @overload def update_properties( @@ -1147,57 +1352,94 @@ def update_properties( content_type: str = "application/json", **kwargs: Any, ) -> _models.ContainerRepositoryProperties: - """Update the attribute identified by ``name`` where ``reference`` is the name of the repository. + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. :param name: Name of the image (including the namespace). Required. :type name: str :param value: Repository attribute value. Default value is None. - :type value: ~container_registry.models.RepositoryWriteableProperties + :type value: ~azure.containerregistry._generated.models.RepositoryWriteableProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update_properties( - self, name: str, value: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any + self, + name: str, + value: Optional[JSON] = None, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.ContainerRepositoryProperties: + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param value: Repository attribute value. Default value is None. + :type value: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_properties( + self, + name: str, + value: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models.ContainerRepositoryProperties: - """Update the attribute identified by ``name`` where ``reference`` is the name of the repository. + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. :param name: Name of the image (including the namespace). Required. :type name: str :param value: Repository attribute value. Default value is None. - :type value: IO + :type value: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update_properties( - self, name: str, value: Optional[Union[_models.RepositoryWriteableProperties, IO]] = None, **kwargs: Any + self, + name: str, + value: Optional[Union[_models.RepositoryWriteableProperties, JSON, IO[bytes]]] = None, + **kwargs: Any, ) -> _models.ContainerRepositoryProperties: - """Update the attribute identified by ``name`` where ``reference`` is the name of the repository. + """Update the attribute identified by ``name`` where ``reference`` is the name of the + repository. :param name: Name of the image (including the namespace). Required. :type name: str - :param value: Repository attribute value. Is either a RepositoryWriteableProperties type or a - IO type. Default value is None. - :type value: ~container_registry.models.RepositoryWriteableProperties or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: ContainerRepositoryProperties - :rtype: ~container_registry.models.ContainerRepositoryProperties + :param value: Repository attribute value. Is one of the following types: + RepositoryWriteableProperties, JSON, IO[bytes] Default value is None. + :type value: ~azure.containerregistry._generated.models.RepositoryWriteableProperties or JSON + or IO[bytes] + :return: ContainerRepositoryProperties. The ContainerRepositoryProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ContainerRepositoryProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1209,53 +1451,61 @@ def update_properties( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if value else None cls: ClsType[_models.ContainerRepositoryProperties] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None + content_type = content_type or "application/json" if value else None _content = None if isinstance(value, (IOBase, bytes)): _content = value else: if value is not None: - _json = self._serialize.body(value, "RepositoryWriteableProperties") + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - request = build_container_registry_update_properties_request( + _request = build_container_registry_update_properties_request( name=name, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ContainerRepositoryProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ContainerRepositoryProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def get_tags( @@ -1264,10 +1514,10 @@ def get_tags( *, last: Optional[str] = None, n: Optional[int] = None, - orderby: Optional[str] = None, + orderby: Optional[Union[str, _models.ArtifactTagOrder]] = None, digest: Optional[str] = None, **kwargs: Any, - ) -> Iterable["_models.TagAttributesBase"]: + ) -> _models.TagList: """List tags of a repository. :param name: Name of the image (including the namespace). Required. @@ -1277,20 +1527,16 @@ def get_tags( :paramtype last: str :keyword n: query parameter for max number of items. Default value is None. :paramtype n: int - :keyword orderby: orderby query parameter. Default value is None. - :paramtype orderby: str + :keyword orderby: orderby query parameter. Known values are: "none", "timedesc", and "timeasc". + Default value is None. + :paramtype orderby: str or ~azure.containerregistry._generated.models.ArtifactTagOrder :keyword digest: filter by digest. Default value is None. :paramtype digest: str - :return: An iterator like instance of TagAttributesBase - :rtype: ~azure.core.paging.ItemPaged[~container_registry.models.TagAttributesBase] + :return: TagList. The TagList is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.TagList :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models._models.TagList] = kwargs.pop("cls", None) # pylint: disable=protected-access - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1298,72 +1544,58 @@ def get_tags( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - request = build_container_registry_get_tags_request( - name=name, - last=last, - n=n, - orderby=orderby, - digest=digest, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + cls: ClsType[_models.TagList] = kwargs.pop("cls", None) - return request + _request = build_container_registry_get_tags_request( + name=name, + last=last, + n=n, + orderby=orderby, + digest=digest, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - def extract_data(pipeline_response): - deserialized = self._deserialize( - _models._models.TagList, pipeline_response # pylint: disable=protected-access - ) - list_of_elem = deserialized.tag_attribute_bases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.link or None, iter(list_of_elem) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) - raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) - return pipeline_response + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.TagList, response.json()) - return ItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> _models.ArtifactTagProperties: @@ -1373,11 +1605,11 @@ def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> _model :type name: str :param reference: Tag name. Required. :type reference: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1390,7 +1622,7 @@ def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> _model cls: ClsType[_models.ArtifactTagProperties] = kwargs.pop("cls", None) - request = build_container_registry_get_tag_properties_request( + _request = build_container_registry_get_tag_properties_request( name=name, reference=reference, api_version=self._config.api_version, @@ -1398,30 +1630,39 @@ def get_tag_properties(self, name: str, reference: str, **kwargs: Any) -> _model params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactTagProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactTagProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @overload def update_tag_attributes( @@ -1440,12 +1681,12 @@ def update_tag_attributes( :param reference: Tag name. Required. :type reference: str :param value: Tag attribute value. Default value is None. - :type value: ~container_registry.models.TagWriteableProperties + :type value: ~azure.containerregistry._generated.models.TagWriteableProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1454,7 +1695,7 @@ def update_tag_attributes( self, name: str, reference: str, - value: Optional[IO] = None, + value: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any, @@ -1466,12 +1707,38 @@ def update_tag_attributes( :param reference: Tag name. Required. :type reference: str :param value: Tag attribute value. Default value is None. - :type value: IO + :type value: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_tag_attributes( + self, + name: str, + reference: str, + value: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.ArtifactTagProperties: + """Update tag attributes. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param reference: Tag name. Required. + :type reference: str + :param value: Tag attribute value. Default value is None. + :type value: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1480,7 +1747,7 @@ def update_tag_attributes( self, name: str, reference: str, - value: Optional[Union[_models.TagWriteableProperties, IO]] = None, + value: Optional[Union[_models.TagWriteableProperties, JSON, IO[bytes]]] = None, **kwargs: Any, ) -> _models.ArtifactTagProperties: """Update tag attributes. @@ -1489,17 +1756,15 @@ def update_tag_attributes( :type name: str :param reference: Tag name. Required. :type reference: str - :param value: Tag attribute value. Is either a TagWriteableProperties type or a IO type. - Default value is None. - :type value: ~container_registry.models.TagWriteableProperties or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: ArtifactTagProperties - :rtype: ~container_registry.models.ArtifactTagProperties + :param value: Tag attribute value. Is one of the following types: TagWriteableProperties, JSON, + IO[bytes] Default value is None. + :type value: ~azure.containerregistry._generated.models.TagWriteableProperties or JSON or + IO[bytes] + :return: ArtifactTagProperties. The ArtifactTagProperties is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactTagProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1511,54 +1776,62 @@ def update_tag_attributes( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if value else None cls: ClsType[_models.ArtifactTagProperties] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None + content_type = content_type or "application/json" if value else None _content = None if isinstance(value, (IOBase, bytes)): _content = value else: if value is not None: - _json = self._serialize.body(value, "TagWriteableProperties") + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - request = build_container_registry_update_tag_attributes_request( + _request = build_container_registry_update_tag_attributes_request( name=name, reference=reference, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactTagProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactTagProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def delete_tag( # pylint: disable=inconsistent-return-statements @@ -1574,7 +1847,7 @@ def delete_tag( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1587,7 +1860,7 @@ def delete_tag( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_delete_tag_request( + _request = build_container_registry_delete_tag_request( name=name, reference=reference, api_version=self._config.api_version, @@ -1595,26 +1868,27 @@ def delete_tag( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 404]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get_manifests( @@ -1623,9 +1897,9 @@ def get_manifests( *, last: Optional[str] = None, n: Optional[int] = None, - orderby: Optional[str] = None, + orderby: Optional[Union[str, _models.ArtifactManifestOrder]] = None, **kwargs: Any, - ) -> Iterable["_models.ManifestAttributesBase"]: + ) -> _models.AcrManifests: """List manifests of a repository. :param name: Name of the image (including the namespace). Required. @@ -1635,18 +1909,14 @@ def get_manifests( :paramtype last: str :keyword n: query parameter for max number of items. Default value is None. :paramtype n: int - :keyword orderby: orderby query parameter. Default value is None. - :paramtype orderby: str - :return: An iterator like instance of ManifestAttributesBase - :rtype: ~azure.core.paging.ItemPaged[~container_registry.models.ManifestAttributesBase] + :keyword orderby: orderby query parameter. Known values are: "none", "timedesc", and "timeasc". + Default value is None. + :paramtype orderby: str or ~azure.containerregistry._generated.models.ArtifactManifestOrder + :return: AcrManifests. The AcrManifests is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrManifests :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models._models.AcrManifests] = kwargs.pop("cls", None) # pylint: disable=protected-access - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1654,71 +1924,57 @@ def get_manifests( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - request = build_container_registry_get_manifests_request( - name=name, - last=last, - n=n, - orderby=orderby, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), - } - request.url = self._client.format_url(request.url, **path_format_arguments) + cls: ClsType[_models.AcrManifests] = kwargs.pop("cls", None) - return request + _request = build_container_registry_get_manifests_request( + name=name, + last=last, + n=n, + orderby=orderby, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - def extract_data(pipeline_response): - deserialized = self._deserialize( - _models._models.AcrManifests, pipeline_response # pylint: disable=protected-access - ) - list_of_elem = deserialized.manifests - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.link or None, iter(list_of_elem) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) - raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) - return pipeline_response + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrManifests, response.json()) - return ItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace def get_manifest_properties(self, name: str, digest: str, **kwargs: Any) -> _models.ArtifactManifestProperties: @@ -1728,11 +1984,12 @@ def get_manifest_properties(self, name: str, digest: str, **kwargs: Any) -> _mod :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1745,7 +2002,7 @@ def get_manifest_properties(self, name: str, digest: str, **kwargs: Any) -> _mod cls: ClsType[_models.ArtifactManifestProperties] = kwargs.pop("cls", None) - request = build_container_registry_get_manifest_properties_request( + _request = build_container_registry_get_manifest_properties_request( name=name, digest=digest, api_version=self._config.api_version, @@ -1753,30 +2010,39 @@ def get_manifest_properties(self, name: str, digest: str, **kwargs: Any) -> _mod params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactManifestProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactManifestProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @overload def update_manifest_properties( @@ -1795,12 +2061,40 @@ def update_manifest_properties( :param digest: Digest of a BLOB. Required. :type digest: str :param value: Manifest attribute value. Default value is None. - :type value: ~container_registry.models.ManifestWriteableProperties + :type value: ~azure.containerregistry._generated.models.ManifestWriteableProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_manifest_properties( + self, + name: str, + digest: str, + value: Optional[JSON] = None, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.ArtifactManifestProperties: + """Update properties of a manifest. + + :param name: Name of the image (including the namespace). Required. + :type name: str + :param digest: Digest of a BLOB. Required. + :type digest: str + :param value: Manifest attribute value. Default value is None. + :type value: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1809,7 +2103,7 @@ def update_manifest_properties( self, name: str, digest: str, - value: Optional[IO] = None, + value: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any, @@ -1821,12 +2115,13 @@ def update_manifest_properties( :param digest: Digest of a BLOB. Required. :type digest: str :param value: Manifest attribute value. Default value is None. - :type value: IO + :type value: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1835,7 +2130,7 @@ def update_manifest_properties( self, name: str, digest: str, - value: Optional[Union[_models.ManifestWriteableProperties, IO]] = None, + value: Optional[Union[_models.ManifestWriteableProperties, JSON, IO[bytes]]] = None, **kwargs: Any, ) -> _models.ArtifactManifestProperties: """Update properties of a manifest. @@ -1844,17 +2139,16 @@ def update_manifest_properties( :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :param value: Manifest attribute value. Is either a ManifestWriteableProperties type or a IO - type. Default value is None. - :type value: ~container_registry.models.ManifestWriteableProperties or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: ArtifactManifestProperties - :rtype: ~container_registry.models.ArtifactManifestProperties + :param value: Manifest attribute value. Is one of the following types: + ManifestWriteableProperties, JSON, IO[bytes] Default value is None. + :type value: ~azure.containerregistry._generated.models.ManifestWriteableProperties or JSON or + IO[bytes] + :return: ArtifactManifestProperties. The ArtifactManifestProperties is compatible with + MutableMapping + :rtype: ~azure.containerregistry._generated.models.ArtifactManifestProperties :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1866,54 +2160,62 @@ def update_manifest_properties( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if value else None cls: ClsType[_models.ArtifactManifestProperties] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None + content_type = content_type or "application/json" if value else None _content = None if isinstance(value, (IOBase, bytes)): _content = value else: if value is not None: - _json = self._serialize.body(value, "ManifestWriteableProperties") + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - request = build_container_registry_update_manifest_properties_request( + _request = build_container_registry_update_manifest_properties_request( name=name, digest=digest, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("ArtifactManifestProperties", pipeline_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ArtifactManifestProperties, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore class ContainerRegistryBlobOperations: @@ -1922,18 +2224,16 @@ class ContainerRegistryBlobOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~container_registry.ContainerRegistry`'s + :class:`~azure.containerregistry._generated.ContainerRegistryClient`'s :attr:`container_registry_blob` attribute. """ - models = _models - - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ContainerRegistryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Iterator[bytes]]: @@ -1943,11 +2243,11 @@ def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Iterator[b :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :return: Iterator of the response bytes or None + :return: Iterator[bytes] or None :rtype: Iterator[bytes] or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1960,29 +2260,37 @@ def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Iterator[b cls: ClsType[Optional[Iterator[bytes]]] = kwargs.pop("cls", None) - request = build_container_registry_blob_get_blob_request( + _request = build_container_registry_blob_get_blob_request( name=name, digest=digest, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = True + _stream = kwargs.pop("stream", True) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 307]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) deserialized = None response_headers = {} @@ -1992,31 +2300,29 @@ def get_blob(self, name: str, digest: str, **kwargs: Any) -> Optional[Iterator[b "str", response.headers.get("Docker-Content-Digest") ) - deserialized = response.iter_bytes() - if response.status_code == 307: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace - def check_blob_exists( # pylint: disable=inconsistent-return-statements - self, name: str, digest: str, **kwargs: Any - ) -> None: + def check_blob_exists(self, name: str, digest: str, **kwargs: Any) -> bool: """Same as GET, except only the headers are returned. :param name: Name of the image (including the namespace). Required. :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :return: None - :rtype: None + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2029,29 +2335,31 @@ def check_blob_exists( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_check_blob_exists_request( + _request = build_container_registry_blob_check_blob_exists_request( name=name, digest=digest, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 307]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2065,7 +2373,8 @@ def check_blob_exists( # pylint: disable=inconsistent-return-statements response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def delete_blob( # pylint: disable=inconsistent-return-statements @@ -2081,7 +2390,7 @@ def delete_blob( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2094,29 +2403,32 @@ def delete_blob( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_delete_blob_request( + _request = build_container_registry_blob_delete_blob_request( name=name, digest=digest, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Docker-Content-Digest"] = self._deserialize( @@ -2124,7 +2436,7 @@ def delete_blob( # pylint: disable=inconsistent-return-statements ) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace def mount_blob( # pylint: disable=inconsistent-return-statements @@ -2142,7 +2454,7 @@ def mount_blob( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2155,30 +2467,32 @@ def mount_blob( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_mount_blob_request( + _request = build_container_registry_blob_mount_blob_request( name=name, from_parameter=from_parameter, mount=mount, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2189,23 +2503,24 @@ def mount_blob( # pylint: disable=inconsistent-return-statements ) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace def get_upload_status( # pylint: disable=inconsistent-return-statements - self, next_link: str, **kwargs: Any + self, next_blob_uuid_link: str, **kwargs: Any ) -> None: - """Retrieve status of upload identified by uuid. The primary purpose of this endpoint is to - resolve the current status of a resumable upload. + """Retrieve status of upload identified by uuid. The primary purpose of this + endpoint is to resolve the current status of a resumable upload. - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2218,28 +2533,30 @@ def get_upload_status( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_get_upload_status_request( - next_link=next_link, + _request = build_container_registry_blob_get_upload_status_request( + next_blob_uuid_link=next_blob_uuid_link, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2247,24 +2564,25 @@ def get_upload_status( # pylint: disable=inconsistent-return-statements response_headers["Docker-Upload-UUID"] = self._deserialize("str", response.headers.get("Docker-Upload-UUID")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace def upload_chunk( # pylint: disable=inconsistent-return-statements - self, next_link: str, value: IO, **kwargs: Any + self, next_blob_uuid_link: str, value: bytes, **kwargs: Any ) -> None: """Upload a stream of data without completing the upload. - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :param value: Raw data of blob. Required. - :type value: IO + :type value: bytes :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2280,30 +2598,32 @@ def upload_chunk( # pylint: disable=inconsistent-return-statements _content = value - request = build_container_registry_blob_upload_chunk_request( - next_link=next_link, + _request = build_container_registry_blob_upload_chunk_request( + next_blob_uuid_link=next_blob_uuid_link, content_type=content_type, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2312,27 +2632,34 @@ def upload_chunk( # pylint: disable=inconsistent-return-statements response_headers["Docker-Upload-UUID"] = self._deserialize("str", response.headers.get("Docker-Upload-UUID")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace def complete_upload( # pylint: disable=inconsistent-return-statements - self, next_link: str, value: Optional[IO] = None, *, digest: str, **kwargs: Any + self, + next_blob_uuid_link: str, + value: Optional[bytes] = None, + *, + digest: str, + **kwargs: Any, ) -> None: - """Complete the upload, providing all the data in the body, if necessary. A request without a body - will just complete the upload with previously uploaded content. + """Complete the upload, providing all the data in the body, if necessary. A + request without a body will just complete the upload with previously uploaded + content. - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :param value: Optional raw data of blob. Default value is None. - :type value: IO + :type value: bytes :keyword digest: Digest of a BLOB. Required. :paramtype digest: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2343,36 +2670,41 @@ def complete_upload( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/octet-stream")) + content_type: Optional[str] = kwargs.pop( + "content_type", _headers.pop("Content-Type", "application/octet-stream") + ) + content_type = content_type if value else None cls: ClsType[None] = kwargs.pop("cls", None) _content = value - request = build_container_registry_blob_complete_upload_request( - next_link=next_link, + _request = build_container_registry_blob_complete_upload_request( + next_blob_uuid_link=next_blob_uuid_link, digest=digest, content_type=content_type, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2383,21 +2715,24 @@ def complete_upload( # pylint: disable=inconsistent-return-statements ) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def cancel_upload(self, next_link: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Cancel outstanding upload processes, releasing associated resources. If this is not called, the - unfinished uploads will eventually timeout. + def cancel_upload( # pylint: disable=inconsistent-return-statements + self, next_blob_uuid_link: str, **kwargs: Any + ) -> None: + """Cancel outstanding upload processes, releasing associated resources. If this is + not called, the unfinished uploads will eventually timeout. - :param next_link: Link acquired from upload start or previous chunk. Note, do not include - initial / (must do substring(1) ). Required. - :type next_link: str + :param next_blob_uuid_link: Link acquired from upload start or previous chunk. Note, do not + include initial + / (must do substring(1) ). Required. + :type next_blob_uuid_link: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2410,32 +2745,34 @@ def cancel_upload(self, next_link: str, **kwargs: Any) -> None: # pylint: disab cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_cancel_upload_request( - next_link=next_link, + _request = build_container_registry_blob_cancel_upload_request( + next_blob_uuid_link=next_blob_uuid_link, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -2447,7 +2784,7 @@ def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2460,28 +2797,30 @@ def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_start_upload_request( + _request = build_container_registry_blob_start_upload_request( name=name, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2490,27 +2829,27 @@ def start_upload(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc response_headers["Docker-Upload-UUID"] = self._deserialize("str", response.headers.get("Docker-Upload-UUID")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_chunk(self, name: str, digest: str, *, range_header: str, **kwargs: Any) -> Iterator[bytes]: - """Retrieve the blob from the registry identified by ``digest``. This endpoint may also support - RFC7233 compliant range requests. Support can be detected by issuing a HEAD request. If the - header ``Accept-Range: bytes`` is returned, range requests can be used to fetch partial - content. + def get_chunk(self, name: str, digest: str, *, range: str, **kwargs: Any) -> Iterator[bytes]: + """Retrieve the blob from the registry identified by ``digest``. This endpoint may + also support RFC7233 compliant range requests. Support can be detected by + issuing a HEAD request. If the header ``Accept-Range: bytes`` is returned, range + requests can be used to fetch partial content. :param name: Name of the image (including the namespace). Required. :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :keyword range_header: Format : bytes=:code:``-:code:``, HTTP Range header - specifying blob chunk. Required. - :paramtype range_header: str - :return: Iterator of the response bytes + :keyword range: Format : bytes=-, HTTP Range header specifying blob chunk. + Required. + :paramtype range: str + :return: Iterator[bytes] :rtype: Iterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2523,30 +2862,38 @@ def get_chunk(self, name: str, digest: str, *, range_header: str, **kwargs: Any) cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_container_registry_blob_get_chunk_request( + _request = build_container_registry_blob_get_chunk_request( name=name, digest=digest, - range_header=range_header, + range=range, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = True + _stream = kwargs.pop("stream", True) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [206]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) @@ -2560,23 +2907,21 @@ def get_chunk(self, name: str, digest: str, *, range_header: str, **kwargs: Any) return deserialized # type: ignore @distributed_trace - def check_chunk_exists( # pylint: disable=inconsistent-return-statements - self, name: str, digest: str, *, range_header: str, **kwargs: Any - ) -> None: + def check_chunk_exists(self, name: str, digest: str, *, range: str, **kwargs: Any) -> bool: """Same as GET, except only the headers are returned. :param name: Name of the image (including the namespace). Required. :type name: str :param digest: Digest of a BLOB. Required. :type digest: str - :keyword range_header: Format : bytes=:code:``-:code:``, HTTP Range header - specifying blob chunk. Required. - :paramtype range_header: str - :return: None - :rtype: None + :keyword range: Format : bytes=-, HTTP Range header specifying blob chunk. + Required. + :paramtype range: str + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2589,30 +2934,32 @@ def check_chunk_exists( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_container_registry_blob_check_chunk_exists_request( + _request = build_container_registry_blob_check_chunk_exists_request( name=name, digest=digest, - range_header=range_header, + range=range, + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2620,31 +2967,298 @@ def check_chunk_exists( # pylint: disable=inconsistent-return-statements response_headers["Content-Range"] = self._deserialize("str", response.headers.get("Content-Range")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 -class AuthenticationOperations: # pylint: disable=abstract-class-instantiated +class AuthenticationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~container_registry.ContainerRegistry`'s + :class:`~azure.containerregistry._generated.ContainerRegistryClient`'s :attr:`authentication` attribute. """ - models = _models - - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - raise_if_not_implemented( - self.__class__, - [ - "exchange_aad_access_token_for_acr_refresh_token", - "exchange_acr_refresh_token_for_acr_access_token", - ], + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ContainerRegistryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def exchange_aad_access_token_for_acr_refresh_token( # pylint: disable=name-too-long + self, body: _models.MultipartBodyParameter, **kwargs: Any + ) -> _models.AcrRefreshToken: + """Exchange AAD tokens for an ACR refresh Token. + + :param body: The body of the request. Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter + :return: AcrRefreshToken. The AcrRefreshToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrRefreshToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def exchange_aad_access_token_for_acr_refresh_token( # pylint: disable=name-too-long + self, body: JSON, **kwargs: Any + ) -> _models.AcrRefreshToken: + """Exchange AAD tokens for an ACR refresh Token. + + :param body: The body of the request. Required. + :type body: JSON + :return: AcrRefreshToken. The AcrRefreshToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrRefreshToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def exchange_aad_access_token_for_acr_refresh_token( # pylint: disable=name-too-long + self, body: Union[_models.MultipartBodyParameter, JSON], **kwargs: Any + ) -> _models.AcrRefreshToken: + """Exchange AAD tokens for an ACR refresh Token. + + :param body: The body of the request. Is either a MultipartBodyParameter type or a JSON type. + Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter or JSON + :return: AcrRefreshToken. The AcrRefreshToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrRefreshToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AcrRefreshToken] = kwargs.pop("cls", None) + + _body = body.as_dict() if isinstance(body, _Model) else body + _file_fields: list[str] = [] + _data_fields: list[str] = [ + "grantType", + "service", + "tenant", + "refreshToken", + "accessToken", + ] + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) + + _request = build_authentication_exchange_aad_access_token_for_acr_refresh_token_request( + files=_files, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrRefreshToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def exchange_acr_refresh_token_for_acr_access_token( # pylint: disable=name-too-long + self, body: _models.MultipartBodyParameter, **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange ACR Refresh token for an ACR Access Token. + + :param body: The body of the request. Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def exchange_acr_refresh_token_for_acr_access_token( # pylint: disable=name-too-long + self, body: JSON, **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange ACR Refresh token for an ACR Access Token. + + :param body: The body of the request. Required. + :type body: JSON + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def exchange_acr_refresh_token_for_acr_access_token( # pylint: disable=name-too-long + self, body: Union[_models.MultipartBodyParameter, JSON], **kwargs: Any + ) -> _models.AcrAccessToken: + """Exchange ACR Refresh token for an ACR Access Token. + + :param body: The body of the request. Is either a MultipartBodyParameter type or a JSON type. + Required. + :type body: ~azure.containerregistry._generated.models.MultipartBodyParameter or JSON + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AcrAccessToken] = kwargs.pop("cls", None) + + _body = body.as_dict() if isinstance(body, _Model) else body + _file_fields: list[str] = [] + _data_fields: list[str] = [ + "grantType", + "service", + "tenant", + "refreshToken", + "accessToken", + ] + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) + + _request = build_authentication_exchange_acr_refresh_token_for_acr_access_token_request( + files=_files, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrAccessToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_acr_access_token_from_login(self, *, service: str, scope: str, **kwargs: Any) -> _models.AcrAccessToken: + """Exchange Username, Password and Scope for an ACR Access Token. + + :keyword service: Indicates the name of your Azure container registry. Required. + :paramtype service: str + :keyword scope: Expected to be a valid scope, and can be specified more than once for multiple + scope requests. You can obtain this from the Www-Authenticate response header + from the challenge. Required. + :paramtype scope: str + :return: AcrAccessToken. The AcrAccessToken is compatible with MutableMapping + :rtype: ~azure.containerregistry._generated.models.AcrAccessToken + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AcrAccessToken] = kwargs.pop("cls", None) + + _request = build_authentication_get_acr_access_token_from_login_request( + service=service, + scope=scope, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.AcrErrors, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AcrAccessToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_patch.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_patch.py index 1cdf038ca534..6a01672d58ab 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_patch.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/operations/_patch.py @@ -1,14 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Callable, Dict, List, Optional, TypeVar, Union -from .._serialization import Serializer +from typing import Any, Optional, TypeVar, Union from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -16,123 +17,109 @@ ResourceNotFoundError, map_error, ) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict +from .._utils.serialization import Serializer from .. import models as _models -from ._operations import AuthenticationOperations as AuthenticationOperationsGenerated +from ..operations import AuthenticationOperations as AuthenticationOperationsGenerated + +from .._utils.model_base import _deserialize, _failsafe_deserialize T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -# fmt: off - - - - -def build_exchange_aad_access_token_for_acr_refresh_token_request( - **kwargs # type: Any -): - # type: (...) -> HttpRequest +def build_exchange_aad_access_token_for_acr_refresh_token_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-07-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/oauth2/exchange") # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_exchange_acr_refresh_token_for_acr_access_token_request( - **kwargs # type: Any -): - # type: (...) -> HttpRequest + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_exchange_acr_refresh_token_for_acr_access_token_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-07-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/oauth2/token") # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) # fmt: on class AuthenticationOperations(AuthenticationOperationsGenerated): @distributed_trace - def exchange_aad_access_token_for_acr_refresh_token( + def exchange_aad_access_token_for_acr_refresh_token( # type: ignore[override] # pylint: disable=name-too-long, docstring-keyword-should-match-keyword-only self, - grant_type, # type: Union[str, "_models.PostContentSchemaGrantType"] - service, # type: str - tenant=None, # type: Optional[str] - refresh_token=None, # type: Optional[str] - access_token=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> _models.AcrRefreshToken + grant_type: Union[str, "_models.PostContentSchemaGrantType"], + service: str, + tenant: Optional[str] = None, + refresh_token: Optional[str] = None, + access_token: Optional[str] = None, + **kwargs: Any, + ) -> _models.AcrRefreshToken: """Exchange AAD tokens for an ACR refresh Token. + :param grant_type: Can take a value of access_token_refresh_token, or access_token, or - refresh_token. + refresh_token. :type grant_type: str or ~container_registry.models.PostContentSchemaGrantType :param service: Indicates the name of your Azure container registry. :type service: str :param tenant: AAD tenant associated to the AAD credentials. Default value is None. :type tenant: str :param refresh_token: AAD refresh token, mandatory when grant_type is - access_token_refresh_token or refresh_token. Default value is None. + access_token_refresh_token or refresh_token. Default value is None. :type refresh_token: str :param access_token: AAD access token, mandatory when grant_type is access_token_refresh_token - or access_token. Default value is None. + or access_token. Default value is None. :type access_token: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AcrRefreshToken, or the result of cls(response) :rtype: ~container_registry.models.AcrRefreshToken :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -140,9 +127,10 @@ def exchange_aad_access_token_for_acr_refresh_token( api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # type: str content_type = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/x-www-form-urlencoded") + "content_type", + _headers.pop("Content-Type", "application/x-www-form-urlencoded"), ) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AcrRefreshToken] + cls = kwargs.pop("cls", None) # Construct form data _data = { @@ -161,7 +149,7 @@ def exchange_aad_access_token_for_acr_refresh_token( params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore @@ -172,42 +160,46 @@ def exchange_aad_access_token_for_acr_refresh_token( if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize(_models.AcrErrors, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("AcrRefreshToken", pipeline_response) + deserialized = _deserialize(_models.AcrRefreshToken, response.json()) if cls: return cls(pipeline_response, deserialized, {}) return deserialized @distributed_trace - def exchange_acr_refresh_token_for_acr_access_token( + def exchange_acr_refresh_token_for_acr_access_token( # type: ignore[override] # pylint: disable=name-too-long, docstring-keyword-should-match-keyword-only self, - service, # type: str - scope, # type: str - refresh_token, # type: str - grant_type="refresh_token", # type: Union[str, "_models.TokenGrantType"] - **kwargs # type: Any - ): - # type: (...) -> _models.AcrAccessToken + service: str, + scope: str, + refresh_token: str, + grant_type: Union[str, "_models.TokenGrantType"] = "refresh_token", + **kwargs: Any, + ) -> _models.AcrAccessToken: """Exchange ACR Refresh token for an ACR Access Token. + :param service: Indicates the name of your Azure container registry. :type service: str :param scope: Which is expected to be a valid scope, and can be specified more than once for - multiple scope requests. You obtained this from the Www-Authenticate response header from the - challenge. + multiple scope requests. You obtained this from the Www-Authenticate response header from the + challenge. :type scope: str :param refresh_token: Must be a valid ACR refresh token. :type refresh_token: str :param grant_type: Grant type is expected to be refresh_token. Default value is - "refresh_token". + "refresh_token". :type grant_type: str or ~container_registry.models.TokenGrantType :keyword callable cls: A custom type or function that will be passed the direct response :return: AcrAccessToken, or the result of cls(response) :rtype: ~container_registry.models.AcrAccessToken :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -215,9 +207,10 @@ def exchange_acr_refresh_token_for_acr_access_token( api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) # type: str content_type = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/x-www-form-urlencoded") + "content_type", + _headers.pop("Content-Type", "application/x-www-form-urlencoded"), ) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AcrAccessToken] + cls = kwargs.pop("cls", None) # Construct form data _data = { @@ -235,7 +228,7 @@ def exchange_acr_refresh_token_for_acr_access_token( params=_params, ) path_format_arguments = { - "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore @@ -246,18 +239,18 @@ def exchange_acr_refresh_token_for_acr_access_token( if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AcrErrors, pipeline_response) + error = _failsafe_deserialize(_models.AcrErrors, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("AcrAccessToken", pipeline_response) + deserialized = _deserialize(_models.AcrAccessToken, response.json()) if cls: return cls(pipeline_response, deserialized, {}) return deserialized -__all__ = [ - "AuthenticationOperations" -] # type: List[str] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [ + "AuthenticationOperations", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_models.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_models.py index c19ab18d008f..81e2f2459cf8 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_models.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/_models.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. @@ -71,16 +72,16 @@ def __init__(self, **kwargs: Any) -> None: self._architecture = ArtifactArchitecture(self._architecture) except ValueError: pass - self._created_on = kwargs.get("created_on", None) - self._digest = kwargs.get("digest", None) - self._last_updated_on = kwargs.get("last_updated_on", None) + self._created_on = kwargs.get("created_on", datetime.min) + self._digest = kwargs.get("digest", "") + self._last_updated_on = kwargs.get("last_updated_on", datetime.min) self._operating_system = kwargs.get("operating_system", None) try: self._operating_system = ArtifactOperatingSystem(self._operating_system) except ValueError: pass - self._repository_name = kwargs.get("repository_name", None) - self._registry = kwargs.get("registry", None) + self._repository_name = kwargs.get("repository_name", "") + self._registry = kwargs.get("registry", "") self._size_in_bytes = kwargs.get("size_in_bytes", None) self._tags = kwargs.get("tags", None) self.can_delete = kwargs.get("can_delete") @@ -98,10 +99,12 @@ def _from_generated(cls, generated: ManifestAttributesBase, **kwargs) -> "Artifa operating_system=generated.operating_system, size_in_bytes=generated.size, tags=generated.tags, - can_delete=None if generated.changeable_attributes is None else generated.changeable_attributes.can_delete, - can_read=None if generated.changeable_attributes is None else generated.changeable_attributes.can_read, - can_write=None if generated.changeable_attributes is None else generated.changeable_attributes.can_write, - can_list=None if generated.changeable_attributes is None else generated.changeable_attributes.can_list, + can_delete=( + None if generated.changeable_attributes is None else generated.changeable_attributes.can_delete + ), + can_read=(None if generated.changeable_attributes is None else generated.changeable_attributes.can_read), + can_write=(None if generated.changeable_attributes is None else generated.changeable_attributes.can_write), + can_list=(None if generated.changeable_attributes is None else generated.changeable_attributes.can_list), repository_name=kwargs.get("repository_name"), registry=kwargs.get("registry"), ) @@ -200,11 +203,11 @@ class RepositoryProperties: """Write Permissions for a repository.""" def __init__(self, **kwargs: Any) -> None: - self._created_on = kwargs.get("created_on", None) - self._last_updated_on = kwargs.get("last_updated_on", None) - self._manifest_count = kwargs.get("manifest_count", None) - self._name = kwargs.get("name", None) - self._tag_count = kwargs.get("tag_count", None) + self._created_on: Optional[datetime] = kwargs.get("created_on", None) + self._last_updated_on: Optional[datetime] = kwargs.get("last_updated_on", None) + self._manifest_count: Optional[int] = kwargs.get("manifest_count", None) + self._name: Optional[str] = kwargs.get("name", None) + self._tag_count: Optional[int] = kwargs.get("tag_count", None) self.can_delete = kwargs.get("can_delete") self.can_read = kwargs.get("can_read") self.can_list = kwargs.get("can_list") @@ -243,42 +246,42 @@ def __getattr__(self, name: str) -> Any: return self.__getattribute__(name) @property - def created_on(self) -> datetime: + def created_on(self) -> Optional[datetime]: """Time and date the repository was created. - :rtype: ~datetime.datetime + :rtype: ~datetime.datetime or None """ return self._created_on @property - def last_updated_on(self) -> datetime: + def last_updated_on(self) -> Optional[datetime]: """Time and date the repository was last updated. - :rtype: ~datetime.datetime + :rtype: ~datetime.datetime or None """ return self._last_updated_on @property - def manifest_count(self) -> int: + def manifest_count(self) -> Optional[int]: """Number of manifests in the repository. - :rtype: int + :rtype: int or None """ return self._manifest_count @property - def name(self) -> str: + def name(self) -> Optional[str]: """Name of the repository. - :rtype: str + :rtype: str or None """ return self._name @property - def tag_count(self) -> int: + def tag_count(self) -> Optional[int]: """Number of tags associated with the repository. - :rtype: int + :rtype: int or None """ return self._tag_count @@ -296,11 +299,11 @@ class ArtifactTagProperties: """Write Permissions for a tag.""" def __init__(self, **kwargs: Any) -> None: - self._created_on = kwargs.get("created_on", None) - self._digest = kwargs.get("digest", None) - self._last_updated_on = kwargs.get("last_updated_on", None) - self._name = kwargs.get("name", None) - self._repository_name = kwargs.get("repository_name", None) + self._created_on = kwargs.get("created_on", datetime.min) + self._digest = kwargs.get("digest", "") + self._last_updated_on = kwargs.get("last_updated_on", datetime.min) + self._name = kwargs.get("name", "") + self._repository_name = kwargs.get("repository_name", "") self.can_delete = kwargs.get("can_delete") self.can_read = kwargs.get("can_read") self.can_list = kwargs.get("can_list") diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_anonymous_exchange_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_anonymous_exchange_client.py index 3543382b9a28..af1afd4eee03 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_anonymous_exchange_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_anonymous_exchange_client.py @@ -10,7 +10,7 @@ from azure.core.credentials_async import AsyncTokenCredential from ._async_exchange_client import ExchangeClientAuthenticationPolicy -from .._generated.aio import ContainerRegistry +from .._generated.aio import ContainerRegistryClient as ContainerRegistry from .._generated.aio.operations._patch import AuthenticationOperations from .._generated.models import TokenGrantType from .._helpers import _parse_challenge @@ -54,8 +54,8 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential endpoint = "https://" + endpoint self._endpoint = endpoint self._client = ContainerRegistry( + endpoint=endpoint, credential=AsyncAnonymousAccessCredential(), - url=endpoint, sdk_moniker=USER_AGENT, authentication_policy=ExchangeClientAuthenticationPolicy(), **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_base_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_base_client.py index fd260cdfa3fb..3207b5e4b6db 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_base_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_base_client.py @@ -11,7 +11,7 @@ from ._async_authentication_policy import ContainerRegistryChallengePolicy from ._async_anonymous_exchange_client import AsyncAnonymousAccessCredential -from .._generated.aio import ContainerRegistry +from .._generated.aio import ContainerRegistryClient as ContainerRegistry from .._user_agent import USER_AGENT ClientType = TypeVar("ClientType", bound="ContainerRegistryBaseClient") @@ -39,8 +39,8 @@ class ContainerRegistryBaseClient(object): def __init__(self, endpoint: str, credential: Optional[AsyncTokenCredential], **kwargs: Any) -> None: self._auth_policy = ContainerRegistryChallengePolicy(credential, endpoint, **kwargs) self._client = ContainerRegistry( + endpoint=endpoint, credential=credential or AsyncAnonymousAccessCredential(), - url=endpoint, sdk_moniker=USER_AGENT, authentication_policy=self._auth_policy, **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_container_registry_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_container_registry_client.py index 1da360b7f75e..8e52db1eb508 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_container_registry_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_container_registry_client.py @@ -1,14 +1,27 @@ +# pylint: disable=too-many-lines,line-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines, protected-access import functools import hashlib import json from io import BytesIO -from typing import Any, Dict, IO, Optional, overload, Union, cast, Tuple, MutableMapping, TYPE_CHECKING +from typing import ( + Any, + Dict, + IO, + Optional, + overload, + Union, + cast, + Tuple, + MutableMapping, + TYPE_CHECKING, +) +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.credentials_async import AsyncTokenCredential @@ -22,6 +35,8 @@ from azure.core.pipeline import PipelineResponse from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.core.rest import HttpRequest from ._async_base_client import ContainerRegistryBaseClient from ._async_download_stream import AsyncDownloadBlobStream @@ -51,8 +66,17 @@ ArtifactTagProperties, GetManifestResult, DigestValidationError, + TagAttributesBase, + ManifestAttributesBase, +) + +from .._generated.operations._operations import ( + build_container_registry_get_repositories_request, + build_container_registry_get_manifests_request, ) +from .._generated._utils.model_base import _deserialize + if TYPE_CHECKING: from .._generated.models import ArtifactManifestOrder, ArtifactTagOrder JSON = MutableMapping[str, Any] @@ -94,8 +118,8 @@ def __init__( .. admonition:: Example: .. literalinclude:: ../samples/sample_hello_world_async.py - :start-after: [START create_registry_client] - :end-before: [END create_registry_client] + :start-after: [START create_registry_client_async] + :end-before: [END create_registry_client_async] :language: python :dedent: 8 :caption: Instantiate an instance of `ContainerRegistryClient` @@ -111,7 +135,10 @@ def __init__( self._endpoint = endpoint self._credential = credential super(ContainerRegistryClient, self).__init__( - endpoint=endpoint, credential=credential, credential_scopes=defaultScope, **kwargs + endpoint=endpoint, + credential=credential, + credential_scopes=defaultScope, + **kwargs, ) async def _get_digest_from_tag(self, repository: str, tag: str) -> str: @@ -131,8 +158,8 @@ async def delete_repository(self, repository: str, **kwargs: Any) -> None: .. admonition:: Example: .. literalinclude:: ../samples/sample_hello_world_async.py - :start-after: [START delete_repository] - :end-before: [END delete_repository] + :start-after: [START delete_repository_async] + :end-before: [END delete_repository_async] :language: python :dedent: 8 :caption: Delete a repository from the `ContainerRegistryClient` @@ -152,94 +179,104 @@ def list_repository_names(self, *, results_per_page: Optional[int] = None, **kwa .. admonition:: Example: .. literalinclude:: ../samples/sample_delete_tags_async.py - :start-after: [START list_repository_names] - :end-before: [END list_repository_names] + :start-after: [START list_repository_names_async] + :end-before: [END list_repository_names_async] :language: python :dedent: 8 :caption: List repositories in a container registry account """ last = kwargs.pop("last", None) cls = kwargs.pop("cls", None) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {})) - accept = "application/json" + accept = "application/json" # pylint: disable=unused-variable def prepare_request(next_link=None): # Construct headers header_parameters: Dict[str, Any] = {} - header_parameters["Accept"] = self._client._serialize.header( # pylint: disable=protected-access - "accept", accept, "str" - ) + query_parameters: Dict[str, Any] = {} if not next_link: - # Construct URL - url = "/acr/v1/_catalog" + + _request = build_container_registry_get_repositories_request( + last=last, + n=results_per_page, + api_version=self._client._config.api_version, # pylint: disable=protected-access + headers=header_parameters, + params=query_parameters, + ) path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", - skip_quote=True, + skip_quote=True, # pylint: disable=protected-access ), } - url = self._client._client.format_url(url, **path_format_arguments) # pylint: disable=protected-access - # Construct parameters - query_parameters: Dict[str, Any] = {} - if last is not None: - query_parameters["last"] = self._client._serialize.query( # pylint: disable=protected-access - "last", last, "str" - ) - if results_per_page is not None: - query_parameters["n"] = self._client._serialize.query( # pylint: disable=protected-access - "n", results_per_page, "int" - ) + _request.url = self._client._client.format_url( # pylint: disable=protected-access + _request.url, **path_format_arguments + ) # pylint: disable=protected-access - request = self._client._client.get( # pylint: disable=protected-access - url, query_parameters, header_parameters - ) else: - url = next_link - query_parameters: Dict[str, Any] = {} + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = ( + self._client._config.api_version # pylint: disable=protected-access + ) # pylint: disable=protected-access + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + params=_next_request_params, + ) path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", - skip_quote=True, + skip_quote=True, # pylint: disable=protected-access ), } - url = self._client._client.format_url(url, **path_format_arguments) # pylint: disable=protected-access - request = self._client._client.get( # pylint: disable=protected-access - url, query_parameters, header_parameters - ) - return request + _request.url = self._client.format_url( # pylint: disable=no-member + _request.url, **path_format_arguments + ) # pylint: disable=no-member + + return _request async def extract_data(pipeline_response): - deserialized = self._client._deserialize( # pylint: disable=protected-access - "Repositories", pipeline_response - ) - list_of_elem = deserialized.repositories or [] + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[str], deserialized.get("repositories", [])) if cls: - list_of_elem = cls(list_of_elem) - link = None - if "Link" in pipeline_response.http_response.headers.keys(): - link = _parse_next_link(pipeline_response.http_response.headers["Link"]) - return link, AsyncList(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("link") or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = ( + await self._client._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._client._deserialize.failsafe_deserialize( # pylint: disable=protected-access - AcrErrors, response + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, ) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) return pipeline_response @@ -290,71 +327,77 @@ def list_manifest_properties( ], ) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {})) - accept = "application/json" + accept = "application/json" # pylint: disable=unused-variable def prepare_request(next_link=None): # Construct headers header_parameters: Dict[str, Any] = {} - header_parameters["Accept"] = self._client._serialize.header( # pylint: disable=protected-access - "accept", accept, "str" - ) + query_parameters: Dict[str, Any] = {} if not next_link: - # Construct URL - url = "/acr/v1/{name}/_manifests" + + _request = build_container_registry_get_manifests_request( + name=name, + last=last, + n=results_per_page, + orderby=order_by, + api_version=self._client._config.api_version, # pylint: disable=protected-access + headers=header_parameters, + params=query_parameters, + ) + path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", - skip_quote=True, + skip_quote=True, # pylint: disable=protected-access ), - "name": self._client._serialize.url("name", name, "str"), # pylint: disable=protected-access } - url = self._client._client.format_url(url, **path_format_arguments) # pylint: disable=protected-access - # Construct parameters - query_parameters: Dict[str, Any] = {} - if last is not None: - query_parameters["last"] = self._client._serialize.query( # pylint: disable=protected-access - "last", last, "str" - ) - if results_per_page is not None: - query_parameters["n"] = self._client._serialize.query( # pylint: disable=protected-access - "n", results_per_page, "int" - ) - if order_by is not None: - query_parameters["orderby"] = self._client._serialize.query( # pylint: disable=protected-access - "orderby", order_by, "str" - ) - request = self._client._client.get( # pylint: disable=protected-access - url, query_parameters, header_parameters - ) + _request.url = self._client._client.format_url( # pylint: disable=protected-access + _request.url, **path_format_arguments + ) # pylint: disable=protected-access else: - url = next_link - query_parameters: Dict[str, Any] = {} + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = ( + self._client._config.api_version # pylint: disable=protected-access + ) + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + params=_next_request_params, + ) + path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", - skip_quote=True, + skip_quote=True, # pylint: disable=protected-access ), - "name": self._client._serialize.url("name", name, "str"), # pylint: disable=protected-access } - url = self._client._client.format_url(url, **path_format_arguments) # pylint: disable=protected-access - request = self._client._client.get( # pylint: disable=protected-access - url, query_parameters, header_parameters - ) - return request + _request.url = self._client._client.format_url( # pylint: disable=protected-access + _request.url, **path_format_arguments + ) # pylint: disable=protected-access + return _request async def extract_data(pipeline_response): - deserialized = self._client._deserialize( # pylint: disable=protected-access - "AcrManifests", pipeline_response - ) - list_of_elem = deserialized.manifests or [] + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[ManifestAttributesBase], deserialized.get("manifests", [])) + if cls: list_of_elem = cls(list_of_elem) link = None @@ -374,7 +417,11 @@ async def get_next(next_link=None): error = self._client._deserialize.failsafe_deserialize( # pylint: disable=protected-access AcrErrors, response ) - map_error(status_code=response.status_code, response=response, error_map=error_map) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -510,7 +557,11 @@ def list_tag_properties( ], ) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + } error_map.update(kwargs.pop("error_map", {})) accept = "application/json" @@ -525,9 +576,9 @@ def prepare_request(next_link=None): # Construct URL url = "/acr/v1/{name}/_tags" path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), @@ -560,9 +611,9 @@ def prepare_request(next_link=None): url = next_link query_parameters: Dict[str, Any] = {} path_format_arguments = { - "url": self._client._serialize.url( # pylint: disable=protected-access - "self._client._config.url", - self._client._config.url, # pylint: disable=protected-access + "endpoint": self._client._serialize.url( # pylint: disable=protected-access + "self._client._config.endpoint", + self._client._config.endpoint, # pylint: disable=protected-access "str", skip_quote=True, ), @@ -575,8 +626,13 @@ def prepare_request(next_link=None): return request async def extract_data(pipeline_response): - deserialized = self._client._deserialize("TagList", pipeline_response) # pylint: disable=protected-access - list_of_elem = deserialized.tag_attribute_bases or [] + list_of_elem = ( + _deserialize( + list[TagAttributesBase], + (await pipeline_response.http_response.internal_response.json()).get("tags", []), + ) + or [] + ) if cls: list_of_elem = cls(list_of_elem) link = None @@ -596,7 +652,11 @@ async def get_next(next_link=None): error = self._client._deserialize.failsafe_deserialize( # pylint: disable=protected-access AcrErrors, response ) - map_error(status_code=response.status_code, response=response, error_map=error_map) + map_error( + status_code=response.status_code, + response=response, + error_map=error_map, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -661,13 +721,19 @@ async def update_repository_properties( return RepositoryProperties._from_generated( # pylint: disable=protected-access await self._client.container_registry.update_properties( - repository, value=properties._to_generated(), **kwargs # pylint: disable=protected-access + repository, + value=properties._to_generated(), + **kwargs, # pylint: disable=protected-access ) ) @overload async def update_manifest_properties( - self, repository: str, tag_or_digest: str, properties: ArtifactManifestProperties, **kwargs: Any + self, + repository: str, + tag_or_digest: str, + properties: ArtifactManifestProperties, + **kwargs: Any, ) -> ArtifactManifestProperties: """Set the permission properties for a manifest. @@ -766,7 +832,10 @@ async def update_manifest_properties( tag_or_digest = await self._get_digest_from_tag(repository, tag_or_digest) manifest_properties = await self._client.container_registry.update_manifest_properties( - repository, tag_or_digest, value=properties._to_generated(), **kwargs # pylint: disable=protected-access + repository, + tag_or_digest, + value=properties._to_generated(), + **kwargs, # pylint: disable=protected-access ) return ArtifactManifestProperties._from_generated( # pylint: disable=protected-access manifest_properties.manifest, # type: ignore[arg-type] # The property "manifest" is required in response @@ -776,7 +845,11 @@ async def update_manifest_properties( @overload async def update_tag_properties( - self, repository: str, tag: str, properties: ArtifactTagProperties, **kwargs: Any + self, + repository: str, + tag: str, + properties: ArtifactTagProperties, + **kwargs: Any, ) -> ArtifactTagProperties: """Set the permission properties for a tag. @@ -869,7 +942,10 @@ async def update_tag_properties( properties.can_write = kwargs.pop("can_write", properties.can_write) tag_attributes = await self._client.container_registry.update_tag_attributes( - repository, tag, value=properties._to_generated(), **kwargs # pylint: disable=protected-access + repository, + tag, + value=properties._to_generated(), + **kwargs, # pylint: disable=protected-access ) return ArtifactTagProperties._from_generated( # pylint: disable=protected-access tag_attributes.tag, # type: ignore[arg-type] # The property "tag" is required in response @@ -912,7 +988,7 @@ async def set_manifest( if tag_or_digest is None: tag_or_digest = _compute_digest(data) - response_headers = await self._client.container_registry.create_manifest( + response_headers = await self._client.container_registry.create_manifest( # type: ignore[func-returns-value] # pylint: disable=line-too-long name=repository, reference=tag_or_digest, payload=data, @@ -920,7 +996,7 @@ async def set_manifest( cls=_return_response_headers, **kwargs, ) - digest = response_headers["Docker-Content-Digest"] + digest = response_headers["Docker-Content-Digest"] # type: ignore[index] if not _validate_digest(data, digest): raise DigestValidationError("The server-computed digest does not match the client-computed digest.") except Exception as e: @@ -1001,7 +1077,7 @@ async def upload_blob(self, repository: str, data: IO[bytes], **kwargs: Any) -> complete_upload_response_headers = cast( Dict[str, str], await self._client.container_registry_blob.complete_upload( - digest=digest, next_link=location, cls=_return_response_headers, **kwargs + location, digest=digest, cls=_return_response_headers, **kwargs ), ) if digest != complete_upload_response_headers["Docker-Content-Digest"]: @@ -1022,7 +1098,7 @@ async def _upload_blob_chunk(self, location: str, data: IO[bytes], **kwargs) -> response_headers = cast( Dict[str, str], await self._client.container_registry_blob.upload_chunk( - location, buffer_stream, cls=_return_response_headers, **kwargs + location, buffer_stream, cls=_return_response_headers, **kwargs # type: ignore[arg-type] ), ) location = response_headers["Location"] @@ -1050,7 +1126,11 @@ async def download_blob(self, repository: str, digest: str, **kwargs: Any) -> As first_chunk, headers = cast( Tuple[PipelineResponse, Dict[str, str]], await self._client.container_registry_blob.get_chunk( - repository, digest, range_header=f"bytes=0-{end_range}", cls=_return_response_and_headers, **kwargs + repository, + digest, + range=f"bytes=0-{end_range}", + cls=_return_response_and_headers, + **kwargs, ), ) blob_size = _get_blob_size(headers) diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_download_stream.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_download_stream.py index cb12a9c70af5..9f01c8570c2c 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_download_stream.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_download_stream.py @@ -58,7 +58,10 @@ async def _yield_data(self) -> bytes: async def _download_chunk(self) -> PipelineResponse: end_range = self._downloaded + self._chunk_size - 1 range_header = f"bytes={self._downloaded}-{end_range}" - next_chunk, headers = cast(Tuple[PipelineResponse, Dict[str, str]], await self._next(range_header=range_header)) + next_chunk, headers = cast( + Tuple[PipelineResponse, Dict[str, str]], + await self._next(range_header=range_header), + ) self._downloaded += int(headers["Content-Length"]) return next_chunk diff --git a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_exchange_client.py b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_exchange_client.py index 4bd6085e5be9..100eaa4fa726 100644 --- a/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_exchange_client.py +++ b/sdk/containerregistry/azure-containerregistry/azure/containerregistry/aio/_async_exchange_client.py @@ -10,7 +10,7 @@ from azure.core.pipeline import PipelineRequest, PipelineResponse from azure.core.pipeline.policies import SansIOHTTPPolicy -from .._generated.aio import ContainerRegistry +from .._generated.aio import ContainerRegistryClient as ContainerRegistry from .._generated.aio.operations._patch import AuthenticationOperations from .._generated.models import PostContentSchemaGrantType from .._helpers import _parse_challenge, _parse_exp_time @@ -46,8 +46,8 @@ def __init__(self, endpoint: str, credential: AsyncTokenCredential, **kwargs: An self._endpoint = endpoint self.credential_scopes = kwargs.get("credential_scopes", ["https://management.core.windows.net/.default"]) self._client = ContainerRegistry( + endpoint=endpoint, credential=credential, - url=endpoint, sdk_moniker=USER_AGENT, authentication_policy=ExchangeClientAuthenticationPolicy(), **kwargs diff --git a/sdk/containerregistry/azure-containerregistry/pyproject.toml b/sdk/containerregistry/azure-containerregistry/pyproject.toml index e9b975a7d2b3..516a8ab574e8 100644 --- a/sdk/containerregistry/azure-containerregistry/pyproject.toml +++ b/sdk/containerregistry/azure-containerregistry/pyproject.toml @@ -1,3 +1,66 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-containerregistry" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Corporation Azure Container Registry Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.containerregistry._generated._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +include = [ + "azure*", +] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] pyright = false black = true diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images.py b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images.py index 29099bc29a41..73894969a7fd 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images.py @@ -26,6 +26,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import os from dotenv import find_dotenv, load_dotenv from azure.containerregistry import ContainerRegistryClient, ArtifactManifestOrder @@ -48,7 +49,8 @@ def delete_images(self): # Keep the three most recent images, delete everything else manifest_count = 0 for manifest in client.list_manifest_properties( - repository, order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING + repository, + order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING, ): manifest_count += 1 if manifest_count > 3: diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images_async.py b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images_async.py index f3bab0cef00f..6a9021cfaccf 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images_async.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_images_async.py @@ -26,6 +26,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import asyncio import os from dotenv import find_dotenv, load_dotenv @@ -49,7 +50,8 @@ async def delete_images(self): # Keep the three most recent images, delete everything else manifest_count = 0 async for manifest in client.list_manifest_properties( - repository, order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING + repository, + order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING, ): manifest_count += 1 if manifest_count > 3: diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags.py b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags.py index d70661093eea..53d542c3f796 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags.py @@ -26,6 +26,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import os from dotenv import find_dotenv, load_dotenv from azure.containerregistry import ContainerRegistryClient, ArtifactTagOrder @@ -51,7 +52,8 @@ def delete_tags(self): # Keep the three most recent tags, delete everything else tag_count = 0 for tag in client.list_tag_properties( - repository_name, order_by=ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING + repository_name, + order_by=ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING, ): tag_count += 1 if tag_count > 3: diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags_async.py b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags_async.py index bcccdc2f16b3..d670321acd27 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags_async.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_delete_tags_async.py @@ -26,6 +26,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import asyncio import os from dotenv import find_dotenv, load_dotenv @@ -43,17 +44,18 @@ def __init__(self): async def delete_tags(self): load_registry(self.endpoint) - # [START list_repository_names] + # [START list_repository_names_async] async with ContainerRegistryClient(self.endpoint, self.credential) as client: # Iterate through all the repositories async for repository_name in client.list_repository_names(): print(repository_name) - # [END list_repository_names] + # [END list_repository_names_async] # Keep the three most recent tags, delete everything else tag_count = 0 async for tag in client.list_tag_properties( - repository_name, order_by=ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING + repository_name, + order_by=ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING, ): tag_count += 1 if tag_count > 3: diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world.py b/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world.py index 06b3a88495d3..0a6e07fc2ab6 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world.py @@ -26,6 +26,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import os from dotenv import find_dotenv, load_dotenv from azure.containerregistry import ContainerRegistryClient diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world_async.py b/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world_async.py index 89b2bd582479..042c690f8e35 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world_async.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_hello_world_async.py @@ -26,6 +26,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import asyncio import os from dotenv import find_dotenv, load_dotenv @@ -43,9 +44,9 @@ def __init__(self): async def basic_sample(self): load_registry(self.endpoint) # Instantiate an instance of ContainerRegistryClient - # [START create_registry_client] + # [START create_registry_client_async] async with ContainerRegistryClient(self.endpoint, self.credential) as client: - # [END create_registry_client] + # [END create_registry_client_async] # Iterate through all the repositories async for repository_name in client.list_repository_names(): print(repository_name) @@ -60,9 +61,9 @@ async def basic_sample(self): ) print("Deleting " + repository_name) - # [START delete_repository] + # [START delete_repository_async] await client.delete_repository(repository_name) - # [END delete_repository] + # [END delete_repository_async] async def main(): diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags.py b/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags.py index c9f99f1884d8..fb1c179c6473 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags.py @@ -28,6 +28,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import os from dotenv import find_dotenv, load_dotenv from azure.containerregistry import ContainerRegistryClient diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags_async.py b/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags_async.py index 8812b24c443c..28f2c8a52749 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags_async.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_list_tags_async.py @@ -28,6 +28,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import asyncio import os from dotenv import find_dotenv, load_dotenv @@ -42,7 +43,7 @@ def __init__(self): async def list_tags(self): endpoint = os.environ["CONTAINERREGISTRY_ANONREGISTRY_ENDPOINT"] load_registry(endpoint) - # [START list_tags_anonymous] + # [START list_tags_anonymous_async] async with ContainerRegistryClient(endpoint) as anon_client: manifest = await anon_client.get_manifest_properties("library/hello-world", "latest") if manifest.tags: @@ -50,7 +51,7 @@ async def list_tags(self): # Iterate through all the tags for tag in manifest.tags: print(tag) - # [END list_tags_anonymous] + # [END list_tags_anonymous_async] async def main(): diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image.py b/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image.py index c0084008dbc5..8fa34ba9aea3 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image.py @@ -18,6 +18,7 @@ Set the environment variables with your own values before running the sample: 1) CONTAINERREGISTRY_ENDPOINT - The URL of your Container Registry account """ + import os import json from io import BytesIO @@ -168,7 +169,10 @@ def set_get_docker_image(self): } # Set the image with one custom media type client.set_manifest( - repository_name, docker_manifest, tag="sample", media_type=str(docker_manifest["mediaType"]) + repository_name, + docker_manifest, + tag="sample", + media_type=str(docker_manifest["mediaType"]), ) # Get the image diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image_async.py b/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image_async.py index 5c27d5d06608..6c4617fd0bd0 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image_async.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image_async.py @@ -18,6 +18,7 @@ Set the environment variables with your own values before running the sample: 1) CONTAINERREGISTRY_ANONREGISTRY_ENDPOINT - The URL of your Container Registry account for anonymous access """ + import asyncio import os import json @@ -75,9 +76,7 @@ async def set_get_oci_image(self): # Set the image manifest_digest = await client.set_manifest(repository_name, oci_manifest, tag="latest") print(f"Uploaded manifest: digest - {manifest_digest}") - # [END upload_blob_and_manifest] - # [START download_blob_and_manifest] # Get the image get_manifest_result = await client.get_manifest(repository_name, "latest") received_manifest = get_manifest_result.manifest @@ -147,7 +146,10 @@ async def set_get_docker_image(self): } # Set the image with one custom media type await client.set_manifest( - repository_name, docker_manifest, tag="sample", media_type=str(docker_manifest["mediaType"]) + repository_name, + docker_manifest, + tag="sample", + media_type=str(docker_manifest["mediaType"]), ) # Get the image diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties.py b/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties.py index 0558193bcf06..11ec15ff0417 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties.py @@ -18,7 +18,7 @@ Set the environment variables with your own values before running the sample: 1) CONTAINERREGISTRY_ENDPOINT - The URL of your Container Registry account - + This sample assumes your registry has a repository "library/hello-world" with image tagged "v1", run load_registry() if you don't have. Set the environment variables with your own values before running load_registry(): @@ -27,6 +27,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import os from dotenv import find_dotenv, load_dotenv from azure.containerregistry import ContainerRegistryClient diff --git a/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties_async.py b/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties_async.py index 14e4d626caf4..22a4e5321107 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties_async.py +++ b/sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties_async.py @@ -27,6 +27,7 @@ 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret """ + import asyncio import os from dotenv import find_dotenv, load_dotenv diff --git a/sdk/containerregistry/azure-containerregistry/samples/utilities.py b/sdk/containerregistry/azure-containerregistry/samples/utilities.py index 3e49e15dd53c..09199cc0c336 100644 --- a/sdk/containerregistry/azure-containerregistry/samples/utilities.py +++ b/sdk/containerregistry/azure-containerregistry/samples/utilities.py @@ -17,6 +17,7 @@ - get_credential(): get credential of the ContainerRegistryClient It is not a file expected to run independently. """ + import json import os from io import BytesIO @@ -68,7 +69,10 @@ def _import_images(endpoint, repository, tags): } for tag in tags: client.set_manifest( - repository, docker_manifest, tag=tag, media_type="application/vnd.docker.distribution.manifest.v2+json" + repository, + docker_manifest, + tag=tag, + media_type="application/vnd.docker.distribution.manifest.v2+json", ) diff --git a/sdk/containerregistry/azure-containerregistry/setup.py b/sdk/containerregistry/azure-containerregistry/setup.py deleted file mode 100644 index b8908f3673f1..000000000000 --- a/sdk/containerregistry/azure-containerregistry/setup.py +++ /dev/null @@ -1,66 +0,0 @@ -from setuptools import setup, find_packages -import os -from io import open -import re - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-containerregistry" -PACKAGE_PPRINT_NAME = "Azure Container Registry" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace("-", "/") -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace("-", ".") - -# 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*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) -if not version: - raise RuntimeError("Cannot find version information") - -with open("README.md", encoding="utf-8") as f: - long_description = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - include_package_data=True, - description=f"Microsoft Azure {PACKAGE_PPRINT_NAME} Client Library for Python", - # ensure that these are updated to reflect the package owners' information - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/Azure/azure-sdk-for-python", - keywords="azure, azure sdk", - author="Microsoft Corporation", - author_email="azuresdkengsysadmins@microsoft.com", - license="MIT License", - # ensure that the development status reflects the status of your package - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "License :: OSI Approved :: MIT License", - ], - packages=find_packages( - exclude=[ - "tests", - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - ] - ), - python_requires=">=3.8", - install_requires=[ - "azure-core>=1.27.0,<2.0.0", - "isodate>=0.6.0", - ], - project_urls={ - "Bug Reports": "https://github.com/Azure/azure-sdk-for-python/issues", - "Source": "https://github.com/Azure/azure-sdk-for-python", - }, -) diff --git a/sdk/containerregistry/azure-containerregistry/tests/asynctestcase.py b/sdk/containerregistry/azure-containerregistry/tests/asynctestcase.py index 07d1a32318f1..2eb4db566c83 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/asynctestcase.py +++ b/sdk/containerregistry/azure-containerregistry/tests/asynctestcase.py @@ -12,7 +12,12 @@ from azure.identity.aio import DefaultAzureCredential, ClientSecretCredential from azure.identity import AzureAuthorityHosts -from testcase import ContainerRegistryTestClass, get_audience, get_authority, get_credential +from testcase import ( + ContainerRegistryTestClass, + get_audience, + get_authority, + get_credential, +) logger = logging.getLogger() diff --git a/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_artifacts.py b/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_artifacts.py index a9a3f913c8da..2dd0a43e3335 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_artifacts.py +++ b/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_artifacts.py @@ -4,7 +4,9 @@ # ------------------------------------ from devtools_testutils.perfstress_tests import PerfStressTest from azure.containerregistry import ContainerRegistryClient -from azure.containerregistry.aio import ContainerRegistryClient as AsyncContainerRegistryClient +from azure.containerregistry.aio import ( + ContainerRegistryClient as AsyncContainerRegistryClient, +) class ListArtifactsTest(PerfStressTest): diff --git a/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_repositories.py b/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_repositories.py index cc2aef648800..3bbb0412725b 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_repositories.py +++ b/sdk/containerregistry/azure-containerregistry/tests/perfstress_tests/list_repositories.py @@ -4,7 +4,9 @@ # ------------------------------------ from devtools_testutils.perfstress_tests import PerfStressTest from azure.containerregistry import ContainerRegistryClient -from azure.containerregistry.aio import ContainerRegistryClient as AsyncContainerRegistryClient +from azure.containerregistry.aio import ( + ContainerRegistryClient as AsyncContainerRegistryClient, +) class ListRepositoriesTest(PerfStressTest): diff --git a/sdk/containerregistry/azure-containerregistry/tests/test_anon_access.py b/sdk/containerregistry/azure-containerregistry/tests/test_anon_access.py index 0df708cfb1a7..39a398ed86fb 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/test_anon_access.py +++ b/sdk/containerregistry/azure-containerregistry/tests/test_anon_access.py @@ -209,12 +209,16 @@ def test_set_api_version(): assert client._client._config.api_version == "2021-07-01" with ContainerRegistryClient( - endpoint=containerregistry_endpoint, audience="https://microsoft.com", api_version="2019-08-15-preview" + endpoint=containerregistry_endpoint, + audience="https://microsoft.com", + api_version="2019-08-15-preview", ) as client: assert client._client._config.api_version == "2019-08-15-preview" with pytest.raises(ValueError): with ContainerRegistryClient( - endpoint=containerregistry_endpoint, audience="https://microsoft.com", api_version="2019-08-15" + endpoint=containerregistry_endpoint, + audience="https://microsoft.com", + api_version="2019-08-15", ) as client: pass diff --git a/sdk/containerregistry/azure-containerregistry/tests/test_anon_access_async.py b/sdk/containerregistry/azure-containerregistry/tests/test_anon_access_async.py index 01013d38d607..61a48c393f1e 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/test_anon_access_async.py +++ b/sdk/containerregistry/azure-containerregistry/tests/test_anon_access_async.py @@ -211,12 +211,16 @@ async def test_set_api_version(): assert client._client._config.api_version == "2021-07-01" async with ContainerRegistryClient( - endpoint=containerregistry_endpoint, audience="https://microsoft.com", api_version="2019-08-15-preview" + endpoint=containerregistry_endpoint, + audience="https://microsoft.com", + api_version="2019-08-15-preview", ) as client: assert client._client._config.api_version == "2019-08-15-preview" with pytest.raises(ValueError): async with ContainerRegistryClient( - endpoint=containerregistry_endpoint, audience="https://microsoft.com", api_version="2019-08-15" + endpoint=containerregistry_endpoint, + audience="https://microsoft.com", + api_version="2019-08-15", ) as client: pass diff --git a/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client.py b/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client.py index 72290b8054de..5f779e48078d 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client.py +++ b/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. @@ -22,7 +23,11 @@ ContainerRegistryClient, DigestValidationError, ) -from azure.containerregistry._helpers import DOCKER_MANIFEST, OCI_IMAGE_MANIFEST, DEFAULT_CHUNK_SIZE +from azure.containerregistry._helpers import ( + DOCKER_MANIFEST, + OCI_IMAGE_MANIFEST, + DEFAULT_CHUNK_SIZE, +) from azure.core.exceptions import ( ResourceNotFoundError, ClientAuthenticationError, @@ -33,7 +38,13 @@ from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineRequest from azure.identity import AzureAuthorityHosts -from testcase import ContainerRegistryTestClass, get_authority, get_audience, is_public_endpoint, is_china_endpoint +from testcase import ( + ContainerRegistryTestClass, + get_authority, + get_audience, + is_public_endpoint, + is_china_endpoint, +) from constants import HELLO_WORLD, DOES_NOT_EXIST from preparer import acr_preparer from devtools_testutils import recorded_by_proxy @@ -261,7 +272,12 @@ def test_update_manifest_properties_kwargs(self, containerregistry_endpoint): self.sleep(5) with self.create_registry_client(containerregistry_endpoint) as client: received = client.update_manifest_properties( - repo, tag, can_delete=False, can_read=False, can_write=False, can_list=False + repo, + tag, + can_delete=False, + can_read=False, + can_write=False, + can_list=False, ) self.assert_all_properties(received, False) @@ -318,7 +334,12 @@ def test_update_tag_properties_kwargs(self, containerregistry_endpoint): self.sleep(5) with self.create_registry_client(containerregistry_endpoint) as client: received = client.update_tag_properties( - repo, tag, can_delete=False, can_read=False, can_write=False, can_list=False + repo, + tag, + can_delete=False, + can_read=False, + can_write=False, + can_list=False, ) self.assert_all_properties(received, False) @@ -424,7 +445,9 @@ def test_delete_manifest_does_not_exist(self, containerregistry_endpoint): @acr_preparer() @recorded_by_proxy def test_expiration_time_parsing(self, containerregistry_endpoint): - from azure.containerregistry._authentication_policy import ContainerRegistryChallengePolicy + from azure.containerregistry._authentication_policy import ( + ContainerRegistryChallengePolicy, + ) with self.create_registry_client(containerregistry_endpoint) as client: for repo in client.list_repository_names(): @@ -451,7 +474,9 @@ def construct_container_registry_client(self, **kwargs): credential = self.get_credential(authority=authority) with ContainerRegistryClient( - endpoint=containerregistry_endpoint, credential=credential, audience="https://microsoft.com" + endpoint=containerregistry_endpoint, + credential=credential, + audience="https://microsoft.com", ) as client: with pytest.raises(ClientAuthenticationError): properties = client.get_repository_properties(HELLO_WORLD) @@ -516,7 +541,12 @@ def test_set_oci_manifest_without_spaces(self, containerregistry_endpoint): pytest.skip("This test is for testing test_set_docker_manifest in playback.") repo = self.get_resource_name("repo") - path = os.path.join(self.get_test_directory(), "data", "oci_artifact", "manifest_without_spaces.json") + path = os.path.join( + self.get_test_directory(), + "data", + "oci_artifact", + "manifest_without_spaces.json", + ) with self.create_registry_client(containerregistry_endpoint) as client: self.upload_oci_manifest_prerequisites(repo, client) @@ -589,7 +619,12 @@ def test_set_docker_manifest_without_spaces(self, containerregistry_endpoint): pytest.skip("This test is for testing test_set_docker_manifest in playback.") repo = self.get_resource_name("repo") - path = os.path.join(self.get_test_directory(), "data", "docker_artifact", "manifest_without_spaces.json") + path = os.path.join( + self.get_test_directory(), + "data", + "docker_artifact", + "manifest_without_spaces.json", + ) with self.create_registry_client(containerregistry_endpoint) as client: self.upload_docker_manifest_prerequisites(repo, client) @@ -723,7 +758,9 @@ def test_set_audience(self, containerregistry_endpoint): valid_audience = get_audience(authority) with ContainerRegistryClient( - endpoint=containerregistry_endpoint, credential=credential, audience=valid_audience + endpoint=containerregistry_endpoint, + credential=credential, + audience=valid_audience, ) as client: for repo in client.list_repository_names(): pass @@ -731,7 +768,9 @@ def test_set_audience(self, containerregistry_endpoint): if valid_audience == get_audience(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD): invalid_audience = get_audience(AzureAuthorityHosts.AZURE_GOVERNMENT) with ContainerRegistryClient( - endpoint=containerregistry_endpoint, credential=credential, audience=invalid_audience + endpoint=containerregistry_endpoint, + credential=credential, + audience=invalid_audience, ) as client: with pytest.raises(ClientAuthenticationError): for repo in client.list_repository_names(): @@ -796,12 +835,15 @@ def send_in_get_manifest(request: PipelineRequest, **kwargs) -> MagicMock: "Content-Type": content_type, "Content-Length": len(b"hello world"), }, + content_type=content_type, read=read, json=json, + text=self.text, ) with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MagicMock(send=send_in_set_manifest) + endpoint=self.containerregistry_endpoint, + transport=MagicMock(send=send_in_set_manifest), ) as client: with pytest.raises(DigestValidationError) as exp: manifest = {"hello": "world"} @@ -809,7 +851,8 @@ def send_in_get_manifest(request: PipelineRequest, **kwargs) -> MagicMock: assert str(exp.value) == "The server-computed digest does not match the client-computed digest." with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MagicMock(send=send_in_get_manifest) + endpoint=self.containerregistry_endpoint, + transport=MagicMock(send=send_in_get_manifest), ) as client: with pytest.raises(DigestValidationError) as exp: digest = hashlib.sha256(b"hello world").hexdigest() @@ -851,14 +894,16 @@ def send_in_download_blob(request: PipelineRequest, **kwargs) -> MagicMock: ) with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MagicMock(send=send_in_upload_blob) + endpoint=self.containerregistry_endpoint, + transport=MagicMock(send=send_in_upload_blob), ) as client: with pytest.raises(DigestValidationError) as exp: client.upload_blob("test-repo", BytesIO(b'{"hello": "world"}')) assert str(exp.value) == "The server-computed digest does not match the client-computed digest." with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MagicMock(send=send_in_download_blob) + endpoint=self.containerregistry_endpoint, + transport=MagicMock(send=send_in_download_blob), ) as client: digest = hashlib.sha256(b"hello world").hexdigest() stream = client.download_blob("test-repo", f"sha256:{digest}") diff --git a/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client_async.py b/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client_async.py index 384afe9ddcb3..6a48e7a2e035 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client_async.py +++ b/sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. @@ -22,7 +23,11 @@ DigestValidationError, ) from azure.containerregistry.aio import ContainerRegistryClient -from azure.containerregistry._helpers import DOCKER_MANIFEST, OCI_IMAGE_MANIFEST, DEFAULT_CHUNK_SIZE +from azure.containerregistry._helpers import ( + DOCKER_MANIFEST, + OCI_IMAGE_MANIFEST, + DEFAULT_CHUNK_SIZE, +) from azure.core.exceptions import ( ResourceNotFoundError, ClientAuthenticationError, @@ -262,7 +267,12 @@ async def test_update_manifest_properties_kwargs(self, containerregistry_endpoin self.sleep(5) async with self.create_registry_client(containerregistry_endpoint) as client: received = await client.update_manifest_properties( - repo, tag, can_delete=False, can_read=False, can_write=False, can_list=False + repo, + tag, + can_delete=False, + can_read=False, + can_write=False, + can_list=False, ) self.assert_all_properties(received, False) @@ -319,7 +329,12 @@ async def test_update_tag_properties_kwargs(self, containerregistry_endpoint): self.sleep(5) async with self.create_registry_client(containerregistry_endpoint) as client: received = await client.update_tag_properties( - repo, tag, can_delete=False, can_read=False, can_write=False, can_list=False + repo, + tag, + can_delete=False, + can_read=False, + can_write=False, + can_list=False, ) self.assert_all_properties(received, False) @@ -429,7 +444,9 @@ async def test_delete_manifest_does_not_exist(self, containerregistry_endpoint): @acr_preparer() @recorded_by_proxy_async async def test_expiration_time_parsing(self, containerregistry_endpoint): - from azure.containerregistry.aio._async_authentication_policy import ContainerRegistryChallengePolicy + from azure.containerregistry.aio._async_authentication_policy import ( + ContainerRegistryChallengePolicy, + ) async with self.create_registry_client(containerregistry_endpoint) as client: async for repo in client.list_repository_names(): @@ -455,7 +472,9 @@ async def test_construct_container_registry_client(self, **kwargs): credential = self.get_credential(authority=authority) async with ContainerRegistryClient( - endpoint=containerregistry_endpoint, credential=credential, audience="https://microsoft.com" + endpoint=containerregistry_endpoint, + credential=credential, + audience="https://microsoft.com", ) as client: with pytest.raises(ClientAuthenticationError): properties = await client.get_repository_properties(HELLO_WORLD) @@ -520,7 +539,12 @@ async def test_set_oci_manifest_without_spaces(self, containerregistry_endpoint) pytest.skip("This test is for testing test_set_docker_manifest in playback.") repo = self.get_resource_name("repo") - path = os.path.join(self.get_test_directory(), "data", "oci_artifact", "manifest_without_spaces.json") + path = os.path.join( + self.get_test_directory(), + "data", + "oci_artifact", + "manifest_without_spaces.json", + ) async with self.create_registry_client(containerregistry_endpoint) as client: await self.upload_oci_manifest_prerequisites(repo, client) @@ -593,7 +617,12 @@ async def test_set_docker_manifest_without_spaces(self, containerregistry_endpoi pytest.skip("This test is for testing test_set_docker_manifest in playback.") repo = self.get_resource_name("repo") - path = os.path.join(self.get_test_directory(), "data", "docker_artifact", "manifest_without_spaces.json") + path = os.path.join( + self.get_test_directory(), + "data", + "docker_artifact", + "manifest_without_spaces.json", + ) async with self.create_registry_client(containerregistry_endpoint) as client: await self.upload_docker_manifest_prerequisites(repo, client) @@ -727,7 +756,9 @@ async def test_set_audience(self, containerregistry_endpoint): valid_audience = get_audience(authority) async with ContainerRegistryClient( - endpoint=containerregistry_endpoint, credential=credential, audience=valid_audience + endpoint=containerregistry_endpoint, + credential=credential, + audience=valid_audience, ) as client: async for repo in client.list_repository_names(): pass @@ -735,7 +766,9 @@ async def test_set_audience(self, containerregistry_endpoint): if valid_audience == get_audience(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD): invalid_audience = get_audience(AzureAuthorityHosts.AZURE_GOVERNMENT) async with ContainerRegistryClient( - endpoint=containerregistry_endpoint, credential=credential, audience=invalid_audience + endpoint=containerregistry_endpoint, + credential=credential, + audience=invalid_audience, ) as client: with pytest.raises(ClientAuthenticationError): async for repo in client.list_repository_names(): @@ -812,12 +845,15 @@ async def send_in_get_manifest(request: PipelineRequest, **kwargs) -> MyMagicMoc "Content-Type": content_type, "Content-Length": len(b"hello world"), }, + content_type=content_type, read=read, json=json, + text=self.text, ) async with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MyMagicMock(send=send_in_set_manifest) + endpoint=self.containerregistry_endpoint, + transport=MyMagicMock(send=send_in_set_manifest), ) as client: with pytest.raises(DigestValidationError) as exp: manifest = {"hello": "world"} @@ -825,7 +861,8 @@ async def send_in_get_manifest(request: PipelineRequest, **kwargs) -> MyMagicMoc assert str(exp.value) == "The server-computed digest does not match the client-computed digest." async with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MyMagicMock(send=send_in_get_manifest) + endpoint=self.containerregistry_endpoint, + transport=MyMagicMock(send=send_in_get_manifest), ) as client: with pytest.raises(DigestValidationError) as exp: digest = hashlib.sha256(b"hello world").hexdigest() @@ -868,14 +905,16 @@ async def send_in_download_blob(request: PipelineRequest, **kwargs) -> MyMagicMo ) async with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MyMagicMock(send=send_in_upload_blob) + endpoint=self.containerregistry_endpoint, + transport=MyMagicMock(send=send_in_upload_blob), ) as client: with pytest.raises(DigestValidationError) as exp: await client.upload_blob("test-repo", BytesIO(b'{"hello": "world"}')) assert str(exp.value) == "The server-computed digest does not match the client-computed digest." async with ContainerRegistryClient( - endpoint=self.containerregistry_endpoint, transport=MyMagicMock(send=send_in_download_blob) + endpoint=self.containerregistry_endpoint, + transport=MyMagicMock(send=send_in_download_blob), ) as client: digest = hashlib.sha256(b"hello world").hexdigest() stream = await client.download_blob("test-repo", f"sha256:{digest}") diff --git a/sdk/containerregistry/azure-containerregistry/tests/testcase.py b/sdk/containerregistry/azure-containerregistry/tests/testcase.py index 3c69981de8ef..a1a25a3693c3 100644 --- a/sdk/containerregistry/azure-containerregistry/tests/testcase.py +++ b/sdk/containerregistry/azure-containerregistry/tests/testcase.py @@ -12,7 +12,11 @@ from azure.containerregistry._helpers import _is_tag from azure.identity import AzureAuthorityHosts, ClientSecretCredential -from devtools_testutils import AzureRecordedTestCase, FakeTokenCredential, get_credential +from devtools_testutils import ( + AzureRecordedTestCase, + FakeTokenCredential, + get_credential, +) logger = logging.getLogger() diff --git a/sdk/containerregistry/azure-containerregistry/tsp-location.yaml b/sdk/containerregistry/azure-containerregistry/tsp-location.yaml new file mode 100644 index 000000000000..86097a1e0176 --- /dev/null +++ b/sdk/containerregistry/azure-containerregistry/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/containerregistry/data-plane/Registry +commit: 9840b830d86d2000dd8d6dc21f63444a67b04e76 +repo: Azure/azure-rest-api-specs +additionalDirectories: